babylon.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var result = new Color3(0.0, 0.0, 0.0);
  1781. Color3.LerpToRef(start, end, amount, result);
  1782. return result;
  1783. };
  1784. /**
  1785. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1786. * @param left defines the start value
  1787. * @param right defines the end value
  1788. * @param amount defines the gradient factor
  1789. * @param result defines the Color3 object where to store the result
  1790. */
  1791. Color3.LerpToRef = function (left, right, amount, result) {
  1792. result.r = left.r + ((right.r - left.r) * amount);
  1793. result.g = left.g + ((right.g - left.g) * amount);
  1794. result.b = left.b + ((right.b - left.b) * amount);
  1795. };
  1796. /**
  1797. * Returns a Color3 value containing a red color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Red = function () { return new Color3(1, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a green color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.Green = function () { return new Color3(0, 1, 0); };
  1806. /**
  1807. * Returns a Color3 value containing a blue color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1811. /**
  1812. * Returns a Color3 value containing a black color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Black = function () { return new Color3(0, 0, 0); };
  1816. /**
  1817. * Returns a Color3 value containing a white color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.White = function () { return new Color3(1, 1, 1); };
  1821. /**
  1822. * Returns a Color3 value containing a purple color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a magenta color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1831. /**
  1832. * Returns a Color3 value containing a yellow color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1836. /**
  1837. * Returns a Color3 value containing a gray color
  1838. * @returns a new Color3 object
  1839. */
  1840. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1841. /**
  1842. * Returns a Color3 value containing a teal color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1846. /**
  1847. * Returns a Color3 value containing a random color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1851. return Color3;
  1852. }());
  1853. BABYLON.Color3 = Color3;
  1854. /**
  1855. * Class used to hold a RBGA color
  1856. */
  1857. var Color4 = /** @class */ (function () {
  1858. /**
  1859. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1860. * @param r defines the red component (between 0 and 1, default is 0)
  1861. * @param g defines the green component (between 0 and 1, default is 0)
  1862. * @param b defines the blue component (between 0 and 1, default is 0)
  1863. * @param a defines the alpha component (between 0 and 1, default is 1)
  1864. */
  1865. function Color4(
  1866. /**
  1867. * Defines the red component (between 0 and 1, default is 0)
  1868. */
  1869. r,
  1870. /**
  1871. * Defines the green component (between 0 and 1, default is 0)
  1872. */
  1873. g,
  1874. /**
  1875. * Defines the blue component (between 0 and 1, default is 0)
  1876. */
  1877. b,
  1878. /**
  1879. * Defines the alpha component (between 0 and 1, default is 1)
  1880. */
  1881. a) {
  1882. if (r === void 0) { r = 0; }
  1883. if (g === void 0) { g = 0; }
  1884. if (b === void 0) { b = 0; }
  1885. if (a === void 0) { a = 1; }
  1886. this.r = r;
  1887. this.g = g;
  1888. this.b = b;
  1889. this.a = a;
  1890. }
  1891. // Operators
  1892. /**
  1893. * Adds in place the given Color4 values to the current Color4 object
  1894. * @param right defines the second operand
  1895. * @returns the current updated Color4 object
  1896. */
  1897. Color4.prototype.addInPlace = function (right) {
  1898. this.r += right.r;
  1899. this.g += right.g;
  1900. this.b += right.b;
  1901. this.a += right.a;
  1902. return this;
  1903. };
  1904. /**
  1905. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1906. * @returns the new array
  1907. */
  1908. Color4.prototype.asArray = function () {
  1909. var result = new Array();
  1910. this.toArray(result, 0);
  1911. return result;
  1912. };
  1913. /**
  1914. * Stores from the starting index in the given array the Color4 successive values
  1915. * @param array defines the array where to store the r,g,b components
  1916. * @param index defines an optional index in the target array to define where to start storing values
  1917. * @returns the current Color4 object
  1918. */
  1919. Color4.prototype.toArray = function (array, index) {
  1920. if (index === undefined) {
  1921. index = 0;
  1922. }
  1923. array[index] = this.r;
  1924. array[index + 1] = this.g;
  1925. array[index + 2] = this.b;
  1926. array[index + 3] = this.a;
  1927. return this;
  1928. };
  1929. /**
  1930. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1931. * @param right defines the second operand
  1932. * @returns a new Color4 object
  1933. */
  1934. Color4.prototype.add = function (right) {
  1935. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1936. };
  1937. /**
  1938. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1939. * @param right defines the second operand
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.subtract = function (right) {
  1943. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1944. };
  1945. /**
  1946. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1947. * @param right defines the second operand
  1948. * @param result defines the Color4 object where to store the result
  1949. * @returns the current Color4 object
  1950. */
  1951. Color4.prototype.subtractToRef = function (right, result) {
  1952. result.r = this.r - right.r;
  1953. result.g = this.g - right.g;
  1954. result.b = this.b - right.b;
  1955. result.a = this.a - right.a;
  1956. return this;
  1957. };
  1958. /**
  1959. * Creates a new Color4 with the current Color4 values multiplied by scale
  1960. * @param scale defines the scaling factor to apply
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.scale = function (scale) {
  1964. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1965. };
  1966. /**
  1967. * Multiplies the current Color4 values by scale and stores the result in "result"
  1968. * @param scale defines the scaling factor to apply
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current unmodified Color4
  1971. */
  1972. Color4.prototype.scaleToRef = function (scale, result) {
  1973. result.r = this.r * scale;
  1974. result.g = this.g * scale;
  1975. result.b = this.b * scale;
  1976. result.a = this.a * scale;
  1977. return this;
  1978. };
  1979. /**
  1980. * Scale the current Color4 values by a factor and add the result to a given Color4
  1981. * @param scale defines the scale factor
  1982. * @param result defines the Color4 object where to store the result
  1983. * @returns the unmodified current Color4
  1984. */
  1985. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1986. result.r += this.r * scale;
  1987. result.g += this.g * scale;
  1988. result.b += this.b * scale;
  1989. result.a += this.a * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Clamps the rgb values by the min and max values and stores the result into "result"
  1994. * @param min defines minimum clamping value (default is 0)
  1995. * @param max defines maximum clamping value (default is 1)
  1996. * @param result defines color to store the result into.
  1997. * @returns the cuurent Color4
  1998. */
  1999. Color4.prototype.clampToRef = function (min, max, result) {
  2000. if (min === void 0) { min = 0; }
  2001. if (max === void 0) { max = 1; }
  2002. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2003. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2004. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2005. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2006. return this;
  2007. };
  2008. /**
  2009. * Multipy an Color4 value by another and return a new Color4 object
  2010. * @param color defines the Color4 value to multiply by
  2011. * @returns a new Color4 object
  2012. */
  2013. Color4.prototype.multiply = function (color) {
  2014. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2015. };
  2016. /**
  2017. * Multipy a Color4 value by another and push the result in a reference value
  2018. * @param color defines the Color4 value to multiply by
  2019. * @param result defines the Color4 to fill the result in
  2020. * @returns the result Color4
  2021. */
  2022. Color4.prototype.multiplyToRef = function (color, result) {
  2023. result.r = this.r * color.r;
  2024. result.g = this.g * color.g;
  2025. result.b = this.b * color.b;
  2026. result.a = this.a * color.a;
  2027. return result;
  2028. };
  2029. /**
  2030. * Creates a string with the Color4 current values
  2031. * @returns the string representation of the Color4 object
  2032. */
  2033. Color4.prototype.toString = function () {
  2034. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2035. };
  2036. /**
  2037. * Returns the string "Color4"
  2038. * @returns "Color4"
  2039. */
  2040. Color4.prototype.getClassName = function () {
  2041. return "Color4";
  2042. };
  2043. /**
  2044. * Compute the Color4 hash code
  2045. * @returns an unique number that can be used to hash Color4 objects
  2046. */
  2047. Color4.prototype.getHashCode = function () {
  2048. var hash = this.r || 0;
  2049. hash = (hash * 397) ^ (this.g || 0);
  2050. hash = (hash * 397) ^ (this.b || 0);
  2051. hash = (hash * 397) ^ (this.a || 0);
  2052. return hash;
  2053. };
  2054. /**
  2055. * Creates a new Color4 copied from the current one
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.clone = function () {
  2059. return new Color4(this.r, this.g, this.b, this.a);
  2060. };
  2061. /**
  2062. * Copies the given Color4 values into the current one
  2063. * @param source defines the source Color4 object
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFrom = function (source) {
  2067. this.r = source.r;
  2068. this.g = source.g;
  2069. this.b = source.b;
  2070. this.a = source.a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2082. this.r = r;
  2083. this.g = g;
  2084. this.b = b;
  2085. this.a = a;
  2086. return this;
  2087. };
  2088. /**
  2089. * Copies the given float values into the current one
  2090. * @param r defines the red component to read from
  2091. * @param g defines the green component to read from
  2092. * @param b defines the blue component to read from
  2093. * @param a defines the alpha component to read from
  2094. * @returns the current updated Color4 object
  2095. */
  2096. Color4.prototype.set = function (r, g, b, a) {
  2097. return this.copyFromFloats(r, g, b, a);
  2098. };
  2099. /**
  2100. * Compute the Color4 hexadecimal code as a string
  2101. * @returns a string containing the hexadecimal representation of the Color4 object
  2102. */
  2103. Color4.prototype.toHexString = function () {
  2104. var intR = (this.r * 255) | 0;
  2105. var intG = (this.g * 255) | 0;
  2106. var intB = (this.b * 255) | 0;
  2107. var intA = (this.a * 255) | 0;
  2108. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2109. };
  2110. /**
  2111. * Computes a new Color4 converted from the current one to linear space
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.prototype.toLinearSpace = function () {
  2115. var convertedColor = new Color4();
  2116. this.toLinearSpaceToRef(convertedColor);
  2117. return convertedColor;
  2118. };
  2119. /**
  2120. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2121. * @param convertedColor defines the Color4 object where to store the linear space version
  2122. * @returns the unmodified Color4
  2123. */
  2124. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2125. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2126. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2127. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2128. convertedColor.a = this.a;
  2129. return this;
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to gamma space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toGammaSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toGammaSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the gamma space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. // Statics
  2153. /**
  2154. * Creates a new Color4 from the string containing valid hexadecimal values
  2155. * @param hex defines a string containing valid hexadecimal values
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromHexString = function (hex) {
  2159. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2160. return new Color4(0.0, 0.0, 0.0, 0.0);
  2161. }
  2162. var r = parseInt(hex.substring(1, 3), 16);
  2163. var g = parseInt(hex.substring(3, 5), 16);
  2164. var b = parseInt(hex.substring(5, 7), 16);
  2165. var a = parseInt(hex.substring(7, 9), 16);
  2166. return Color4.FromInts(r, g, b, a);
  2167. };
  2168. /**
  2169. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2170. * @param left defines the start value
  2171. * @param right defines the end value
  2172. * @param amount defines the gradient factor
  2173. * @returns a new Color4 object
  2174. */
  2175. Color4.Lerp = function (left, right, amount) {
  2176. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2177. Color4.LerpToRef(left, right, amount, result);
  2178. return result;
  2179. };
  2180. /**
  2181. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2182. * @param left defines the start value
  2183. * @param right defines the end value
  2184. * @param amount defines the gradient factor
  2185. * @param result defines the Color4 object where to store data
  2186. */
  2187. Color4.LerpToRef = function (left, right, amount, result) {
  2188. result.r = left.r + (right.r - left.r) * amount;
  2189. result.g = left.g + (right.g - left.g) * amount;
  2190. result.b = left.b + (right.b - left.b) * amount;
  2191. result.a = left.a + (right.a - left.a) * amount;
  2192. };
  2193. /**
  2194. * Creates a new Color4 from a Color3 and an alpha value
  2195. * @param color3 defines the source Color3 to read from
  2196. * @param alpha defines the alpha component (1.0 by default)
  2197. * @returns a new Color4 object
  2198. */
  2199. Color4.FromColor3 = function (color3, alpha) {
  2200. if (alpha === void 0) { alpha = 1.0; }
  2201. return new Color4(color3.r, color3.g, color3.b, alpha);
  2202. };
  2203. /**
  2204. * Creates a new Color4 from the starting index element of the given array
  2205. * @param array defines the source array to read from
  2206. * @param offset defines the offset in the source array
  2207. * @returns a new Color4 object
  2208. */
  2209. Color4.FromArray = function (array, offset) {
  2210. if (offset === void 0) { offset = 0; }
  2211. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2212. };
  2213. /**
  2214. * Creates a new Color3 from integer values (< 256)
  2215. * @param r defines the red component to read from (value between 0 and 255)
  2216. * @param g defines the green component to read from (value between 0 and 255)
  2217. * @param b defines the blue component to read from (value between 0 and 255)
  2218. * @param a defines the alpha component to read from (value between 0 and 255)
  2219. * @returns a new Color3 object
  2220. */
  2221. Color4.FromInts = function (r, g, b, a) {
  2222. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2223. };
  2224. /**
  2225. * Check the content of a given array and convert it to an array containing RGBA data
  2226. * If the original array was already containing count * 4 values then it is returned directly
  2227. * @param colors defines the array to check
  2228. * @param count defines the number of RGBA data to expect
  2229. * @returns an array containing count * 4 values (RGBA)
  2230. */
  2231. Color4.CheckColors4 = function (colors, count) {
  2232. // Check if color3 was used
  2233. if (colors.length === count * 3) {
  2234. var colors4 = [];
  2235. for (var index = 0; index < colors.length; index += 3) {
  2236. var newIndex = (index / 3) * 4;
  2237. colors4[newIndex] = colors[index];
  2238. colors4[newIndex + 1] = colors[index + 1];
  2239. colors4[newIndex + 2] = colors[index + 2];
  2240. colors4[newIndex + 3] = 1.0;
  2241. }
  2242. return colors4;
  2243. }
  2244. return colors;
  2245. };
  2246. return Color4;
  2247. }());
  2248. BABYLON.Color4 = Color4;
  2249. /**
  2250. * Class representing a vector containing 2 coordinates
  2251. */
  2252. var Vector2 = /** @class */ (function () {
  2253. /**
  2254. * Creates a new Vector2 from the given x and y coordinates
  2255. * @param x defines the first coordinate
  2256. * @param y defines the second coordinate
  2257. */
  2258. function Vector2(
  2259. /** defines the first coordinate */
  2260. x,
  2261. /** defines the second coordinate */
  2262. y) {
  2263. if (x === void 0) { x = 0; }
  2264. if (y === void 0) { y = 0; }
  2265. this.x = x;
  2266. this.y = y;
  2267. }
  2268. /**
  2269. * Gets a string with the Vector2 coordinates
  2270. * @returns a string with the Vector2 coordinates
  2271. */
  2272. Vector2.prototype.toString = function () {
  2273. return "{X: " + this.x + " Y:" + this.y + "}";
  2274. };
  2275. /**
  2276. * Gets class name
  2277. * @returns the string "Vector2"
  2278. */
  2279. Vector2.prototype.getClassName = function () {
  2280. return "Vector2";
  2281. };
  2282. /**
  2283. * Gets current vector hash code
  2284. * @returns the Vector2 hash code as a number
  2285. */
  2286. Vector2.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. return hash;
  2290. };
  2291. // Operators
  2292. /**
  2293. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2294. * @param array defines the source array
  2295. * @param index defines the offset in source array
  2296. * @returns the current Vector2
  2297. */
  2298. Vector2.prototype.toArray = function (array, index) {
  2299. if (index === void 0) { index = 0; }
  2300. array[index] = this.x;
  2301. array[index + 1] = this.y;
  2302. return this;
  2303. };
  2304. /**
  2305. * Copy the current vector to an array
  2306. * @returns a new array with 2 elements: the Vector2 coordinates.
  2307. */
  2308. Vector2.prototype.asArray = function () {
  2309. var result = new Array();
  2310. this.toArray(result, 0);
  2311. return result;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2315. * @param source defines the source Vector2
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.copyFrom = function (source) {
  2319. this.x = source.x;
  2320. this.y = source.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the Vector2 coordinates with the given floats
  2325. * @param x defines the first coordinate
  2326. * @param y defines the second coordinate
  2327. * @returns the current updated Vector2
  2328. */
  2329. Vector2.prototype.copyFromFloats = function (x, y) {
  2330. this.x = x;
  2331. this.y = y;
  2332. return this;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given floats
  2336. * @param x defines the first coordinate
  2337. * @param y defines the second coordinate
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.set = function (x, y) {
  2341. return this.copyFromFloats(x, y);
  2342. };
  2343. /**
  2344. * Add another vector with the current one
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2347. */
  2348. Vector2.prototype.add = function (otherVector) {
  2349. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2350. };
  2351. /**
  2352. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.addInPlace = function (otherVector) {
  2368. this.x += otherVector.x;
  2369. this.y += otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.addVector3 = function (otherVector) {
  2378. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2379. };
  2380. /**
  2381. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2382. * @param otherVector defines the other vector
  2383. * @returns a new Vector2
  2384. */
  2385. Vector2.prototype.subtract = function (otherVector) {
  2386. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2387. };
  2388. /**
  2389. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2390. * @param otherVector defines the other vector
  2391. * @param result defines the target vector
  2392. * @returns the unmodified current Vector2
  2393. */
  2394. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2395. result.x = this.x - otherVector.x;
  2396. result.y = this.y - otherVector.y;
  2397. return this;
  2398. };
  2399. /**
  2400. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns the current updated Vector2
  2403. */
  2404. Vector2.prototype.subtractInPlace = function (otherVector) {
  2405. this.x -= otherVector.x;
  2406. this.y -= otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Multiplies in place the current Vector2 coordinates by the given ones
  2411. * @param otherVector defines the other vector
  2412. * @returns the current updated Vector2
  2413. */
  2414. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2415. this.x *= otherVector.x;
  2416. this.y *= otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2421. * @param otherVector defines the other vector
  2422. * @returns a new Vector2
  2423. */
  2424. Vector2.prototype.multiply = function (otherVector) {
  2425. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2426. };
  2427. /**
  2428. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2429. * @param otherVector defines the other vector
  2430. * @param result defines the target vector
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2434. result.x = this.x * otherVector.x;
  2435. result.y = this.y * otherVector.y;
  2436. return this;
  2437. };
  2438. /**
  2439. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2440. * @param x defines the first coordinate
  2441. * @param y defines the second coordinate
  2442. * @returns a new Vector2
  2443. */
  2444. Vector2.prototype.multiplyByFloats = function (x, y) {
  2445. return new Vector2(this.x * x, this.y * y);
  2446. };
  2447. /**
  2448. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns a new Vector2
  2451. */
  2452. Vector2.prototype.divide = function (otherVector) {
  2453. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2454. };
  2455. /**
  2456. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2457. * @param otherVector defines the other vector
  2458. * @param result defines the target vector
  2459. * @returns the unmodified current Vector2
  2460. */
  2461. Vector2.prototype.divideToRef = function (otherVector, result) {
  2462. result.x = this.x / otherVector.x;
  2463. result.y = this.y / otherVector.y;
  2464. return this;
  2465. };
  2466. /**
  2467. * Divides the current Vector2 coordinates by the given ones
  2468. * @param otherVector defines the other vector
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.divideInPlace = function (otherVector) {
  2472. return this.divideToRef(otherVector, this);
  2473. };
  2474. /**
  2475. * Gets a new Vector2 with current Vector2 negated coordinates
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.negate = function () {
  2479. return new Vector2(-this.x, -this.y);
  2480. };
  2481. /**
  2482. * Multiply the Vector2 coordinates by scale
  2483. * @param scale defines the scaling factor
  2484. * @returns the current updated Vector2
  2485. */
  2486. Vector2.prototype.scaleInPlace = function (scale) {
  2487. this.x *= scale;
  2488. this.y *= scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2493. * @param scale defines the scaling factor
  2494. * @returns a new Vector2
  2495. */
  2496. Vector2.prototype.scale = function (scale) {
  2497. var result = new Vector2(0, 0);
  2498. this.scaleToRef(scale, result);
  2499. return result;
  2500. };
  2501. /**
  2502. * Scale the current Vector2 values by a factor to a given Vector2
  2503. * @param scale defines the scale factor
  2504. * @param result defines the Vector2 object where to store the result
  2505. * @returns the unmodified current Vector2
  2506. */
  2507. Vector2.prototype.scaleToRef = function (scale, result) {
  2508. result.x = this.x * scale;
  2509. result.y = this.y * scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2514. * @param scale defines the scale factor
  2515. * @param result defines the Vector2 object where to store the result
  2516. * @returns the unmodified current Vector2
  2517. */
  2518. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2519. result.x += this.x * scale;
  2520. result.y += this.y * scale;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a boolean if two vectors are equals
  2525. * @param otherVector defines the other vector
  2526. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2527. */
  2528. Vector2.prototype.equals = function (otherVector) {
  2529. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2530. };
  2531. /**
  2532. * Gets a boolean if two vectors are equals (using an epsilon value)
  2533. * @param otherVector defines the other vector
  2534. * @param epsilon defines the minimal distance to consider equality
  2535. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2536. */
  2537. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2538. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2539. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2540. };
  2541. /**
  2542. * Gets a new Vector2 from current Vector2 floored values
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.prototype.floor = function () {
  2546. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2547. };
  2548. /**
  2549. * Gets a new Vector2 from current Vector2 floored values
  2550. * @returns a new Vector2
  2551. */
  2552. Vector2.prototype.fract = function () {
  2553. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2554. };
  2555. // Properties
  2556. /**
  2557. * Gets the length of the vector
  2558. * @returns the vector length (float)
  2559. */
  2560. Vector2.prototype.length = function () {
  2561. return Math.sqrt(this.x * this.x + this.y * this.y);
  2562. };
  2563. /**
  2564. * Gets the vector squared length
  2565. * @returns the vector squared length (float)
  2566. */
  2567. Vector2.prototype.lengthSquared = function () {
  2568. return (this.x * this.x + this.y * this.y);
  2569. };
  2570. // Methods
  2571. /**
  2572. * Normalize the vector
  2573. * @returns the current updated Vector2
  2574. */
  2575. Vector2.prototype.normalize = function () {
  2576. var len = this.length();
  2577. if (len === 0)
  2578. return this;
  2579. var num = 1.0 / len;
  2580. this.x *= num;
  2581. this.y *= num;
  2582. return this;
  2583. };
  2584. /**
  2585. * Gets a new Vector2 copied from the Vector2
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.prototype.clone = function () {
  2589. return new Vector2(this.x, this.y);
  2590. };
  2591. // Statics
  2592. /**
  2593. * Gets a new Vector2(0, 0)
  2594. * @returns a new Vector2
  2595. */
  2596. Vector2.Zero = function () {
  2597. return new Vector2(0, 0);
  2598. };
  2599. /**
  2600. * Gets a new Vector2(1, 1)
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.One = function () {
  2604. return new Vector2(1, 1);
  2605. };
  2606. /**
  2607. * Gets a new Vector2 set from the given index element of the given array
  2608. * @param array defines the data source
  2609. * @param offset defines the offset in the data source
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.FromArray = function (array, offset) {
  2613. if (offset === void 0) { offset = 0; }
  2614. return new Vector2(array[offset], array[offset + 1]);
  2615. };
  2616. /**
  2617. * Sets "result" from the given index element of the given array
  2618. * @param array defines the data source
  2619. * @param offset defines the offset in the data source
  2620. * @param result defines the target vector
  2621. */
  2622. Vector2.FromArrayToRef = function (array, offset, result) {
  2623. result.x = array[offset];
  2624. result.y = array[offset + 1];
  2625. };
  2626. /**
  2627. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2628. * @param value1 defines 1st point of control
  2629. * @param value2 defines 2nd point of control
  2630. * @param value3 defines 3rd point of control
  2631. * @param value4 defines 4th point of control
  2632. * @param amount defines the interpolation factor
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2636. var squared = amount * amount;
  2637. var cubed = amount * squared;
  2638. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2639. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2640. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2641. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2642. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2643. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2648. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2649. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2650. * @param value defines the value to clamp
  2651. * @param min defines the lower limit
  2652. * @param max defines the upper limit
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Clamp = function (value, min, max) {
  2656. var x = value.x;
  2657. x = (x > max.x) ? max.x : x;
  2658. x = (x < min.x) ? min.x : x;
  2659. var y = value.y;
  2660. y = (y > max.y) ? max.y : y;
  2661. y = (y < min.y) ? min.y : y;
  2662. return new Vector2(x, y);
  2663. };
  2664. /**
  2665. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2666. * @param value1 defines the 1st control point
  2667. * @param tangent1 defines the outgoing tangent
  2668. * @param value2 defines the 2nd control point
  2669. * @param tangent2 defines the incoming tangent
  2670. * @param amount defines the interpolation factor
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2674. var squared = amount * amount;
  2675. var cubed = amount * squared;
  2676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2678. var part3 = (cubed - (2.0 * squared)) + amount;
  2679. var part4 = cubed - squared;
  2680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2682. return new Vector2(x, y);
  2683. };
  2684. /**
  2685. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2686. * @param start defines the start vector
  2687. * @param end defines the end vector
  2688. * @param amount defines the interpolation factor
  2689. * @returns a new Vector2
  2690. */
  2691. Vector2.Lerp = function (start, end, amount) {
  2692. var x = start.x + ((end.x - start.x) * amount);
  2693. var y = start.y + ((end.y - start.y) * amount);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Gets the dot product of the vector "left" and the vector "right"
  2698. * @param left defines first vector
  2699. * @param right defines second vector
  2700. * @returns the dot product (float)
  2701. */
  2702. Vector2.Dot = function (left, right) {
  2703. return left.x * right.x + left.y * right.y;
  2704. };
  2705. /**
  2706. * Returns a new Vector2 equal to the normalized given vector
  2707. * @param vector defines the vector to normalize
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Normalize = function (vector) {
  2711. var newVector = vector.clone();
  2712. newVector.normalize();
  2713. return newVector;
  2714. };
  2715. /**
  2716. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2717. * @param left defines 1st vector
  2718. * @param right defines 2nd vector
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Minimize = function (left, right) {
  2722. var x = (left.x < right.x) ? left.x : right.x;
  2723. var y = (left.y < right.y) ? left.y : right.y;
  2724. return new Vector2(x, y);
  2725. };
  2726. /**
  2727. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2728. * @param left defines 1st vector
  2729. * @param right defines 2nd vector
  2730. * @returns a new Vector2
  2731. */
  2732. Vector2.Maximize = function (left, right) {
  2733. var x = (left.x > right.x) ? left.x : right.x;
  2734. var y = (left.y > right.y) ? left.y : right.y;
  2735. return new Vector2(x, y);
  2736. };
  2737. /**
  2738. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2739. * @param vector defines the vector to transform
  2740. * @param transformation defines the matrix to apply
  2741. * @returns a new Vector2
  2742. */
  2743. Vector2.Transform = function (vector, transformation) {
  2744. var r = Vector2.Zero();
  2745. Vector2.TransformToRef(vector, transformation, r);
  2746. return r;
  2747. };
  2748. /**
  2749. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2750. * @param vector defines the vector to transform
  2751. * @param transformation defines the matrix to apply
  2752. * @param result defines the target vector
  2753. */
  2754. Vector2.TransformToRef = function (vector, transformation, result) {
  2755. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2756. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2757. result.x = x;
  2758. result.y = y;
  2759. };
  2760. /**
  2761. * Determines if a given vector is included in a triangle
  2762. * @param p defines the vector to test
  2763. * @param p0 defines 1st triangle point
  2764. * @param p1 defines 2nd triangle point
  2765. * @param p2 defines 3rd triangle point
  2766. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2767. */
  2768. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2769. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2770. var sign = a < 0 ? -1 : 1;
  2771. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2772. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2773. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2774. };
  2775. /**
  2776. * Gets the distance between the vectors "value1" and "value2"
  2777. * @param value1 defines first vector
  2778. * @param value2 defines second vector
  2779. * @returns the distance between vectors
  2780. */
  2781. Vector2.Distance = function (value1, value2) {
  2782. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2783. };
  2784. /**
  2785. * Returns the squared distance between the vectors "value1" and "value2"
  2786. * @param value1 defines first vector
  2787. * @param value2 defines second vector
  2788. * @returns the squared distance between vectors
  2789. */
  2790. Vector2.DistanceSquared = function (value1, value2) {
  2791. var x = value1.x - value2.x;
  2792. var y = value1.y - value2.y;
  2793. return (x * x) + (y * y);
  2794. };
  2795. /**
  2796. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2797. * @param value1 defines first vector
  2798. * @param value2 defines second vector
  2799. * @returns a new Vector2
  2800. */
  2801. Vector2.Center = function (value1, value2) {
  2802. var center = value1.add(value2);
  2803. center.scaleInPlace(0.5);
  2804. return center;
  2805. };
  2806. /**
  2807. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2808. * @param p defines the middle point
  2809. * @param segA defines one point of the segment
  2810. * @param segB defines the other point of the segment
  2811. * @returns the shortest distance
  2812. */
  2813. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2814. var l2 = Vector2.DistanceSquared(segA, segB);
  2815. if (l2 === 0.0) {
  2816. return Vector2.Distance(p, segA);
  2817. }
  2818. var v = segB.subtract(segA);
  2819. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2820. var proj = segA.add(v.multiplyByFloats(t, t));
  2821. return Vector2.Distance(p, proj);
  2822. };
  2823. return Vector2;
  2824. }());
  2825. BABYLON.Vector2 = Vector2;
  2826. /**
  2827. * Classed used to store (x,y,z) vector representation
  2828. * A Vector3 is the main object used in 3D geometry
  2829. * It can represent etiher the coordinates of a point the space, either a direction
  2830. * Reminder: Babylon.js uses a left handed forward facing system
  2831. */
  2832. var Vector3 = /** @class */ (function () {
  2833. /**
  2834. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2835. * @param x defines the first coordinates (on X axis)
  2836. * @param y defines the second coordinates (on Y axis)
  2837. * @param z defines the third coordinates (on Z axis)
  2838. */
  2839. function Vector3(
  2840. /**
  2841. * Defines the first coordinates (on X axis)
  2842. */
  2843. x,
  2844. /**
  2845. * Defines the second coordinates (on Y axis)
  2846. */
  2847. y,
  2848. /**
  2849. * Defines the third coordinates (on Z axis)
  2850. */
  2851. z) {
  2852. if (x === void 0) { x = 0; }
  2853. if (y === void 0) { y = 0; }
  2854. if (z === void 0) { z = 0; }
  2855. this.x = x;
  2856. this.y = y;
  2857. this.z = z;
  2858. }
  2859. /**
  2860. * Creates a string representation of the Vector3
  2861. * @returns a string with the Vector3 coordinates.
  2862. */
  2863. Vector3.prototype.toString = function () {
  2864. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2865. };
  2866. /**
  2867. * Gets the class name
  2868. * @returns the string "Vector3"
  2869. */
  2870. Vector3.prototype.getClassName = function () {
  2871. return "Vector3";
  2872. };
  2873. /**
  2874. * Creates the Vector3 hash code
  2875. * @returns a number which tends to be unique between Vector3 instances
  2876. */
  2877. Vector3.prototype.getHashCode = function () {
  2878. var hash = this.x || 0;
  2879. hash = (hash * 397) ^ (this.y || 0);
  2880. hash = (hash * 397) ^ (this.z || 0);
  2881. return hash;
  2882. };
  2883. // Operators
  2884. /**
  2885. * Creates an array containing three elements : the coordinates of the Vector3
  2886. * @returns a new array of numbers
  2887. */
  2888. Vector3.prototype.asArray = function () {
  2889. var result = [];
  2890. this.toArray(result, 0);
  2891. return result;
  2892. };
  2893. /**
  2894. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2895. * @param array defines the destination array
  2896. * @param index defines the offset in the destination array
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.toArray = function (array, index) {
  2900. if (index === void 0) { index = 0; }
  2901. array[index] = this.x;
  2902. array[index + 1] = this.y;
  2903. array[index + 2] = this.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2908. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2909. */
  2910. Vector3.prototype.toQuaternion = function () {
  2911. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2912. };
  2913. /**
  2914. * Adds the given vector to the current Vector3
  2915. * @param otherVector defines the second operand
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.addInPlace = function (otherVector) {
  2919. this.x += otherVector.x;
  2920. this.y += otherVector.y;
  2921. this.z += otherVector.z;
  2922. return this;
  2923. };
  2924. /**
  2925. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2926. * @param otherVector defines the second operand
  2927. * @returns the resulting Vector3
  2928. */
  2929. Vector3.prototype.add = function (otherVector) {
  2930. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2931. };
  2932. /**
  2933. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2934. * @param otherVector defines the second operand
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.addToRef = function (otherVector, result) {
  2939. result.x = this.x + otherVector.x;
  2940. result.y = this.y + otherVector.y;
  2941. result.z = this.z + otherVector.z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Subtract the given vector from the current Vector3
  2946. * @param otherVector defines the second operand
  2947. * @returns the current updated Vector3
  2948. */
  2949. Vector3.prototype.subtractInPlace = function (otherVector) {
  2950. this.x -= otherVector.x;
  2951. this.y -= otherVector.y;
  2952. this.z -= otherVector.z;
  2953. return this;
  2954. };
  2955. /**
  2956. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2957. * @param otherVector defines the second operand
  2958. * @returns the resulting Vector3
  2959. */
  2960. Vector3.prototype.subtract = function (otherVector) {
  2961. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2962. };
  2963. /**
  2964. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2965. * @param otherVector defines the second operand
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2970. result.x = this.x - otherVector.x;
  2971. result.y = this.y - otherVector.y;
  2972. result.z = this.z - otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2977. * @param x defines the x coordinate of the operand
  2978. * @param y defines the y coordinate of the operand
  2979. * @param z defines the z coordinate of the operand
  2980. * @returns the resulting Vector3
  2981. */
  2982. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2983. return new Vector3(this.x - x, this.y - y, this.z - z);
  2984. };
  2985. /**
  2986. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2987. * @param x defines the x coordinate of the operand
  2988. * @param y defines the y coordinate of the operand
  2989. * @param z defines the z coordinate of the operand
  2990. * @param result defines the Vector3 object where to store the result
  2991. * @returns the current Vector3
  2992. */
  2993. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2994. result.x = this.x - x;
  2995. result.y = this.y - y;
  2996. result.z = this.z - z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3001. * @returns a new Vector3
  3002. */
  3003. Vector3.prototype.negate = function () {
  3004. return new Vector3(-this.x, -this.y, -this.z);
  3005. };
  3006. /**
  3007. * Multiplies the Vector3 coordinates by the float "scale"
  3008. * @param scale defines the multiplier factor
  3009. * @returns the current updated Vector3
  3010. */
  3011. Vector3.prototype.scaleInPlace = function (scale) {
  3012. this.x *= scale;
  3013. this.y *= scale;
  3014. this.z *= scale;
  3015. return this;
  3016. };
  3017. /**
  3018. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3019. * @param scale defines the multiplier factor
  3020. * @returns a new Vector3
  3021. */
  3022. Vector3.prototype.scale = function (scale) {
  3023. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3024. };
  3025. /**
  3026. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3027. * @param scale defines the multiplier factor
  3028. * @param result defines the Vector3 object where to store the result
  3029. * @returns the current Vector3
  3030. */
  3031. Vector3.prototype.scaleToRef = function (scale, result) {
  3032. result.x = this.x * scale;
  3033. result.y = this.y * scale;
  3034. result.z = this.z * scale;
  3035. return this;
  3036. };
  3037. /**
  3038. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3039. * @param scale defines the scale factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the unmodified current Vector3
  3042. */
  3043. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3044. result.x += this.x * scale;
  3045. result.y += this.y * scale;
  3046. result.z += this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3051. * @param otherVector defines the second operand
  3052. * @returns true if both vectors are equals
  3053. */
  3054. Vector3.prototype.equals = function (otherVector) {
  3055. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3056. };
  3057. /**
  3058. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3059. * @param otherVector defines the second operand
  3060. * @param epsilon defines the minimal distance to define values as equals
  3061. * @returns true if both vectors are distant less than epsilon
  3062. */
  3063. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3064. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3065. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3066. };
  3067. /**
  3068. * Returns true if the current Vector3 coordinates equals the given floats
  3069. * @param x defines the x coordinate of the operand
  3070. * @param y defines the y coordinate of the operand
  3071. * @param z defines the z coordinate of the operand
  3072. * @returns true if both vectors are equals
  3073. */
  3074. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3075. return this.x === x && this.y === y && this.z === z;
  3076. };
  3077. /**
  3078. * Multiplies the current Vector3 coordinates by the given ones
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3083. this.x *= otherVector.x;
  3084. this.y *= otherVector.y;
  3085. this.z *= otherVector.z;
  3086. return this;
  3087. };
  3088. /**
  3089. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3090. * @param otherVector defines the second operand
  3091. * @returns the new Vector3
  3092. */
  3093. Vector3.prototype.multiply = function (otherVector) {
  3094. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3095. };
  3096. /**
  3097. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3098. * @param otherVector defines the second operand
  3099. * @param result defines the Vector3 object where to store the result
  3100. * @returns the current Vector3
  3101. */
  3102. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3103. result.x = this.x * otherVector.x;
  3104. result.y = this.y * otherVector.y;
  3105. result.z = this.z * otherVector.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3110. * @param x defines the x coordinate of the operand
  3111. * @param y defines the y coordinate of the operand
  3112. * @param z defines the z coordinate of the operand
  3113. * @returns the new Vector3
  3114. */
  3115. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3116. return new Vector3(this.x * x, this.y * y, this.z * z);
  3117. };
  3118. /**
  3119. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3120. * @param otherVector defines the second operand
  3121. * @returns the new Vector3
  3122. */
  3123. Vector3.prototype.divide = function (otherVector) {
  3124. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3125. };
  3126. /**
  3127. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3128. * @param otherVector defines the second operand
  3129. * @param result defines the Vector3 object where to store the result
  3130. * @returns the current Vector3
  3131. */
  3132. Vector3.prototype.divideToRef = function (otherVector, result) {
  3133. result.x = this.x / otherVector.x;
  3134. result.y = this.y / otherVector.y;
  3135. result.z = this.z / otherVector.z;
  3136. return this;
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones.
  3140. * @param otherVector defines the second operand
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.divideInPlace = function (otherVector) {
  3144. return this.divideToRef(otherVector, this);
  3145. };
  3146. /**
  3147. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3148. * @param other defines the second operand
  3149. * @returns the current updated Vector3
  3150. */
  3151. Vector3.prototype.minimizeInPlace = function (other) {
  3152. if (other.x < this.x)
  3153. this.x = other.x;
  3154. if (other.y < this.y)
  3155. this.y = other.y;
  3156. if (other.z < this.z)
  3157. this.z = other.z;
  3158. return this;
  3159. };
  3160. /**
  3161. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3162. * @param other defines the second operand
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.maximizeInPlace = function (other) {
  3166. if (other.x > this.x)
  3167. this.x = other.x;
  3168. if (other.y > this.y)
  3169. this.y = other.y;
  3170. if (other.z > this.z)
  3171. this.z = other.z;
  3172. return this;
  3173. };
  3174. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3175. /**
  3176. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3177. */
  3178. get: function () {
  3179. var absX = Math.abs(this.x);
  3180. var absY = Math.abs(this.y);
  3181. if (absX !== absY) {
  3182. return true;
  3183. }
  3184. var absZ = Math.abs(this.z);
  3185. if (absX !== absZ) {
  3186. return true;
  3187. }
  3188. if (absY !== absZ) {
  3189. return true;
  3190. }
  3191. return false;
  3192. },
  3193. enumerable: true,
  3194. configurable: true
  3195. });
  3196. /**
  3197. * Gets a new Vector3 from current Vector3 floored values
  3198. * @returns a new Vector3
  3199. */
  3200. Vector3.prototype.floor = function () {
  3201. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3202. };
  3203. /**
  3204. * Gets a new Vector3 from current Vector3 floored values
  3205. * @returns a new Vector3
  3206. */
  3207. Vector3.prototype.fract = function () {
  3208. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3209. };
  3210. // Properties
  3211. /**
  3212. * Gets the length of the Vector3
  3213. * @returns the length of the Vecto3
  3214. */
  3215. Vector3.prototype.length = function () {
  3216. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3217. };
  3218. /**
  3219. * Gets the squared length of the Vector3
  3220. * @returns squared length of the Vector3
  3221. */
  3222. Vector3.prototype.lengthSquared = function () {
  3223. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Normalize the current Vector3.
  3227. * Please note that this is an in place operation.
  3228. * @returns the current updated Vector3
  3229. */
  3230. Vector3.prototype.normalize = function () {
  3231. var len = this.length();
  3232. if (len === 0 || len === 1.0)
  3233. return this;
  3234. var num = 1.0 / len;
  3235. this.x *= num;
  3236. this.y *= num;
  3237. this.z *= num;
  3238. return this;
  3239. };
  3240. /**
  3241. * Normalize the current Vector3 to a new vector
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.prototype.normalizeToNew = function () {
  3245. var normalized = new Vector3(0, 0, 0);
  3246. this.normalizeToRef(normalized);
  3247. return normalized;
  3248. };
  3249. /**
  3250. * Normalize the current Vector3 to the reference
  3251. * @param reference define the Vector3 to update
  3252. * @returns the updated Vector3
  3253. */
  3254. Vector3.prototype.normalizeToRef = function (reference) {
  3255. var len = this.length();
  3256. if (len === 0 || len === 1.0) {
  3257. reference.set(this.x, this.y, this.z);
  3258. return reference;
  3259. }
  3260. var scale = 1.0 / len;
  3261. this.scaleToRef(scale, reference);
  3262. return reference;
  3263. };
  3264. /**
  3265. * Creates a new Vector3 copied from the current Vector3
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.prototype.clone = function () {
  3269. return new Vector3(this.x, this.y, this.z);
  3270. };
  3271. /**
  3272. * Copies the given vector coordinates to the current Vector3 ones
  3273. * @param source defines the source Vector3
  3274. * @returns the current updated Vector3
  3275. */
  3276. Vector3.prototype.copyFrom = function (source) {
  3277. this.x = source.x;
  3278. this.y = source.y;
  3279. this.z = source.z;
  3280. return this;
  3281. };
  3282. /**
  3283. * Copies the given floats to the current Vector3 coordinates
  3284. * @param x defines the x coordinate of the operand
  3285. * @param y defines the y coordinate of the operand
  3286. * @param z defines the z coordinate of the operand
  3287. * @returns the current updated Vector3
  3288. */
  3289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. return this;
  3294. };
  3295. /**
  3296. * Copies the given floats to the current Vector3 coordinates
  3297. * @param x defines the x coordinate of the operand
  3298. * @param y defines the y coordinate of the operand
  3299. * @param z defines the z coordinate of the operand
  3300. * @returns the current updated Vector3
  3301. */
  3302. Vector3.prototype.set = function (x, y, z) {
  3303. return this.copyFromFloats(x, y, z);
  3304. };
  3305. // Statics
  3306. /**
  3307. * Get the clip factor between two vectors
  3308. * @param vector0 defines the first operand
  3309. * @param vector1 defines the second operand
  3310. * @param axis defines the axis to use
  3311. * @param size defines the size along the axis
  3312. * @returns the clip factor
  3313. */
  3314. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3315. var d0 = Vector3.Dot(vector0, axis) - size;
  3316. var d1 = Vector3.Dot(vector1, axis) - size;
  3317. var s = d0 / (d0 - d1);
  3318. return s;
  3319. };
  3320. /**
  3321. * Get angle between two vectors
  3322. * @param vector0 angle between vector0 and vector1
  3323. * @param vector1 angle between vector0 and vector1
  3324. * @param normal direction of the normal
  3325. * @return the angle between vector0 and vector1
  3326. */
  3327. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3328. var v0 = vector0.clone().normalize();
  3329. var v1 = vector1.clone().normalize();
  3330. var dot = Vector3.Dot(v0, v1);
  3331. var n = Vector3.Cross(v0, v1);
  3332. if (Vector3.Dot(n, normal) > 0) {
  3333. return Math.acos(dot);
  3334. }
  3335. return -Math.acos(dot);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set from the index "offset" of the given array
  3339. * @param array defines the source array
  3340. * @param offset defines the offset in the source array
  3341. * @returns the new Vector3
  3342. */
  3343. Vector3.FromArray = function (array, offset) {
  3344. if (!offset) {
  3345. offset = 0;
  3346. }
  3347. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3348. };
  3349. /**
  3350. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArray instead
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.FromFloatArray = function (array, offset) {
  3357. return Vector3.FromArray(array, offset);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3361. * @param array defines the source array
  3362. * @param offset defines the offset in the source array
  3363. * @param result defines the Vector3 where to store the result
  3364. */
  3365. Vector3.FromArrayToRef = function (array, offset, result) {
  3366. result.x = array[offset];
  3367. result.y = array[offset + 1];
  3368. result.z = array[offset + 2];
  3369. };
  3370. /**
  3371. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArrayToRef instead.
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @param result defines the Vector3 where to store the result
  3376. */
  3377. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3378. return Vector3.FromArrayToRef(array, offset, result);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the given floats.
  3382. * @param x defines the x coordinate of the source
  3383. * @param y defines the y coordinate of the source
  3384. * @param z defines the z coordinate of the source
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3388. result.x = x;
  3389. result.y = y;
  3390. result.z = z;
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3394. * @returns a new empty Vector3
  3395. */
  3396. Vector3.Zero = function () {
  3397. return new Vector3(0.0, 0.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3401. * @returns a new unit Vector3
  3402. */
  3403. Vector3.One = function () {
  3404. return new Vector3(1.0, 1.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3408. * @returns a new up Vector3
  3409. */
  3410. Vector3.Up = function () {
  3411. return new Vector3(0.0, 1.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3415. * @returns a new down Vector3
  3416. */
  3417. Vector3.Down = function () {
  3418. return new Vector3(0.0, -1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3422. * @returns a new forward Vector3
  3423. */
  3424. Vector3.Forward = function () {
  3425. return new Vector3(0.0, 0.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3429. * @returns a new forward Vector3
  3430. */
  3431. Vector3.Backward = function () {
  3432. return new Vector3(0.0, 0.0, -1.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3436. * @returns a new right Vector3
  3437. */
  3438. Vector3.Right = function () {
  3439. return new Vector3(1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3443. * @returns a new left Vector3
  3444. */
  3445. Vector3.Left = function () {
  3446. return new Vector3(-1.0, 0.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @returns the transformed Vector3
  3454. */
  3455. Vector3.TransformCoordinates = function (vector, transformation) {
  3456. var result = Vector3.Zero();
  3457. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3458. return result;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @param result defines the Vector3 where to store the result
  3466. */
  3467. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3468. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3469. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3470. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3471. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3472. result.x = x / w;
  3473. result.y = y / w;
  3474. result.z = z / w;
  3475. };
  3476. /**
  3477. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3478. * This method computes tranformed coordinates only, not transformed direction vectors
  3479. * @param x define the x coordinate of the source vector
  3480. * @param y define the y coordinate of the source vector
  3481. * @param z define the z coordinate of the source vector
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3490. result.x = rx / rw;
  3491. result.y = ry / rw;
  3492. result.z = rz / rw;
  3493. };
  3494. /**
  3495. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.TransformNormal = function (vector, transformation) {
  3502. var result = Vector3.Zero();
  3503. Vector3.TransformNormalToRef(vector, transformation, result);
  3504. return result;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3514. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3515. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3516. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3517. result.x = x;
  3518. result.y = y;
  3519. result.z = z;
  3520. };
  3521. /**
  3522. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3523. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3524. * @param x define the x coordinate of the source vector
  3525. * @param y define the y coordinate of the source vector
  3526. * @param z define the z coordinate of the source vector
  3527. * @param transformation defines the transformation matrix
  3528. * @param result defines the Vector3 where to store the result
  3529. */
  3530. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3531. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3532. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3533. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3537. * @param value1 defines the first control point
  3538. * @param value2 defines the second control point
  3539. * @param value3 defines the third control point
  3540. * @param value4 defines the fourth control point
  3541. * @param amount defines the amount on the spline to use
  3542. * @returns the new Vector3
  3543. */
  3544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3545. var squared = amount * amount;
  3546. var cubed = amount * squared;
  3547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3556. return new Vector3(x, y, z);
  3557. };
  3558. /**
  3559. * 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"
  3560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3562. * @param value defines the current value
  3563. * @param min defines the lower range value
  3564. * @param max defines the upper range value
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Clamp = function (value, min, max) {
  3568. var x = value.x;
  3569. x = (x > max.x) ? max.x : x;
  3570. x = (x < min.x) ? min.x : x;
  3571. var y = value.y;
  3572. y = (y > max.y) ? max.y : y;
  3573. y = (y < min.y) ? min.y : y;
  3574. var z = value.z;
  3575. z = (z > max.z) ? max.z : z;
  3576. z = (z < min.z) ? min.z : z;
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3581. * @param value1 defines the first control point
  3582. * @param tangent1 defines the first tangent vector
  3583. * @param value2 defines the second control point
  3584. * @param tangent2 defines the second tangent vector
  3585. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3589. var squared = amount * amount;
  3590. var cubed = amount * squared;
  3591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3593. var part3 = (cubed - (2.0 * squared)) + amount;
  3594. var part4 = cubed - squared;
  3595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @returns the new Vector3
  3606. */
  3607. Vector3.Lerp = function (start, end, amount) {
  3608. var result = new Vector3(0, 0, 0);
  3609. Vector3.LerpToRef(start, end, amount, result);
  3610. return result;
  3611. };
  3612. /**
  3613. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.LerpToRef = function (start, end, amount, result) {
  3620. result.x = start.x + ((end.x - start.x) * amount);
  3621. result.y = start.y + ((end.y - start.y) * amount);
  3622. result.z = start.z + ((end.z - start.z) * amount);
  3623. };
  3624. /**
  3625. * Returns the dot product (float) between the vectors "left" and "right"
  3626. * @param left defines the left operand
  3627. * @param right defines the right operand
  3628. * @returns the dot product
  3629. */
  3630. Vector3.Dot = function (left, right) {
  3631. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3632. };
  3633. /**
  3634. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @returns the cross product
  3639. */
  3640. Vector3.Cross = function (left, right) {
  3641. var result = Vector3.Zero();
  3642. Vector3.CrossToRef(left, right, result);
  3643. return result;
  3644. };
  3645. /**
  3646. * Sets the given vector "result" with the cross product of "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @param result defines the Vector3 where to store the result
  3651. */
  3652. Vector3.CrossToRef = function (left, right, result) {
  3653. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3654. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3655. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3656. result.copyFrom(MathTmp.Vector3[0]);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 as the normalization of the given vector
  3660. * @param vector defines the Vector3 to normalize
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Normalize = function (vector) {
  3664. var result = Vector3.Zero();
  3665. Vector3.NormalizeToRef(vector, result);
  3666. return result;
  3667. };
  3668. /**
  3669. * Sets the given vector "result" with the normalization of the given first vector
  3670. * @param vector defines the Vector3 to normalize
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.NormalizeToRef = function (vector, result) {
  3674. result.copyFrom(vector);
  3675. result.normalize();
  3676. };
  3677. /**
  3678. * Project a Vector3 onto screen space
  3679. * @param vector defines the Vector3 to project
  3680. * @param world defines the world matrix to use
  3681. * @param transform defines the transform (view x projection) matrix to use
  3682. * @param viewport defines the screen viewport to use
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Project = function (vector, world, transform, viewport) {
  3686. var cw = viewport.width;
  3687. var ch = viewport.height;
  3688. var cx = viewport.x;
  3689. var cy = viewport.y;
  3690. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3691. 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);
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.multiplyToRef(viewportMatrix, matrix);
  3695. return Vector3.TransformCoordinates(vector, matrix);
  3696. };
  3697. /**
  3698. * Unproject from screen space to object space
  3699. * @param source defines the screen space Vector3 to use
  3700. * @param viewportWidth defines the current width of the viewport
  3701. * @param viewportHeight defines the current height of the viewport
  3702. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3703. * @param transform defines the transform (view x projection) matrix to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3707. var matrix = MathTmp.Matrix[0];
  3708. world.multiplyToRef(transform, matrix);
  3709. matrix.invert();
  3710. source.x = source.x / viewportWidth * 2 - 1;
  3711. source.y = -(source.y / viewportHeight * 2 - 1);
  3712. var vector = Vector3.TransformCoordinates(source, matrix);
  3713. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3714. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3715. vector = vector.scale(1.0 / num);
  3716. }
  3717. return vector;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3730. var result = Vector3.Zero();
  3731. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3732. return result;
  3733. };
  3734. /**
  3735. * Unproject from screen space to object space
  3736. * @param source defines the screen space Vector3 to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3746. };
  3747. /**
  3748. * Unproject from screen space to object space
  3749. * @param sourceX defines the screen space x coordinate to use
  3750. * @param sourceY defines the screen space y coordinate to use
  3751. * @param sourceZ defines the screen space z coordinate to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param view defines the view matrix to use
  3756. * @param projection defines the projection matrix to use
  3757. * @param result defines the Vector3 where to store the result
  3758. */
  3759. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3760. var matrix = MathTmp.Matrix[0];
  3761. world.multiplyToRef(view, matrix);
  3762. matrix.multiplyToRef(projection, matrix);
  3763. matrix.invert();
  3764. var screenSource = MathTmp.Vector3[0];
  3765. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3766. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3767. screenSource.z = 2 * sourceZ - 1.0;
  3768. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3769. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3770. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3771. result.scaleInPlace(1.0 / num);
  3772. }
  3773. };
  3774. /**
  3775. * Gets the minimal coordinate values between two Vector3
  3776. * @param left defines the first operand
  3777. * @param right defines the second operand
  3778. * @returns the new Vector3
  3779. */
  3780. Vector3.Minimize = function (left, right) {
  3781. var min = left.clone();
  3782. min.minimizeInPlace(right);
  3783. return min;
  3784. };
  3785. /**
  3786. * Gets the maximal coordinate values between two Vector3
  3787. * @param left defines the first operand
  3788. * @param right defines the second operand
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Maximize = function (left, right) {
  3792. var max = left.clone();
  3793. max.maximizeInPlace(right);
  3794. return max;
  3795. };
  3796. /**
  3797. * Returns the distance between the vectors "value1" and "value2"
  3798. * @param value1 defines the first operand
  3799. * @param value2 defines the second operand
  3800. * @returns the distance
  3801. */
  3802. Vector3.Distance = function (value1, value2) {
  3803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3804. };
  3805. /**
  3806. * Returns the squared distance between the vectors "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the squared distance
  3810. */
  3811. Vector3.DistanceSquared = function (value1, value2) {
  3812. var x = value1.x - value2.x;
  3813. var y = value1.y - value2.y;
  3814. var z = value1.z - value2.z;
  3815. return (x * x) + (y * y) + (z * z);
  3816. };
  3817. /**
  3818. * Returns a new Vector3 located at the center between "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the new Vector3
  3822. */
  3823. Vector3.Center = function (value1, value2) {
  3824. var center = value1.add(value2);
  3825. center.scaleInPlace(0.5);
  3826. return center;
  3827. };
  3828. /**
  3829. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3830. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3831. * to something in order to rotate it from its local system to the given target system
  3832. * Note: axis1, axis2 and axis3 are normalized during this operation
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @returns a new Vector3
  3837. */
  3838. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3839. var rotation = Vector3.Zero();
  3840. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3841. return rotation;
  3842. };
  3843. /**
  3844. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @param ref defines the Vector3 where to store the result
  3849. */
  3850. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3851. var quat = MathTmp.Quaternion[0];
  3852. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3853. quat.toEulerAnglesToRef(ref);
  3854. };
  3855. return Vector3;
  3856. }());
  3857. BABYLON.Vector3 = Vector3;
  3858. //Vector4 class created for EulerAngle class conversion to Quaternion
  3859. var Vector4 = /** @class */ (function () {
  3860. /**
  3861. * Creates a Vector4 object from the given floats.
  3862. */
  3863. function Vector4(x, y, z, w) {
  3864. this.x = x;
  3865. this.y = y;
  3866. this.z = z;
  3867. this.w = w;
  3868. }
  3869. /**
  3870. * Returns the string with the Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.toString = function () {
  3873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3874. };
  3875. /**
  3876. * Returns the string "Vector4".
  3877. */
  3878. Vector4.prototype.getClassName = function () {
  3879. return "Vector4";
  3880. };
  3881. /**
  3882. * Returns the Vector4 hash code.
  3883. */
  3884. Vector4.prototype.getHashCode = function () {
  3885. var hash = this.x || 0;
  3886. hash = (hash * 397) ^ (this.y || 0);
  3887. hash = (hash * 397) ^ (this.z || 0);
  3888. hash = (hash * 397) ^ (this.w || 0);
  3889. return hash;
  3890. };
  3891. // Operators
  3892. /**
  3893. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3894. */
  3895. Vector4.prototype.asArray = function () {
  3896. var result = new Array();
  3897. this.toArray(result, 0);
  3898. return result;
  3899. };
  3900. /**
  3901. * Populates the given array from the given index with the Vector4 coordinates.
  3902. * Returns the Vector4.
  3903. */
  3904. Vector4.prototype.toArray = function (array, index) {
  3905. if (index === undefined) {
  3906. index = 0;
  3907. }
  3908. array[index] = this.x;
  3909. array[index + 1] = this.y;
  3910. array[index + 2] = this.z;
  3911. array[index + 3] = this.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Adds the given vector to the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.addInPlace = function (otherVector) {
  3919. this.x += otherVector.x;
  3920. this.y += otherVector.y;
  3921. this.z += otherVector.z;
  3922. this.w += otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3927. */
  3928. Vector4.prototype.add = function (otherVector) {
  3929. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3930. };
  3931. /**
  3932. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.addToRef = function (otherVector, result) {
  3936. result.x = this.x + otherVector.x;
  3937. result.y = this.y + otherVector.y;
  3938. result.z = this.z + otherVector.z;
  3939. result.w = this.w + otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Subtract in place the given vector from the current Vector4.
  3944. * Returns the updated Vector4.
  3945. */
  3946. Vector4.prototype.subtractInPlace = function (otherVector) {
  3947. this.x -= otherVector.x;
  3948. this.y -= otherVector.y;
  3949. this.z -= otherVector.z;
  3950. this.w -= otherVector.w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3955. */
  3956. Vector4.prototype.subtract = function (otherVector) {
  3957. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3958. };
  3959. /**
  3960. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3961. * Returns the current Vector4.
  3962. */
  3963. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3964. result.x = this.x - otherVector.x;
  3965. result.y = this.y - otherVector.y;
  3966. result.z = this.z - otherVector.z;
  3967. result.w = this.w - otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3972. */
  3973. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3974. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3981. result.x = this.x - x;
  3982. result.y = this.y - y;
  3983. result.z = this.z - z;
  3984. result.w = this.w - w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3989. */
  3990. Vector4.prototype.negate = function () {
  3991. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3992. };
  3993. /**
  3994. * Multiplies the current Vector4 coordinates by scale (float).
  3995. * Returns the updated Vector4.
  3996. */
  3997. Vector4.prototype.scaleInPlace = function (scale) {
  3998. this.x *= scale;
  3999. this.y *= scale;
  4000. this.z *= scale;
  4001. this.w *= scale;
  4002. return this;
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4006. */
  4007. Vector4.prototype.scale = function (scale) {
  4008. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4009. };
  4010. /**
  4011. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.scaleToRef = function (scale, result) {
  4015. result.x = this.x * scale;
  4016. result.y = this.y * scale;
  4017. result.z = this.z * scale;
  4018. result.w = this.w * scale;
  4019. return this;
  4020. };
  4021. /**
  4022. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4023. * @param scale defines the scale factor
  4024. * @param result defines the Vector4 object where to store the result
  4025. * @returns the unmodified current Vector4
  4026. */
  4027. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4028. result.x += this.x * scale;
  4029. result.y += this.y * scale;
  4030. result.z += this.z * scale;
  4031. result.w += this.w * scale;
  4032. return this;
  4033. };
  4034. /**
  4035. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4036. */
  4037. Vector4.prototype.equals = function (otherVector) {
  4038. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4039. };
  4040. /**
  4041. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4042. */
  4043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4044. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4045. return otherVector
  4046. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4047. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4048. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4049. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4050. };
  4051. /**
  4052. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4055. return this.x === x && this.y === y && this.z === z && this.w === w;
  4056. };
  4057. /**
  4058. * Multiplies in place the current Vector4 by the given one.
  4059. * Returns the updated Vector4.
  4060. */
  4061. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4062. this.x *= otherVector.x;
  4063. this.y *= otherVector.y;
  4064. this.z *= otherVector.z;
  4065. this.w *= otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4070. */
  4071. Vector4.prototype.multiply = function (otherVector) {
  4072. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4073. };
  4074. /**
  4075. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4076. * Returns the current Vector4.
  4077. */
  4078. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4079. result.x = this.x * otherVector.x;
  4080. result.y = this.y * otherVector.y;
  4081. result.z = this.z * otherVector.z;
  4082. result.w = this.w * otherVector.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4087. */
  4088. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4089. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4093. */
  4094. Vector4.prototype.divide = function (otherVector) {
  4095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4096. };
  4097. /**
  4098. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4099. * Returns the current Vector4.
  4100. */
  4101. Vector4.prototype.divideToRef = function (otherVector, result) {
  4102. result.x = this.x / otherVector.x;
  4103. result.y = this.y / otherVector.y;
  4104. result.z = this.z / otherVector.z;
  4105. result.w = this.w / otherVector.w;
  4106. return this;
  4107. };
  4108. /**
  4109. * Divides the current Vector3 coordinates by the given ones.
  4110. * @returns the updated Vector3.
  4111. */
  4112. Vector4.prototype.divideInPlace = function (otherVector) {
  4113. return this.divideToRef(otherVector, this);
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.minimizeInPlace = function (other) {
  4121. if (other.x < this.x)
  4122. this.x = other.x;
  4123. if (other.y < this.y)
  4124. this.y = other.y;
  4125. if (other.z < this.z)
  4126. this.z = other.z;
  4127. if (other.w < this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4133. * @param other defines the second operand
  4134. * @returns the current updated Vector4
  4135. */
  4136. Vector4.prototype.maximizeInPlace = function (other) {
  4137. if (other.x > this.x)
  4138. this.x = other.x;
  4139. if (other.y > this.y)
  4140. this.y = other.y;
  4141. if (other.z > this.z)
  4142. this.z = other.z;
  4143. if (other.w > this.w)
  4144. this.w = other.w;
  4145. return this;
  4146. };
  4147. /**
  4148. * Gets a new Vector4 from current Vector4 floored values
  4149. * @returns a new Vector4
  4150. */
  4151. Vector4.prototype.floor = function () {
  4152. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4153. };
  4154. /**
  4155. * Gets a new Vector4 from current Vector3 floored values
  4156. * @returns a new Vector4
  4157. */
  4158. Vector4.prototype.fract = function () {
  4159. 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));
  4160. };
  4161. // Properties
  4162. /**
  4163. * Returns the Vector4 length (float).
  4164. */
  4165. Vector4.prototype.length = function () {
  4166. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4167. };
  4168. /**
  4169. * Returns the Vector4 squared length (float).
  4170. */
  4171. Vector4.prototype.lengthSquared = function () {
  4172. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4173. };
  4174. // Methods
  4175. /**
  4176. * Normalizes in place the Vector4.
  4177. * Returns the updated Vector4.
  4178. */
  4179. Vector4.prototype.normalize = function () {
  4180. var len = this.length();
  4181. if (len === 0)
  4182. return this;
  4183. var num = 1.0 / len;
  4184. this.x *= num;
  4185. this.y *= num;
  4186. this.z *= num;
  4187. this.w *= num;
  4188. return this;
  4189. };
  4190. /**
  4191. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4192. */
  4193. Vector4.prototype.toVector3 = function () {
  4194. return new Vector3(this.x, this.y, this.z);
  4195. };
  4196. /**
  4197. * Returns a new Vector4 copied from the current one.
  4198. */
  4199. Vector4.prototype.clone = function () {
  4200. return new Vector4(this.x, this.y, this.z, this.w);
  4201. };
  4202. /**
  4203. * Updates the current Vector4 with the given one coordinates.
  4204. * Returns the updated Vector4.
  4205. */
  4206. Vector4.prototype.copyFrom = function (source) {
  4207. this.x = source.x;
  4208. this.y = source.y;
  4209. this.z = source.z;
  4210. this.w = source.w;
  4211. return this;
  4212. };
  4213. /**
  4214. * Updates the current Vector4 coordinates with the given floats.
  4215. * Returns the updated Vector4.
  4216. */
  4217. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4218. this.x = x;
  4219. this.y = y;
  4220. this.z = z;
  4221. this.w = w;
  4222. return this;
  4223. };
  4224. /**
  4225. * Updates the current Vector4 coordinates with the given floats.
  4226. * Returns the updated Vector4.
  4227. */
  4228. Vector4.prototype.set = function (x, y, z, w) {
  4229. return this.copyFromFloats(x, y, z, w);
  4230. };
  4231. // Statics
  4232. /**
  4233. * Returns a new Vector4 set from the starting index of the given array.
  4234. */
  4235. Vector4.FromArray = function (array, offset) {
  4236. if (!offset) {
  4237. offset = 0;
  4238. }
  4239. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4240. };
  4241. /**
  4242. * Updates the given vector "result" from the starting index of the given array.
  4243. */
  4244. Vector4.FromArrayToRef = function (array, offset, result) {
  4245. result.x = array[offset];
  4246. result.y = array[offset + 1];
  4247. result.z = array[offset + 2];
  4248. result.w = array[offset + 3];
  4249. };
  4250. /**
  4251. * Updates the given vector "result" from the starting index of the given Float32Array.
  4252. */
  4253. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4254. Vector4.FromArrayToRef(array, offset, result);
  4255. };
  4256. /**
  4257. * Updates the given vector "result" coordinates from the given floats.
  4258. */
  4259. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4260. result.x = x;
  4261. result.y = y;
  4262. result.z = z;
  4263. result.w = w;
  4264. };
  4265. /**
  4266. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4267. */
  4268. Vector4.Zero = function () {
  4269. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4270. };
  4271. /**
  4272. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4273. */
  4274. Vector4.One = function () {
  4275. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4276. };
  4277. /**
  4278. * Returns a new normalized Vector4 from the given one.
  4279. */
  4280. Vector4.Normalize = function (vector) {
  4281. var result = Vector4.Zero();
  4282. Vector4.NormalizeToRef(vector, result);
  4283. return result;
  4284. };
  4285. /**
  4286. * Updates the given vector "result" from the normalization of the given one.
  4287. */
  4288. Vector4.NormalizeToRef = function (vector, result) {
  4289. result.copyFrom(vector);
  4290. result.normalize();
  4291. };
  4292. Vector4.Minimize = function (left, right) {
  4293. var min = left.clone();
  4294. min.minimizeInPlace(right);
  4295. return min;
  4296. };
  4297. Vector4.Maximize = function (left, right) {
  4298. var max = left.clone();
  4299. max.maximizeInPlace(right);
  4300. return max;
  4301. };
  4302. /**
  4303. * Returns the distance (float) between the vectors "value1" and "value2".
  4304. */
  4305. Vector4.Distance = function (value1, value2) {
  4306. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4307. };
  4308. /**
  4309. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4310. */
  4311. Vector4.DistanceSquared = function (value1, value2) {
  4312. var x = value1.x - value2.x;
  4313. var y = value1.y - value2.y;
  4314. var z = value1.z - value2.z;
  4315. var w = value1.w - value2.w;
  4316. return (x * x) + (y * y) + (z * z) + (w * w);
  4317. };
  4318. /**
  4319. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4320. */
  4321. Vector4.Center = function (value1, value2) {
  4322. var center = value1.add(value2);
  4323. center.scaleInPlace(0.5);
  4324. return center;
  4325. };
  4326. /**
  4327. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4328. * This methods computes transformed normalized direction vectors only.
  4329. */
  4330. Vector4.TransformNormal = function (vector, transformation) {
  4331. var result = Vector4.Zero();
  4332. Vector4.TransformNormalToRef(vector, transformation, result);
  4333. return result;
  4334. };
  4335. /**
  4336. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4337. * This methods computes transformed normalized direction vectors only.
  4338. */
  4339. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4340. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4341. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4342. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4343. result.x = x;
  4344. result.y = y;
  4345. result.z = z;
  4346. result.w = vector.w;
  4347. };
  4348. /**
  4349. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4350. * This methods computes transformed normalized direction vectors only.
  4351. */
  4352. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4353. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4354. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4355. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4356. result.w = w;
  4357. };
  4358. return Vector4;
  4359. }());
  4360. BABYLON.Vector4 = Vector4;
  4361. var Size = /** @class */ (function () {
  4362. /**
  4363. * Creates a Size object from the given width and height (floats).
  4364. */
  4365. function Size(width, height) {
  4366. this.width = width;
  4367. this.height = height;
  4368. }
  4369. // Returns a string with the Size width and height.
  4370. Size.prototype.toString = function () {
  4371. return "{W: " + this.width + ", H: " + this.height + "}";
  4372. };
  4373. /**
  4374. * Returns the string "Size"
  4375. */
  4376. Size.prototype.getClassName = function () {
  4377. return "Size";
  4378. };
  4379. /**
  4380. * Returns the Size hash code.
  4381. */
  4382. Size.prototype.getHashCode = function () {
  4383. var hash = this.width || 0;
  4384. hash = (hash * 397) ^ (this.height || 0);
  4385. return hash;
  4386. };
  4387. /**
  4388. * Updates the current size from the given one.
  4389. * Returns the updated Size.
  4390. */
  4391. Size.prototype.copyFrom = function (src) {
  4392. this.width = src.width;
  4393. this.height = src.height;
  4394. };
  4395. /**
  4396. * Updates in place the current Size from the given floats.
  4397. * Returns the updated Size.
  4398. */
  4399. Size.prototype.copyFromFloats = function (width, height) {
  4400. this.width = width;
  4401. this.height = height;
  4402. return this;
  4403. };
  4404. /**
  4405. * Updates in place the current Size from the given floats.
  4406. * Returns the updated Size.
  4407. */
  4408. Size.prototype.set = function (width, height) {
  4409. return this.copyFromFloats(width, height);
  4410. };
  4411. /**
  4412. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4413. */
  4414. Size.prototype.multiplyByFloats = function (w, h) {
  4415. return new Size(this.width * w, this.height * h);
  4416. };
  4417. /**
  4418. * Returns a new Size copied from the given one.
  4419. */
  4420. Size.prototype.clone = function () {
  4421. return new Size(this.width, this.height);
  4422. };
  4423. /**
  4424. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4425. */
  4426. Size.prototype.equals = function (other) {
  4427. if (!other) {
  4428. return false;
  4429. }
  4430. return (this.width === other.width) && (this.height === other.height);
  4431. };
  4432. Object.defineProperty(Size.prototype, "surface", {
  4433. /**
  4434. * Returns the surface of the Size : width * height (float).
  4435. */
  4436. get: function () {
  4437. return this.width * this.height;
  4438. },
  4439. enumerable: true,
  4440. configurable: true
  4441. });
  4442. /**
  4443. * Returns a new Size set to (0.0, 0.0)
  4444. */
  4445. Size.Zero = function () {
  4446. return new Size(0.0, 0.0);
  4447. };
  4448. /**
  4449. * Returns a new Size set as the addition result of the current Size and the given one.
  4450. */
  4451. Size.prototype.add = function (otherSize) {
  4452. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4453. return r;
  4454. };
  4455. /**
  4456. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4457. */
  4458. Size.prototype.subtract = function (otherSize) {
  4459. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4460. return r;
  4461. };
  4462. /**
  4463. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4464. */
  4465. Size.Lerp = function (start, end, amount) {
  4466. var w = start.width + ((end.width - start.width) * amount);
  4467. var h = start.height + ((end.height - start.height) * amount);
  4468. return new Size(w, h);
  4469. };
  4470. return Size;
  4471. }());
  4472. BABYLON.Size = Size;
  4473. /**
  4474. * Class used to store quaternion data
  4475. * @see https://en.wikipedia.org/wiki/Quaternion
  4476. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4477. */
  4478. var Quaternion = /** @class */ (function () {
  4479. /**
  4480. * Creates a new Quaternion from the given floats
  4481. * @param x defines the first component (0 by default)
  4482. * @param y defines the second component (0 by default)
  4483. * @param z defines the third component (0 by default)
  4484. * @param w defines the fourth component (1.0 by default)
  4485. */
  4486. function Quaternion(
  4487. /** defines the first component (0 by default) */
  4488. x,
  4489. /** defines the second component (0 by default) */
  4490. y,
  4491. /** defines the third component (0 by default) */
  4492. z,
  4493. /** defines the fourth component (1.0 by default) */
  4494. w) {
  4495. if (x === void 0) { x = 0.0; }
  4496. if (y === void 0) { y = 0.0; }
  4497. if (z === void 0) { z = 0.0; }
  4498. if (w === void 0) { w = 1.0; }
  4499. this.x = x;
  4500. this.y = y;
  4501. this.z = z;
  4502. this.w = w;
  4503. }
  4504. /**
  4505. * Gets a string representation for the current quaternion
  4506. * @returns a string with the Quaternion coordinates
  4507. */
  4508. Quaternion.prototype.toString = function () {
  4509. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4510. };
  4511. /**
  4512. * Gets the class name of the quaternion
  4513. * @returns the string "Quaternion"
  4514. */
  4515. Quaternion.prototype.getClassName = function () {
  4516. return "Quaternion";
  4517. };
  4518. /**
  4519. * Gets a hash code for this quaternion
  4520. * @returns the quaternion hash code
  4521. */
  4522. Quaternion.prototype.getHashCode = function () {
  4523. var hash = this.x || 0;
  4524. hash = (hash * 397) ^ (this.y || 0);
  4525. hash = (hash * 397) ^ (this.z || 0);
  4526. hash = (hash * 397) ^ (this.w || 0);
  4527. return hash;
  4528. };
  4529. /**
  4530. * Copy the quaternion to an array
  4531. * @returns a new array populated with 4 elements from the quaternion coordinates
  4532. */
  4533. Quaternion.prototype.asArray = function () {
  4534. return [this.x, this.y, this.z, this.w];
  4535. };
  4536. /**
  4537. * Check if two quaternions are equals
  4538. * @param otherQuaternion defines the second operand
  4539. * @return true if the current quaternion and the given one coordinates are strictly equals
  4540. */
  4541. Quaternion.prototype.equals = function (otherQuaternion) {
  4542. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4543. };
  4544. /**
  4545. * Clone the current quaternion
  4546. * @returns a new quaternion copied from the current one
  4547. */
  4548. Quaternion.prototype.clone = function () {
  4549. return new Quaternion(this.x, this.y, this.z, this.w);
  4550. };
  4551. /**
  4552. * Copy a quaternion to the current one
  4553. * @param other defines the other quaternion
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.copyFrom = function (other) {
  4557. this.x = other.x;
  4558. this.y = other.y;
  4559. this.z = other.z;
  4560. this.w = other.w;
  4561. return this;
  4562. };
  4563. /**
  4564. * Updates the current quaternion with the given float coordinates
  4565. * @param x defines the x coordinate
  4566. * @param y defines the y coordinate
  4567. * @param z defines the z coordinate
  4568. * @param w defines the w coordinate
  4569. * @returns the updated current quaternion
  4570. */
  4571. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4572. this.x = x;
  4573. this.y = y;
  4574. this.z = z;
  4575. this.w = w;
  4576. return this;
  4577. };
  4578. /**
  4579. * Updates the current quaternion from the given float coordinates
  4580. * @param x defines the x coordinate
  4581. * @param y defines the y coordinate
  4582. * @param z defines the z coordinate
  4583. * @param w defines the w coordinate
  4584. * @returns the updated current quaternion
  4585. */
  4586. Quaternion.prototype.set = function (x, y, z, w) {
  4587. return this.copyFromFloats(x, y, z, w);
  4588. };
  4589. /**
  4590. * Adds two quaternions
  4591. * @param other defines the second operand
  4592. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4593. */
  4594. Quaternion.prototype.add = function (other) {
  4595. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4596. };
  4597. /**
  4598. * Add a quaternion to the current one
  4599. * @param other defines the quaternion to add
  4600. * @returns the current quaternion
  4601. */
  4602. Quaternion.prototype.addInPlace = function (other) {
  4603. this.x += other.x;
  4604. this.y += other.y;
  4605. this.z += other.z;
  4606. this.w += other.w;
  4607. return this;
  4608. };
  4609. /**
  4610. * Subtract two quaternions
  4611. * @param other defines the second operand
  4612. * @returns a new quaternion as the subtraction result of the given one from the current one
  4613. */
  4614. Quaternion.prototype.subtract = function (other) {
  4615. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4616. };
  4617. /**
  4618. * Multiplies the current quaternion by a scale factor
  4619. * @param value defines the scale factor
  4620. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4621. */
  4622. Quaternion.prototype.scale = function (value) {
  4623. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4624. };
  4625. /**
  4626. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4627. * @param scale defines the scale factor
  4628. * @param result defines the Quaternion object where to store the result
  4629. * @returns the unmodified current quaternion
  4630. */
  4631. Quaternion.prototype.scaleToRef = function (scale, result) {
  4632. result.x = this.x * scale;
  4633. result.y = this.y * scale;
  4634. result.z = this.z * scale;
  4635. result.w = this.w * scale;
  4636. return this;
  4637. };
  4638. /**
  4639. * Multiplies in place the current quaternion by a scale factor
  4640. * @param value defines the scale factor
  4641. * @returns the current modified quaternion
  4642. */
  4643. Quaternion.prototype.scaleInPlace = function (value) {
  4644. this.x *= value;
  4645. this.y *= value;
  4646. this.z *= value;
  4647. this.w *= value;
  4648. return this;
  4649. };
  4650. /**
  4651. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4652. * @param scale defines the scale factor
  4653. * @param result defines the Quaternion object where to store the result
  4654. * @returns the unmodified current quaternion
  4655. */
  4656. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4657. result.x += this.x * scale;
  4658. result.y += this.y * scale;
  4659. result.z += this.z * scale;
  4660. result.w += this.w * scale;
  4661. return this;
  4662. };
  4663. /**
  4664. * Multiplies two quaternions
  4665. * @param q1 defines the second operand
  4666. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4667. */
  4668. Quaternion.prototype.multiply = function (q1) {
  4669. var result = new Quaternion(0, 0, 0, 1.0);
  4670. this.multiplyToRef(q1, result);
  4671. return result;
  4672. };
  4673. /**
  4674. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4675. * @param q1 defines the second operand
  4676. * @param result defines the target quaternion
  4677. * @returns the current quaternion
  4678. */
  4679. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4680. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4681. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4682. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4683. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4684. result.copyFromFloats(x, y, z, w);
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4689. * @param q1 defines the second operand
  4690. * @returns the currentupdated quaternion
  4691. */
  4692. Quaternion.prototype.multiplyInPlace = function (q1) {
  4693. this.multiplyToRef(q1, this);
  4694. return this;
  4695. };
  4696. /**
  4697. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4698. * @param ref defines the target quaternion
  4699. * @returns the current quaternion
  4700. */
  4701. Quaternion.prototype.conjugateToRef = function (ref) {
  4702. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4703. return this;
  4704. };
  4705. /**
  4706. * Conjugates in place (1-q) the current quaternion
  4707. * @returns the current updated quaternion
  4708. */
  4709. Quaternion.prototype.conjugateInPlace = function () {
  4710. this.x *= -1;
  4711. this.y *= -1;
  4712. this.z *= -1;
  4713. return this;
  4714. };
  4715. /**
  4716. * Conjugates in place (1-q) the current quaternion
  4717. * @returns a new quaternion
  4718. */
  4719. Quaternion.prototype.conjugate = function () {
  4720. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4721. return result;
  4722. };
  4723. /**
  4724. * Gets length of current quaternion
  4725. * @returns the quaternion length (float)
  4726. */
  4727. Quaternion.prototype.length = function () {
  4728. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4729. };
  4730. /**
  4731. * Normalize in place the current quaternion
  4732. * @returns the current updated quaternion
  4733. */
  4734. Quaternion.prototype.normalize = function () {
  4735. var length = 1.0 / this.length();
  4736. this.x *= length;
  4737. this.y *= length;
  4738. this.z *= length;
  4739. this.w *= length;
  4740. return this;
  4741. };
  4742. /**
  4743. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4744. * @param order is a reserved parameter and is ignore for now
  4745. * @returns a new Vector3 containing the Euler angles
  4746. */
  4747. Quaternion.prototype.toEulerAngles = function (order) {
  4748. if (order === void 0) { order = "YZX"; }
  4749. var result = Vector3.Zero();
  4750. this.toEulerAnglesToRef(result, order);
  4751. return result;
  4752. };
  4753. /**
  4754. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4755. * @param result defines the vector which will be filled with the Euler angles
  4756. * @param order is a reserved parameter and is ignore for now
  4757. * @returns the current unchanged quaternion
  4758. */
  4759. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4760. if (order === void 0) { order = "YZX"; }
  4761. var qz = this.z;
  4762. var qx = this.x;
  4763. var qy = this.y;
  4764. var qw = this.w;
  4765. var sqw = qw * qw;
  4766. var sqz = qz * qz;
  4767. var sqx = qx * qx;
  4768. var sqy = qy * qy;
  4769. var zAxisY = qy * qz - qx * qw;
  4770. var limit = .4999999;
  4771. if (zAxisY < -limit) {
  4772. result.y = 2 * Math.atan2(qy, qw);
  4773. result.x = Math.PI / 2;
  4774. result.z = 0;
  4775. }
  4776. else if (zAxisY > limit) {
  4777. result.y = 2 * Math.atan2(qy, qw);
  4778. result.x = -Math.PI / 2;
  4779. result.z = 0;
  4780. }
  4781. else {
  4782. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4783. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4784. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4785. }
  4786. return this;
  4787. };
  4788. /**
  4789. * Updates the given rotation matrix with the current quaternion values
  4790. * @param result defines the target matrix
  4791. * @returns the current unchanged quaternion
  4792. */
  4793. Quaternion.prototype.toRotationMatrix = function (result) {
  4794. var xx = this.x * this.x;
  4795. var yy = this.y * this.y;
  4796. var zz = this.z * this.z;
  4797. var xy = this.x * this.y;
  4798. var zw = this.z * this.w;
  4799. var zx = this.z * this.x;
  4800. var yw = this.y * this.w;
  4801. var yz = this.y * this.z;
  4802. var xw = this.x * this.w;
  4803. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4804. result.m[1] = 2.0 * (xy + zw);
  4805. result.m[2] = 2.0 * (zx - yw);
  4806. result.m[3] = 0;
  4807. result.m[4] = 2.0 * (xy - zw);
  4808. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4809. result.m[6] = 2.0 * (yz + xw);
  4810. result.m[7] = 0;
  4811. result.m[8] = 2.0 * (zx + yw);
  4812. result.m[9] = 2.0 * (yz - xw);
  4813. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4814. result.m[11] = 0;
  4815. result.m[12] = 0;
  4816. result.m[13] = 0;
  4817. result.m[14] = 0;
  4818. result.m[15] = 1.0;
  4819. result._markAsUpdated();
  4820. return this;
  4821. };
  4822. /**
  4823. * Updates the current quaternion from the given rotation matrix values
  4824. * @param matrix defines the source matrix
  4825. * @returns the current updated quaternion
  4826. */
  4827. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4828. Quaternion.FromRotationMatrixToRef(matrix, this);
  4829. return this;
  4830. };
  4831. // Statics
  4832. /**
  4833. * Creates a new quaternion from a rotation matrix
  4834. * @param matrix defines the source matrix
  4835. * @returns a new quaternion created from the given rotation matrix values
  4836. */
  4837. Quaternion.FromRotationMatrix = function (matrix) {
  4838. var result = new Quaternion();
  4839. Quaternion.FromRotationMatrixToRef(matrix, result);
  4840. return result;
  4841. };
  4842. /**
  4843. * Updates the given quaternion with the given rotation matrix values
  4844. * @param matrix defines the source matrix
  4845. * @param result defines the target quaternion
  4846. */
  4847. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4848. var data = matrix.m;
  4849. var m11 = data[0], m12 = data[4], m13 = data[8];
  4850. var m21 = data[1], m22 = data[5], m23 = data[9];
  4851. var m31 = data[2], m32 = data[6], m33 = data[10];
  4852. var trace = m11 + m22 + m33;
  4853. var s;
  4854. if (trace > 0) {
  4855. s = 0.5 / Math.sqrt(trace + 1.0);
  4856. result.w = 0.25 / s;
  4857. result.x = (m32 - m23) * s;
  4858. result.y = (m13 - m31) * s;
  4859. result.z = (m21 - m12) * s;
  4860. }
  4861. else if (m11 > m22 && m11 > m33) {
  4862. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4863. result.w = (m32 - m23) / s;
  4864. result.x = 0.25 * s;
  4865. result.y = (m12 + m21) / s;
  4866. result.z = (m13 + m31) / s;
  4867. }
  4868. else if (m22 > m33) {
  4869. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4870. result.w = (m13 - m31) / s;
  4871. result.x = (m12 + m21) / s;
  4872. result.y = 0.25 * s;
  4873. result.z = (m23 + m32) / s;
  4874. }
  4875. else {
  4876. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4877. result.w = (m21 - m12) / s;
  4878. result.x = (m13 + m31) / s;
  4879. result.y = (m23 + m32) / s;
  4880. result.z = 0.25 * s;
  4881. }
  4882. };
  4883. /**
  4884. * Returns the dot product (float) between the quaternions "left" and "right"
  4885. * @param left defines the left operand
  4886. * @param right defines the right operand
  4887. * @returns the dot product
  4888. */
  4889. Quaternion.Dot = function (left, right) {
  4890. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4891. };
  4892. /**
  4893. * Checks if the two quaternions are close to each other
  4894. * @param quat0 defines the first quaternion to check
  4895. * @param quat1 defines the second quaternion to check
  4896. * @returns true if the two quaternions are close to each other
  4897. */
  4898. Quaternion.AreClose = function (quat0, quat1) {
  4899. var dot = Quaternion.Dot(quat0, quat1);
  4900. return dot >= 0;
  4901. };
  4902. /**
  4903. * Creates an empty quaternion
  4904. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4905. */
  4906. Quaternion.Zero = function () {
  4907. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4908. };
  4909. /**
  4910. * Inverse a given quaternion
  4911. * @param q defines the source quaternion
  4912. * @returns a new quaternion as the inverted current quaternion
  4913. */
  4914. Quaternion.Inverse = function (q) {
  4915. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4916. };
  4917. /**
  4918. * Creates an identity quaternion
  4919. * @returns the identity quaternion
  4920. */
  4921. Quaternion.Identity = function () {
  4922. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4923. };
  4924. /**
  4925. * Gets a boolean indicating if the given quaternion is identity
  4926. * @param quaternion defines the quaternion to check
  4927. * @returns true if the quaternion is identity
  4928. */
  4929. Quaternion.IsIdentity = function (quaternion) {
  4930. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4931. };
  4932. /**
  4933. * Creates a quaternion from a rotation around an axis
  4934. * @param axis defines the axis to use
  4935. * @param angle defines the angle to use
  4936. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4937. */
  4938. Quaternion.RotationAxis = function (axis, angle) {
  4939. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4940. };
  4941. /**
  4942. * Creates a rotation around an axis and stores it into the given quaternion
  4943. * @param axis defines the axis to use
  4944. * @param angle defines the angle to use
  4945. * @param result defines the target quaternion
  4946. * @returns the target quaternion
  4947. */
  4948. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4949. var sin = Math.sin(angle / 2);
  4950. axis.normalize();
  4951. result.w = Math.cos(angle / 2);
  4952. result.x = axis.x * sin;
  4953. result.y = axis.y * sin;
  4954. result.z = axis.z * sin;
  4955. return result;
  4956. };
  4957. /**
  4958. * Creates a new quaternion from data stored into an array
  4959. * @param array defines the data source
  4960. * @param offset defines the offset in the source array where the data starts
  4961. * @returns a new quaternion
  4962. */
  4963. Quaternion.FromArray = function (array, offset) {
  4964. if (!offset) {
  4965. offset = 0;
  4966. }
  4967. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4968. };
  4969. /**
  4970. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4971. * @param yaw defines the rotation around Y axis
  4972. * @param pitch defines the rotation around X axis
  4973. * @param roll defines the rotation around Z axis
  4974. * @returns the new quaternion
  4975. */
  4976. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4977. var q = new Quaternion();
  4978. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4979. return q;
  4980. };
  4981. /**
  4982. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4983. * @param yaw defines the rotation around Y axis
  4984. * @param pitch defines the rotation around X axis
  4985. * @param roll defines the rotation around Z axis
  4986. * @param result defines the target quaternion
  4987. */
  4988. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4989. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4990. var halfRoll = roll * 0.5;
  4991. var halfPitch = pitch * 0.5;
  4992. var halfYaw = yaw * 0.5;
  4993. var sinRoll = Math.sin(halfRoll);
  4994. var cosRoll = Math.cos(halfRoll);
  4995. var sinPitch = Math.sin(halfPitch);
  4996. var cosPitch = Math.cos(halfPitch);
  4997. var sinYaw = Math.sin(halfYaw);
  4998. var cosYaw = Math.cos(halfYaw);
  4999. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5000. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5001. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5002. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5003. };
  5004. /**
  5005. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5006. * @param alpha defines the rotation around first axis
  5007. * @param beta defines the rotation around second axis
  5008. * @param gamma defines the rotation around third axis
  5009. * @returns the new quaternion
  5010. */
  5011. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5012. var result = new Quaternion();
  5013. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5014. return result;
  5015. };
  5016. /**
  5017. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5018. * @param alpha defines the rotation around first axis
  5019. * @param beta defines the rotation around second axis
  5020. * @param gamma defines the rotation around third axis
  5021. * @param result defines the target quaternion
  5022. */
  5023. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5024. // Produces a quaternion from Euler angles in the z-x-z orientation
  5025. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5026. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5027. var halfBeta = beta * 0.5;
  5028. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5029. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5030. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5031. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5032. };
  5033. /**
  5034. * 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)
  5035. * @param axis1 defines the first axis
  5036. * @param axis2 defines the second axis
  5037. * @param axis3 defines the third axis
  5038. * @returns the new quaternion
  5039. */
  5040. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5041. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5042. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5043. return quat;
  5044. };
  5045. /**
  5046. * 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
  5047. * @param axis1 defines the first axis
  5048. * @param axis2 defines the second axis
  5049. * @param axis3 defines the third axis
  5050. * @param ref defines the target quaternion
  5051. */
  5052. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5053. var rotMat = MathTmp.Matrix[0];
  5054. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5055. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5056. };
  5057. /**
  5058. * Interpolates between two quaternions
  5059. * @param left defines first quaternion
  5060. * @param right defines second quaternion
  5061. * @param amount defines the gradient to use
  5062. * @returns the new interpolated quaternion
  5063. */
  5064. Quaternion.Slerp = function (left, right, amount) {
  5065. var result = Quaternion.Identity();
  5066. Quaternion.SlerpToRef(left, right, amount, result);
  5067. return result;
  5068. };
  5069. /**
  5070. * Interpolates between two quaternions and stores it into a target quaternion
  5071. * @param left defines first quaternion
  5072. * @param right defines second quaternion
  5073. * @param amount defines the gradient to use
  5074. * @param result defines the target quaternion
  5075. */
  5076. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5077. var num2;
  5078. var num3;
  5079. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5080. var flag = false;
  5081. if (num4 < 0) {
  5082. flag = true;
  5083. num4 = -num4;
  5084. }
  5085. if (num4 > 0.999999) {
  5086. num3 = 1 - amount;
  5087. num2 = flag ? -amount : amount;
  5088. }
  5089. else {
  5090. var num5 = Math.acos(num4);
  5091. var num6 = (1.0 / Math.sin(num5));
  5092. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5093. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5094. }
  5095. result.x = (num3 * left.x) + (num2 * right.x);
  5096. result.y = (num3 * left.y) + (num2 * right.y);
  5097. result.z = (num3 * left.z) + (num2 * right.z);
  5098. result.w = (num3 * left.w) + (num2 * right.w);
  5099. };
  5100. /**
  5101. * Interpolate between two quaternions using Hermite interpolation
  5102. * @param value1 defines first quaternion
  5103. * @param tangent1 defines the incoming tangent
  5104. * @param value2 defines second quaternion
  5105. * @param tangent2 defines the outgoing tangent
  5106. * @param amount defines the target quaternion
  5107. * @returns the new interpolated quaternion
  5108. */
  5109. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5110. var squared = amount * amount;
  5111. var cubed = amount * squared;
  5112. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5113. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5114. var part3 = (cubed - (2.0 * squared)) + amount;
  5115. var part4 = cubed - squared;
  5116. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5117. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5118. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5119. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5120. return new Quaternion(x, y, z, w);
  5121. };
  5122. return Quaternion;
  5123. }());
  5124. BABYLON.Quaternion = Quaternion;
  5125. /**
  5126. * Class used to store matrix data (4x4)
  5127. */
  5128. var Matrix = /** @class */ (function () {
  5129. /**
  5130. * Creates an empty matrix (filled with zeros)
  5131. */
  5132. function Matrix() {
  5133. this._isIdentity = false;
  5134. this._isIdentityDirty = true;
  5135. /**
  5136. * Gets or sets the internal data of the matrix
  5137. */
  5138. this.m = new Float32Array(16);
  5139. this._markAsUpdated();
  5140. }
  5141. /** @hidden */
  5142. Matrix.prototype._markAsUpdated = function () {
  5143. this.updateFlag = Matrix._updateFlagSeed++;
  5144. this._isIdentityDirty = true;
  5145. };
  5146. // Properties
  5147. /**
  5148. * Check if the current matrix is indentity
  5149. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5150. * @returns true is the matrix is the identity matrix
  5151. */
  5152. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5153. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5154. if (this._isIdentityDirty) {
  5155. this._isIdentityDirty = false;
  5156. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5157. this._isIdentity = false;
  5158. }
  5159. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5160. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5161. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5162. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5163. this._isIdentity = false;
  5164. }
  5165. else {
  5166. this._isIdentity = true;
  5167. }
  5168. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5169. this._isIdentity = false;
  5170. }
  5171. }
  5172. return this._isIdentity;
  5173. };
  5174. /**
  5175. * Gets the determinant of the matrix
  5176. * @returns the matrix determinant
  5177. */
  5178. Matrix.prototype.determinant = function () {
  5179. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5180. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5181. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5182. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5183. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5184. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5185. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5186. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5187. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5188. };
  5189. // Methods
  5190. /**
  5191. * Returns the matrix as a Float32Array
  5192. * @returns the matrix underlying array
  5193. */
  5194. Matrix.prototype.toArray = function () {
  5195. return this.m;
  5196. };
  5197. /**
  5198. * Returns the matrix as a Float32Array
  5199. * @returns the matrix underlying array.
  5200. */
  5201. Matrix.prototype.asArray = function () {
  5202. return this.toArray();
  5203. };
  5204. /**
  5205. * Inverts the current matrix in place
  5206. * @returns the current inverted matrix
  5207. */
  5208. Matrix.prototype.invert = function () {
  5209. this.invertToRef(this);
  5210. return this;
  5211. };
  5212. /**
  5213. * Sets all the matrix elements to zero
  5214. * @returns the current matrix
  5215. */
  5216. Matrix.prototype.reset = function () {
  5217. for (var index = 0; index < 16; index++) {
  5218. this.m[index] = 0.0;
  5219. }
  5220. this._markAsUpdated();
  5221. return this;
  5222. };
  5223. /**
  5224. * Adds the current matrix with a second one
  5225. * @param other defines the matrix to add
  5226. * @returns a new matrix as the addition of the current matrix and the given one
  5227. */
  5228. Matrix.prototype.add = function (other) {
  5229. var result = new Matrix();
  5230. this.addToRef(other, result);
  5231. return result;
  5232. };
  5233. /**
  5234. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5235. * @param other defines the matrix to add
  5236. * @param result defines the target matrix
  5237. * @returns the current matrix
  5238. */
  5239. Matrix.prototype.addToRef = function (other, result) {
  5240. for (var index = 0; index < 16; index++) {
  5241. result.m[index] = this.m[index] + other.m[index];
  5242. }
  5243. result._markAsUpdated();
  5244. return this;
  5245. };
  5246. /**
  5247. * Adds in place the given matrix to the current matrix
  5248. * @param other defines the second operand
  5249. * @returns the current updated matrix
  5250. */
  5251. Matrix.prototype.addToSelf = function (other) {
  5252. for (var index = 0; index < 16; index++) {
  5253. this.m[index] += other.m[index];
  5254. }
  5255. this._markAsUpdated();
  5256. return this;
  5257. };
  5258. /**
  5259. * Sets the given matrix to the current inverted Matrix
  5260. * @param other defines the target matrix
  5261. * @returns the unmodified current matrix
  5262. */
  5263. Matrix.prototype.invertToRef = function (other) {
  5264. var l1 = this.m[0];
  5265. var l2 = this.m[1];
  5266. var l3 = this.m[2];
  5267. var l4 = this.m[3];
  5268. var l5 = this.m[4];
  5269. var l6 = this.m[5];
  5270. var l7 = this.m[6];
  5271. var l8 = this.m[7];
  5272. var l9 = this.m[8];
  5273. var l10 = this.m[9];
  5274. var l11 = this.m[10];
  5275. var l12 = this.m[11];
  5276. var l13 = this.m[12];
  5277. var l14 = this.m[13];
  5278. var l15 = this.m[14];
  5279. var l16 = this.m[15];
  5280. var l17 = (l11 * l16) - (l12 * l15);
  5281. var l18 = (l10 * l16) - (l12 * l14);
  5282. var l19 = (l10 * l15) - (l11 * l14);
  5283. var l20 = (l9 * l16) - (l12 * l13);
  5284. var l21 = (l9 * l15) - (l11 * l13);
  5285. var l22 = (l9 * l14) - (l10 * l13);
  5286. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5287. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5288. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5289. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5290. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5291. var l28 = (l7 * l16) - (l8 * l15);
  5292. var l29 = (l6 * l16) - (l8 * l14);
  5293. var l30 = (l6 * l15) - (l7 * l14);
  5294. var l31 = (l5 * l16) - (l8 * l13);
  5295. var l32 = (l5 * l15) - (l7 * l13);
  5296. var l33 = (l5 * l14) - (l6 * l13);
  5297. var l34 = (l7 * l12) - (l8 * l11);
  5298. var l35 = (l6 * l12) - (l8 * l10);
  5299. var l36 = (l6 * l11) - (l7 * l10);
  5300. var l37 = (l5 * l12) - (l8 * l9);
  5301. var l38 = (l5 * l11) - (l7 * l9);
  5302. var l39 = (l5 * l10) - (l6 * l9);
  5303. other.m[0] = l23 * l27;
  5304. other.m[4] = l24 * l27;
  5305. other.m[8] = l25 * l27;
  5306. other.m[12] = l26 * l27;
  5307. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5308. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5309. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5310. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5311. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5312. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5313. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5314. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5315. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5316. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5317. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5318. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5319. other._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Inserts the translation vector (using 3 floats) in the current matrix
  5324. * @param x defines the 1st component of the translation
  5325. * @param y defines the 2nd component of the translation
  5326. * @param z defines the 3rd component of the translation
  5327. * @returns the current updated matrix
  5328. */
  5329. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5330. this.m[12] = x;
  5331. this.m[13] = y;
  5332. this.m[14] = z;
  5333. this._markAsUpdated();
  5334. return this;
  5335. };
  5336. /**
  5337. * Inserts the translation vector in the current matrix
  5338. * @param vector3 defines the translation to insert
  5339. * @returns the current updated matrix
  5340. */
  5341. Matrix.prototype.setTranslation = function (vector3) {
  5342. this.m[12] = vector3.x;
  5343. this.m[13] = vector3.y;
  5344. this.m[14] = vector3.z;
  5345. this._markAsUpdated();
  5346. return this;
  5347. };
  5348. /**
  5349. * Gets the translation value of the current matrix
  5350. * @returns a new Vector3 as the extracted translation from the matrix
  5351. */
  5352. Matrix.prototype.getTranslation = function () {
  5353. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5354. };
  5355. /**
  5356. * Fill a Vector3 with the extracted translation from the matrix
  5357. * @param result defines the Vector3 where to store the translation
  5358. * @returns the current matrix
  5359. */
  5360. Matrix.prototype.getTranslationToRef = function (result) {
  5361. result.x = this.m[12];
  5362. result.y = this.m[13];
  5363. result.z = this.m[14];
  5364. return this;
  5365. };
  5366. /**
  5367. * Remove rotation and scaling part from the matrix
  5368. * @returns the updated matrix
  5369. */
  5370. Matrix.prototype.removeRotationAndScaling = function () {
  5371. this.setRowFromFloats(0, 1, 0, 0, 0);
  5372. this.setRowFromFloats(1, 0, 1, 0, 0);
  5373. this.setRowFromFloats(2, 0, 0, 1, 0);
  5374. return this;
  5375. };
  5376. /**
  5377. * Multiply two matrices
  5378. * @param other defines the second operand
  5379. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5380. */
  5381. Matrix.prototype.multiply = function (other) {
  5382. var result = new Matrix();
  5383. this.multiplyToRef(other, result);
  5384. return result;
  5385. };
  5386. /**
  5387. * Copy the current matrix from the given one
  5388. * @param other defines the source matrix
  5389. * @returns the current updated matrix
  5390. */
  5391. Matrix.prototype.copyFrom = function (other) {
  5392. for (var index = 0; index < 16; index++) {
  5393. this.m[index] = other.m[index];
  5394. }
  5395. this._markAsUpdated();
  5396. return this;
  5397. };
  5398. /**
  5399. * Populates the given array from the starting index with the current matrix values
  5400. * @param array defines the target array
  5401. * @param offset defines the offset in the target array where to start storing values
  5402. * @returns the current matrix
  5403. */
  5404. Matrix.prototype.copyToArray = function (array, offset) {
  5405. if (offset === void 0) { offset = 0; }
  5406. for (var index = 0; index < 16; index++) {
  5407. array[offset + index] = this.m[index];
  5408. }
  5409. return this;
  5410. };
  5411. /**
  5412. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5413. * @param other defines the second operand
  5414. * @param result defines the matrix where to store the multiplication
  5415. * @returns the current matrix
  5416. */
  5417. Matrix.prototype.multiplyToRef = function (other, result) {
  5418. this.multiplyToArray(other, result.m, 0);
  5419. result._markAsUpdated();
  5420. return this;
  5421. };
  5422. /**
  5423. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5424. * @param other defines the second operand
  5425. * @param result defines the array where to store the multiplication
  5426. * @param offset defines the offset in the target array where to start storing values
  5427. * @returns the current matrix
  5428. */
  5429. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5430. var tm0 = this.m[0];
  5431. var tm1 = this.m[1];
  5432. var tm2 = this.m[2];
  5433. var tm3 = this.m[3];
  5434. var tm4 = this.m[4];
  5435. var tm5 = this.m[5];
  5436. var tm6 = this.m[6];
  5437. var tm7 = this.m[7];
  5438. var tm8 = this.m[8];
  5439. var tm9 = this.m[9];
  5440. var tm10 = this.m[10];
  5441. var tm11 = this.m[11];
  5442. var tm12 = this.m[12];
  5443. var tm13 = this.m[13];
  5444. var tm14 = this.m[14];
  5445. var tm15 = this.m[15];
  5446. var om0 = other.m[0];
  5447. var om1 = other.m[1];
  5448. var om2 = other.m[2];
  5449. var om3 = other.m[3];
  5450. var om4 = other.m[4];
  5451. var om5 = other.m[5];
  5452. var om6 = other.m[6];
  5453. var om7 = other.m[7];
  5454. var om8 = other.m[8];
  5455. var om9 = other.m[9];
  5456. var om10 = other.m[10];
  5457. var om11 = other.m[11];
  5458. var om12 = other.m[12];
  5459. var om13 = other.m[13];
  5460. var om14 = other.m[14];
  5461. var om15 = other.m[15];
  5462. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5463. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5464. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5465. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5466. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5467. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5468. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5469. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5470. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5471. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5472. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5473. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5474. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5475. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5476. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5477. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5478. return this;
  5479. };
  5480. /**
  5481. * Check equality between this matrix and a second one
  5482. * @param value defines the second matrix to compare
  5483. * @returns true is the current matrix and the given one values are strictly equal
  5484. */
  5485. Matrix.prototype.equals = function (value) {
  5486. return value &&
  5487. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5488. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5489. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5490. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5491. };
  5492. /**
  5493. * Clone the current matrix
  5494. * @returns a new matrix from the current matrix
  5495. */
  5496. Matrix.prototype.clone = function () {
  5497. 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]);
  5498. };
  5499. /**
  5500. * Returns the name of the current matrix class
  5501. * @returns the string "Matrix"
  5502. */
  5503. Matrix.prototype.getClassName = function () {
  5504. return "Matrix";
  5505. };
  5506. /**
  5507. * Gets the hash code of the current matrix
  5508. * @returns the hash code
  5509. */
  5510. Matrix.prototype.getHashCode = function () {
  5511. var hash = this.m[0] || 0;
  5512. for (var i = 1; i < 16; i++) {
  5513. hash = (hash * 397) ^ (this.m[i] || 0);
  5514. }
  5515. return hash;
  5516. };
  5517. /**
  5518. * Decomposes the current Matrix into a translation, rotation and scaling components
  5519. * @param scale defines the scale vector3 given as a reference to update
  5520. * @param rotation defines the rotation quaternion given as a reference to update
  5521. * @param translation defines the translation vector3 given as a reference to update
  5522. * @returns true if operation was successful
  5523. */
  5524. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5525. if (translation) {
  5526. translation.x = this.m[12];
  5527. translation.y = this.m[13];
  5528. translation.z = this.m[14];
  5529. }
  5530. scale = scale || MathTmp.Vector3[0];
  5531. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5532. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5533. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5534. if (this.determinant() <= 0) {
  5535. scale.y *= -1;
  5536. }
  5537. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5538. if (rotation) {
  5539. rotation.x = 0;
  5540. rotation.y = 0;
  5541. rotation.z = 0;
  5542. rotation.w = 1;
  5543. }
  5544. return false;
  5545. }
  5546. if (rotation) {
  5547. 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]);
  5548. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5549. }
  5550. return true;
  5551. };
  5552. /**
  5553. * Gets specific row of the matrix
  5554. * @param index defines the number of the row to get
  5555. * @returns the index-th row of the current matrix as a new Vector4
  5556. */
  5557. Matrix.prototype.getRow = function (index) {
  5558. if (index < 0 || index > 3) {
  5559. return null;
  5560. }
  5561. var i = index * 4;
  5562. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5563. };
  5564. /**
  5565. * Sets the index-th row of the current matrix to the vector4 values
  5566. * @param index defines the number of the row to set
  5567. * @param row defines the target vector4
  5568. * @returns the updated current matrix
  5569. */
  5570. Matrix.prototype.setRow = function (index, row) {
  5571. if (index < 0 || index > 3) {
  5572. return this;
  5573. }
  5574. var i = index * 4;
  5575. this.m[i + 0] = row.x;
  5576. this.m[i + 1] = row.y;
  5577. this.m[i + 2] = row.z;
  5578. this.m[i + 3] = row.w;
  5579. this._markAsUpdated();
  5580. return this;
  5581. };
  5582. /**
  5583. * Compute the transpose of the matrix
  5584. * @returns the new transposed matrix
  5585. */
  5586. Matrix.prototype.transpose = function () {
  5587. return Matrix.Transpose(this);
  5588. };
  5589. /**
  5590. * Compute the transpose of the matrix and store it in a given matrix
  5591. * @param result defines the target matrix
  5592. * @returns the current matrix
  5593. */
  5594. Matrix.prototype.transposeToRef = function (result) {
  5595. Matrix.TransposeToRef(this, result);
  5596. return this;
  5597. };
  5598. /**
  5599. * Sets the index-th row of the current matrix with the given 4 x float values
  5600. * @param index defines the row index
  5601. * @param x defines the x component to set
  5602. * @param y defines the y component to set
  5603. * @param z defines the z component to set
  5604. * @param w defines the w component to set
  5605. * @returns the updated current matrix
  5606. */
  5607. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5608. if (index < 0 || index > 3) {
  5609. return this;
  5610. }
  5611. var i = index * 4;
  5612. this.m[i + 0] = x;
  5613. this.m[i + 1] = y;
  5614. this.m[i + 2] = z;
  5615. this.m[i + 3] = w;
  5616. this._markAsUpdated();
  5617. return this;
  5618. };
  5619. /**
  5620. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5621. * @param scale defines the scale factor
  5622. * @returns a new matrix
  5623. */
  5624. Matrix.prototype.scale = function (scale) {
  5625. var result = new Matrix();
  5626. this.scaleToRef(scale, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * Scale the current matrix values by a factor to a given result matrix
  5631. * @param scale defines the scale factor
  5632. * @param result defines the matrix to store the result
  5633. * @returns the current matrix
  5634. */
  5635. Matrix.prototype.scaleToRef = function (scale, result) {
  5636. for (var index = 0; index < 16; index++) {
  5637. result.m[index] = this.m[index] * scale;
  5638. }
  5639. result._markAsUpdated();
  5640. return this;
  5641. };
  5642. /**
  5643. * Scale the current matrix values by a factor and add the result to a given matrix
  5644. * @param scale defines the scale factor
  5645. * @param result defines the Matrix to store the result
  5646. * @returns the current matrix
  5647. */
  5648. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5649. for (var index = 0; index < 16; index++) {
  5650. result.m[index] += this.m[index] * scale;
  5651. }
  5652. result._markAsUpdated();
  5653. return this;
  5654. };
  5655. /**
  5656. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5657. * @param ref matrix to store the result
  5658. */
  5659. Matrix.prototype.toNormalMatrix = function (ref) {
  5660. this.invertToRef(ref);
  5661. ref.transpose();
  5662. var m = ref.m;
  5663. 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);
  5664. };
  5665. /**
  5666. * Gets only rotation part of the current matrix
  5667. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5668. */
  5669. Matrix.prototype.getRotationMatrix = function () {
  5670. var result = Matrix.Identity();
  5671. this.getRotationMatrixToRef(result);
  5672. return result;
  5673. };
  5674. /**
  5675. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5676. * @param result defines the target matrix to store data to
  5677. * @returns the current matrix
  5678. */
  5679. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5680. var m = this.m;
  5681. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5682. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5683. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5684. if (this.determinant() <= 0) {
  5685. sy *= -1;
  5686. }
  5687. if (sx === 0 || sy === 0 || sz === 0) {
  5688. Matrix.IdentityToRef(result);
  5689. }
  5690. else {
  5691. 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);
  5692. }
  5693. return this;
  5694. };
  5695. // Statics
  5696. /**
  5697. * Creates a matrix from an array
  5698. * @param array defines the source array
  5699. * @param offset defines an offset in the source array
  5700. * @returns a new Matrix set from the starting index of the given array
  5701. */
  5702. Matrix.FromArray = function (array, offset) {
  5703. var result = new Matrix();
  5704. if (!offset) {
  5705. offset = 0;
  5706. }
  5707. Matrix.FromArrayToRef(array, offset, result);
  5708. return result;
  5709. };
  5710. /**
  5711. * Copy the content of an array into a given matrix
  5712. * @param array defines the source array
  5713. * @param offset defines an offset in the source array
  5714. * @param result defines the target matrix
  5715. */
  5716. Matrix.FromArrayToRef = function (array, offset, result) {
  5717. for (var index = 0; index < 16; index++) {
  5718. result.m[index] = array[index + offset];
  5719. }
  5720. result._markAsUpdated();
  5721. };
  5722. /**
  5723. * Stores an array into a matrix after having multiplied each component by a given factor
  5724. * @param array defines the source array
  5725. * @param offset defines the offset in the source array
  5726. * @param scale defines the scaling factor
  5727. * @param result defines the target matrix
  5728. */
  5729. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5730. for (var index = 0; index < 16; index++) {
  5731. result.m[index] = array[index + offset] * scale;
  5732. }
  5733. result._markAsUpdated();
  5734. };
  5735. /**
  5736. * Stores a list of values (16) inside a given matrix
  5737. * @param initialM11 defines 1st value of 1st row
  5738. * @param initialM12 defines 2nd value of 1st row
  5739. * @param initialM13 defines 3rd value of 1st row
  5740. * @param initialM14 defines 4th value of 1st row
  5741. * @param initialM21 defines 1st value of 2nd row
  5742. * @param initialM22 defines 2nd value of 2nd row
  5743. * @param initialM23 defines 3rd value of 2nd row
  5744. * @param initialM24 defines 4th value of 2nd row
  5745. * @param initialM31 defines 1st value of 3rd row
  5746. * @param initialM32 defines 2nd value of 3rd row
  5747. * @param initialM33 defines 3rd value of 3rd row
  5748. * @param initialM34 defines 4th value of 3rd row
  5749. * @param initialM41 defines 1st value of 4th row
  5750. * @param initialM42 defines 2nd value of 4th row
  5751. * @param initialM43 defines 3rd value of 4th row
  5752. * @param initialM44 defines 4th value of 4th row
  5753. * @param result defines the target matrix
  5754. */
  5755. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5756. result.m[0] = initialM11;
  5757. result.m[1] = initialM12;
  5758. result.m[2] = initialM13;
  5759. result.m[3] = initialM14;
  5760. result.m[4] = initialM21;
  5761. result.m[5] = initialM22;
  5762. result.m[6] = initialM23;
  5763. result.m[7] = initialM24;
  5764. result.m[8] = initialM31;
  5765. result.m[9] = initialM32;
  5766. result.m[10] = initialM33;
  5767. result.m[11] = initialM34;
  5768. result.m[12] = initialM41;
  5769. result.m[13] = initialM42;
  5770. result.m[14] = initialM43;
  5771. result.m[15] = initialM44;
  5772. result._markAsUpdated();
  5773. };
  5774. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5775. /**
  5776. * Gets an identity matrix that must not be updated
  5777. */
  5778. get: function () {
  5779. return Matrix._identityReadOnly;
  5780. },
  5781. enumerable: true,
  5782. configurable: true
  5783. });
  5784. /**
  5785. * Creates new matrix from a list of values (16)
  5786. * @param initialM11 defines 1st value of 1st row
  5787. * @param initialM12 defines 2nd value of 1st row
  5788. * @param initialM13 defines 3rd value of 1st row
  5789. * @param initialM14 defines 4th value of 1st row
  5790. * @param initialM21 defines 1st value of 2nd row
  5791. * @param initialM22 defines 2nd value of 2nd row
  5792. * @param initialM23 defines 3rd value of 2nd row
  5793. * @param initialM24 defines 4th value of 2nd row
  5794. * @param initialM31 defines 1st value of 3rd row
  5795. * @param initialM32 defines 2nd value of 3rd row
  5796. * @param initialM33 defines 3rd value of 3rd row
  5797. * @param initialM34 defines 4th value of 3rd row
  5798. * @param initialM41 defines 1st value of 4th row
  5799. * @param initialM42 defines 2nd value of 4th row
  5800. * @param initialM43 defines 3rd value of 4th row
  5801. * @param initialM44 defines 4th value of 4th row
  5802. * @returns the new matrix
  5803. */
  5804. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5805. var result = new Matrix();
  5806. result.m[0] = initialM11;
  5807. result.m[1] = initialM12;
  5808. result.m[2] = initialM13;
  5809. result.m[3] = initialM14;
  5810. result.m[4] = initialM21;
  5811. result.m[5] = initialM22;
  5812. result.m[6] = initialM23;
  5813. result.m[7] = initialM24;
  5814. result.m[8] = initialM31;
  5815. result.m[9] = initialM32;
  5816. result.m[10] = initialM33;
  5817. result.m[11] = initialM34;
  5818. result.m[12] = initialM41;
  5819. result.m[13] = initialM42;
  5820. result.m[14] = initialM43;
  5821. result.m[15] = initialM44;
  5822. return result;
  5823. };
  5824. /**
  5825. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5826. * @param scale defines the scale vector3
  5827. * @param rotation defines the rotation quaternion
  5828. * @param translation defines the translation vector3
  5829. * @returns a new matrix
  5830. */
  5831. Matrix.Compose = function (scale, rotation, translation) {
  5832. var result = Matrix.Identity();
  5833. Matrix.ComposeToRef(scale, rotation, translation, result);
  5834. return result;
  5835. };
  5836. /**
  5837. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5838. * @param scale defines the scale vector3
  5839. * @param rotation defines the rotation quaternion
  5840. * @param translation defines the translation vector3
  5841. * @param result defines the target matrix
  5842. */
  5843. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5844. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5845. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5846. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5847. result.setTranslation(translation);
  5848. };
  5849. /**
  5850. * Creates a new identity matrix
  5851. * @returns a new identity matrix
  5852. */
  5853. Matrix.Identity = function () {
  5854. 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);
  5855. };
  5856. /**
  5857. * Creates a new identity matrix and stores the result in a given matrix
  5858. * @param result defines the target matrix
  5859. */
  5860. Matrix.IdentityToRef = function (result) {
  5861. 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);
  5862. };
  5863. /**
  5864. * Creates a new zero matrix
  5865. * @returns a new zero matrix
  5866. */
  5867. Matrix.Zero = function () {
  5868. 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);
  5869. };
  5870. /**
  5871. * Creates a new rotation matrix for "angle" radians around the X axis
  5872. * @param angle defines the angle (in radians) to use
  5873. * @return the new matrix
  5874. */
  5875. Matrix.RotationX = function (angle) {
  5876. var result = new Matrix();
  5877. Matrix.RotationXToRef(angle, result);
  5878. return result;
  5879. };
  5880. /**
  5881. * Creates a new matrix as the invert of a given matrix
  5882. * @param source defines the source matrix
  5883. * @returns the new matrix
  5884. */
  5885. Matrix.Invert = function (source) {
  5886. var result = new Matrix();
  5887. source.invertToRef(result);
  5888. return result;
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5892. * @param angle defines the angle (in radians) to use
  5893. * @param result defines the target matrix
  5894. */
  5895. Matrix.RotationXToRef = function (angle, result) {
  5896. var s = Math.sin(angle);
  5897. var c = Math.cos(angle);
  5898. result.m[0] = 1.0;
  5899. result.m[15] = 1.0;
  5900. result.m[5] = c;
  5901. result.m[10] = c;
  5902. result.m[9] = -s;
  5903. result.m[6] = s;
  5904. result.m[1] = 0.0;
  5905. result.m[2] = 0.0;
  5906. result.m[3] = 0.0;
  5907. result.m[4] = 0.0;
  5908. result.m[7] = 0.0;
  5909. result.m[8] = 0.0;
  5910. result.m[11] = 0.0;
  5911. result.m[12] = 0.0;
  5912. result.m[13] = 0.0;
  5913. result.m[14] = 0.0;
  5914. result._markAsUpdated();
  5915. };
  5916. /**
  5917. * Creates a new rotation matrix for "angle" radians around the Y axis
  5918. * @param angle defines the angle (in radians) to use
  5919. * @return the new matrix
  5920. */
  5921. Matrix.RotationY = function (angle) {
  5922. var result = new Matrix();
  5923. Matrix.RotationYToRef(angle, result);
  5924. return result;
  5925. };
  5926. /**
  5927. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5928. * @param angle defines the angle (in radians) to use
  5929. * @param result defines the target matrix
  5930. */
  5931. Matrix.RotationYToRef = function (angle, result) {
  5932. var s = Math.sin(angle);
  5933. var c = Math.cos(angle);
  5934. result.m[5] = 1.0;
  5935. result.m[15] = 1.0;
  5936. result.m[0] = c;
  5937. result.m[2] = -s;
  5938. result.m[8] = s;
  5939. result.m[10] = c;
  5940. result.m[1] = 0.0;
  5941. result.m[3] = 0.0;
  5942. result.m[4] = 0.0;
  5943. result.m[6] = 0.0;
  5944. result.m[7] = 0.0;
  5945. result.m[9] = 0.0;
  5946. result.m[11] = 0.0;
  5947. result.m[12] = 0.0;
  5948. result.m[13] = 0.0;
  5949. result.m[14] = 0.0;
  5950. result._markAsUpdated();
  5951. };
  5952. /**
  5953. * Creates a new rotation matrix for "angle" radians around the Z axis
  5954. * @param angle defines the angle (in radians) to use
  5955. * @return the new matrix
  5956. */
  5957. Matrix.RotationZ = function (angle) {
  5958. var result = new Matrix();
  5959. Matrix.RotationZToRef(angle, result);
  5960. return result;
  5961. };
  5962. /**
  5963. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5964. * @param angle defines the angle (in radians) to use
  5965. * @param result defines the target matrix
  5966. */
  5967. Matrix.RotationZToRef = function (angle, result) {
  5968. var s = Math.sin(angle);
  5969. var c = Math.cos(angle);
  5970. result.m[10] = 1.0;
  5971. result.m[15] = 1.0;
  5972. result.m[0] = c;
  5973. result.m[1] = s;
  5974. result.m[4] = -s;
  5975. result.m[5] = c;
  5976. result.m[2] = 0.0;
  5977. result.m[3] = 0.0;
  5978. result.m[6] = 0.0;
  5979. result.m[7] = 0.0;
  5980. result.m[8] = 0.0;
  5981. result.m[9] = 0.0;
  5982. result.m[11] = 0.0;
  5983. result.m[12] = 0.0;
  5984. result.m[13] = 0.0;
  5985. result.m[14] = 0.0;
  5986. result._markAsUpdated();
  5987. };
  5988. /**
  5989. * Creates a new rotation matrix for "angle" radians around the given axis
  5990. * @param axis defines the axis to use
  5991. * @param angle defines the angle (in radians) to use
  5992. * @return the new matrix
  5993. */
  5994. Matrix.RotationAxis = function (axis, angle) {
  5995. var result = Matrix.Zero();
  5996. Matrix.RotationAxisToRef(axis, angle, result);
  5997. return result;
  5998. };
  5999. /**
  6000. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6001. * @param axis defines the axis to use
  6002. * @param angle defines the angle (in radians) to use
  6003. * @param result defines the target matrix
  6004. */
  6005. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6006. var s = Math.sin(-angle);
  6007. var c = Math.cos(-angle);
  6008. var c1 = 1 - c;
  6009. axis.normalize();
  6010. result.m[0] = (axis.x * axis.x) * c1 + c;
  6011. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6012. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6013. result.m[3] = 0.0;
  6014. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6015. result.m[5] = (axis.y * axis.y) * c1 + c;
  6016. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6017. result.m[7] = 0.0;
  6018. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6019. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6020. result.m[10] = (axis.z * axis.z) * c1 + c;
  6021. result.m[11] = 0.0;
  6022. result.m[15] = 1.0;
  6023. result._markAsUpdated();
  6024. };
  6025. /**
  6026. * Creates a rotation matrix
  6027. * @param yaw defines the yaw angle in radians (Y axis)
  6028. * @param pitch defines the pitch angle in radians (X axis)
  6029. * @param roll defines the roll angle in radians (X axis)
  6030. * @returns the new rotation matrix
  6031. */
  6032. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6033. var result = new Matrix();
  6034. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6035. return result;
  6036. };
  6037. /**
  6038. * Creates a rotation matrix and stores it in a given matrix
  6039. * @param yaw defines the yaw angle in radians (Y axis)
  6040. * @param pitch defines the pitch angle in radians (X axis)
  6041. * @param roll defines the roll angle in radians (X axis)
  6042. * @param result defines the target matrix
  6043. */
  6044. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6045. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6046. this._tempQuaternion.toRotationMatrix(result);
  6047. };
  6048. /**
  6049. * Creates a scaling matrix
  6050. * @param x defines the scale factor on X axis
  6051. * @param y defines the scale factor on Y axis
  6052. * @param z defines the scale factor on Z axis
  6053. * @returns the new matrix
  6054. */
  6055. Matrix.Scaling = function (x, y, z) {
  6056. var result = Matrix.Zero();
  6057. Matrix.ScalingToRef(x, y, z, result);
  6058. return result;
  6059. };
  6060. /**
  6061. * Creates a scaling matrix and stores it in a given matrix
  6062. * @param x defines the scale factor on X axis
  6063. * @param y defines the scale factor on Y axis
  6064. * @param z defines the scale factor on Z axis
  6065. * @param result defines the target matrix
  6066. */
  6067. Matrix.ScalingToRef = function (x, y, z, result) {
  6068. result.m[0] = x;
  6069. result.m[1] = 0.0;
  6070. result.m[2] = 0.0;
  6071. result.m[3] = 0.0;
  6072. result.m[4] = 0.0;
  6073. result.m[5] = y;
  6074. result.m[6] = 0.0;
  6075. result.m[7] = 0.0;
  6076. result.m[8] = 0.0;
  6077. result.m[9] = 0.0;
  6078. result.m[10] = z;
  6079. result.m[11] = 0.0;
  6080. result.m[12] = 0.0;
  6081. result.m[13] = 0.0;
  6082. result.m[14] = 0.0;
  6083. result.m[15] = 1.0;
  6084. result._markAsUpdated();
  6085. };
  6086. /**
  6087. * Creates a translation matrix
  6088. * @param x defines the translation on X axis
  6089. * @param y defines the translation on Y axis
  6090. * @param z defines the translationon Z axis
  6091. * @returns the new matrix
  6092. */
  6093. Matrix.Translation = function (x, y, z) {
  6094. var result = Matrix.Identity();
  6095. Matrix.TranslationToRef(x, y, z, result);
  6096. return result;
  6097. };
  6098. /**
  6099. * Creates a translation matrix and stores it in a given matrix
  6100. * @param x defines the translation on X axis
  6101. * @param y defines the translation on Y axis
  6102. * @param z defines the translationon Z axis
  6103. * @param result defines the target matrix
  6104. */
  6105. Matrix.TranslationToRef = function (x, y, z, result) {
  6106. 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);
  6107. };
  6108. /**
  6109. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6110. * @param startValue defines the start value
  6111. * @param endValue defines the end value
  6112. * @param gradient defines the gradient factor
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.Lerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6122. * @param startValue defines the start value
  6123. * @param endValue defines the end value
  6124. * @param gradient defines the gradient factor
  6125. * @param result defines the Matrix object where to store data
  6126. */
  6127. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6128. for (var index = 0; index < 16; index++) {
  6129. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6130. }
  6131. result._markAsUpdated();
  6132. };
  6133. /**
  6134. * Builds a new matrix whose values are computed by:
  6135. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6136. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6137. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6138. * @param startValue defines the first matrix
  6139. * @param endValue defines the second matrix
  6140. * @param gradient defines the gradient between the two matrices
  6141. * @returns the new matrix
  6142. */
  6143. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6144. var result = Matrix.Zero();
  6145. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6146. return result;
  6147. };
  6148. /**
  6149. * Update a matrix to values which are computed by:
  6150. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6151. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6152. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6153. * @param startValue defines the first matrix
  6154. * @param endValue defines the second matrix
  6155. * @param gradient defines the gradient between the two matrices
  6156. * @param result defines the target matrix
  6157. */
  6158. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6159. var startScale = MathTmp.Vector3[0];
  6160. var startRotation = MathTmp.Quaternion[0];
  6161. var startTranslation = MathTmp.Vector3[1];
  6162. startValue.decompose(startScale, startRotation, startTranslation);
  6163. var endScale = MathTmp.Vector3[2];
  6164. var endRotation = MathTmp.Quaternion[1];
  6165. var endTranslation = MathTmp.Vector3[3];
  6166. endValue.decompose(endScale, endRotation, endTranslation);
  6167. var resultScale = MathTmp.Vector3[4];
  6168. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6169. var resultRotation = MathTmp.Quaternion[2];
  6170. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6171. var resultTranslation = MathTmp.Vector3[5];
  6172. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6173. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6174. };
  6175. /**
  6176. * 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"
  6177. * This function works in left handed mode
  6178. * @param eye defines the final position of the entity
  6179. * @param target defines where the entity should look at
  6180. * @param up defines the up vector for the entity
  6181. * @returns the new matrix
  6182. */
  6183. Matrix.LookAtLH = function (eye, target, up) {
  6184. var result = Matrix.Zero();
  6185. Matrix.LookAtLHToRef(eye, target, up, result);
  6186. return result;
  6187. };
  6188. /**
  6189. * 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".
  6190. * This function works in left handed mode
  6191. * @param eye defines the final position of the entity
  6192. * @param target defines where the entity should look at
  6193. * @param up defines the up vector for the entity
  6194. * @param result defines the target matrix
  6195. */
  6196. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6197. // Z axis
  6198. target.subtractToRef(eye, this._zAxis);
  6199. this._zAxis.normalize();
  6200. // X axis
  6201. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6202. if (this._xAxis.lengthSquared() === 0) {
  6203. this._xAxis.x = 1.0;
  6204. }
  6205. else {
  6206. this._xAxis.normalize();
  6207. }
  6208. // Y axis
  6209. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6210. this._yAxis.normalize();
  6211. // Eye angles
  6212. var ex = -Vector3.Dot(this._xAxis, eye);
  6213. var ey = -Vector3.Dot(this._yAxis, eye);
  6214. var ez = -Vector3.Dot(this._zAxis, eye);
  6215. 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);
  6216. };
  6217. /**
  6218. * 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"
  6219. * This function works in right handed mode
  6220. * @param eye defines the final position of the entity
  6221. * @param target defines where the entity should look at
  6222. * @param up defines the up vector for the entity
  6223. * @returns the new matrix
  6224. */
  6225. Matrix.LookAtRH = function (eye, target, up) {
  6226. var result = Matrix.Zero();
  6227. Matrix.LookAtRHToRef(eye, target, up, result);
  6228. return result;
  6229. };
  6230. /**
  6231. * 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".
  6232. * This function works in right handed mode
  6233. * @param eye defines the final position of the entity
  6234. * @param target defines where the entity should look at
  6235. * @param up defines the up vector for the entity
  6236. * @param result defines the target matrix
  6237. */
  6238. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6239. // Z axis
  6240. eye.subtractToRef(target, this._zAxis);
  6241. this._zAxis.normalize();
  6242. // X axis
  6243. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6244. if (this._xAxis.lengthSquared() === 0) {
  6245. this._xAxis.x = 1.0;
  6246. }
  6247. else {
  6248. this._xAxis.normalize();
  6249. }
  6250. // Y axis
  6251. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6252. this._yAxis.normalize();
  6253. // Eye angles
  6254. var ex = -Vector3.Dot(this._xAxis, eye);
  6255. var ey = -Vector3.Dot(this._yAxis, eye);
  6256. var ez = -Vector3.Dot(this._zAxis, eye);
  6257. 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);
  6258. };
  6259. /**
  6260. * Create a left-handed orthographic projection matrix
  6261. * @param width defines the viewport width
  6262. * @param height defines the viewport height
  6263. * @param znear defines the near clip plane
  6264. * @param zfar defines the far clip plane
  6265. * @returns a new matrix as a left-handed orthographic projection matrix
  6266. */
  6267. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6268. var matrix = Matrix.Zero();
  6269. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6270. return matrix;
  6271. };
  6272. /**
  6273. * Store a left-handed orthographic projection to a given matrix
  6274. * @param width defines the viewport width
  6275. * @param height defines the viewport height
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @param result defines the target matrix
  6279. */
  6280. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6281. var n = znear;
  6282. var f = zfar;
  6283. var a = 2.0 / width;
  6284. var b = 2.0 / height;
  6285. var c = 2.0 / (f - n);
  6286. var d = -(f + n) / (f - n);
  6287. 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);
  6288. };
  6289. /**
  6290. * Create a left-handed orthographic projection matrix
  6291. * @param left defines the viewport left coordinate
  6292. * @param right defines the viewport right coordinate
  6293. * @param bottom defines the viewport bottom coordinate
  6294. * @param top defines the viewport top coordinate
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @returns a new matrix as a left-handed orthographic projection matrix
  6298. */
  6299. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6300. var matrix = Matrix.Zero();
  6301. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6302. return matrix;
  6303. };
  6304. /**
  6305. * Stores a left-handed orthographic projection into a given matrix
  6306. * @param left defines the viewport left coordinate
  6307. * @param right defines the viewport right coordinate
  6308. * @param bottom defines the viewport bottom coordinate
  6309. * @param top defines the viewport top coordinate
  6310. * @param znear defines the near clip plane
  6311. * @param zfar defines the far clip plane
  6312. * @param result defines the target matrix
  6313. */
  6314. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6315. var n = znear;
  6316. var f = zfar;
  6317. var a = 2.0 / (right - left);
  6318. var b = 2.0 / (top - bottom);
  6319. var c = 2.0 / (f - n);
  6320. var d = -(f + n) / (f - n);
  6321. var i0 = (left + right) / (left - right);
  6322. var i1 = (top + bottom) / (bottom - top);
  6323. 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);
  6324. };
  6325. /**
  6326. * Creates a right-handed orthographic projection matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @returns a new matrix as a right-handed orthographic projection matrix
  6334. */
  6335. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6336. var matrix = Matrix.Zero();
  6337. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6338. return matrix;
  6339. };
  6340. /**
  6341. * Stores a right-handed orthographic projection into a given matrix
  6342. * @param left defines the viewport left coordinate
  6343. * @param right defines the viewport right coordinate
  6344. * @param bottom defines the viewport bottom coordinate
  6345. * @param top defines the viewport top coordinate
  6346. * @param znear defines the near clip plane
  6347. * @param zfar defines the far clip plane
  6348. * @param result defines the target matrix
  6349. */
  6350. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6351. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6352. result.m[10] *= -1.0;
  6353. };
  6354. /**
  6355. * Creates a left-handed perspective projection matrix
  6356. * @param width defines the viewport width
  6357. * @param height defines the viewport height
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @returns a new matrix as a left-handed perspective projection matrix
  6361. */
  6362. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6363. var matrix = Matrix.Zero();
  6364. var n = znear;
  6365. var f = zfar;
  6366. var a = 2.0 * n / width;
  6367. var b = 2.0 * n / height;
  6368. var c = (f + n) / (f - n);
  6369. var d = -2.0 * f * n / (f - n);
  6370. 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);
  6371. return matrix;
  6372. };
  6373. /**
  6374. * Creates a left-handed perspective projection matrix
  6375. * @param fov defines the horizontal field of view
  6376. * @param aspect defines the aspect ratio
  6377. * @param znear defines the near clip plane
  6378. * @param zfar defines the far clip plane
  6379. * @returns a new matrix as a left-handed perspective projection matrix
  6380. */
  6381. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6382. var matrix = Matrix.Zero();
  6383. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6384. return matrix;
  6385. };
  6386. /**
  6387. * Stores a left-handed perspective projection into a given matrix
  6388. * @param fov defines the horizontal field of view
  6389. * @param aspect defines the aspect ratio
  6390. * @param znear defines the near clip plane
  6391. * @param zfar defines the far clip plane
  6392. * @param result defines the target matrix
  6393. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6394. */
  6395. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6396. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6397. var n = znear;
  6398. var f = zfar;
  6399. var t = 1.0 / (Math.tan(fov * 0.5));
  6400. var a = isVerticalFovFixed ? (t / aspect) : t;
  6401. var b = isVerticalFovFixed ? t : (t * aspect);
  6402. var c = (f + n) / (f - n);
  6403. var d = -2.0 * f * n / (f - n);
  6404. 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);
  6405. };
  6406. /**
  6407. * Creates a right-handed perspective projection matrix
  6408. * @param fov defines the horizontal field of view
  6409. * @param aspect defines the aspect ratio
  6410. * @param znear defines the near clip plane
  6411. * @param zfar defines the far clip plane
  6412. * @returns a new matrix as a right-handed perspective projection matrix
  6413. */
  6414. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6415. var matrix = Matrix.Zero();
  6416. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6417. return matrix;
  6418. };
  6419. /**
  6420. * Stores a right-handed perspective projection into a given matrix
  6421. * @param fov defines the horizontal field of view
  6422. * @param aspect defines the aspect ratio
  6423. * @param znear defines the near clip plane
  6424. * @param zfar defines the far clip plane
  6425. * @param result defines the target matrix
  6426. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6427. */
  6428. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6429. //alternatively this could be expressed as:
  6430. // m = PerspectiveFovLHToRef
  6431. // m[10] *= -1.0;
  6432. // m[11] *= -1.0;
  6433. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6434. var n = znear;
  6435. var f = zfar;
  6436. var t = 1.0 / (Math.tan(fov * 0.5));
  6437. var a = isVerticalFovFixed ? (t / aspect) : t;
  6438. var b = isVerticalFovFixed ? t : (t * aspect);
  6439. var c = -(f + n) / (f - n);
  6440. var d = -2 * f * n / (f - n);
  6441. 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);
  6442. };
  6443. /**
  6444. * Stores a perspective projection for WebVR info a given matrix
  6445. * @param fov defines the field of view
  6446. * @param znear defines the near clip plane
  6447. * @param zfar defines the far clip plane
  6448. * @param result defines the target matrix
  6449. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6450. */
  6451. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6452. if (rightHanded === void 0) { rightHanded = false; }
  6453. var rightHandedFactor = rightHanded ? -1 : 1;
  6454. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6455. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6456. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6457. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6458. var xScale = 2.0 / (leftTan + rightTan);
  6459. var yScale = 2.0 / (upTan + downTan);
  6460. result.m[0] = xScale;
  6461. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6462. result.m[5] = yScale;
  6463. result.m[6] = result.m[7] = 0.0;
  6464. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6465. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6466. result.m[10] = -zfar / (znear - zfar);
  6467. result.m[11] = 1.0 * rightHandedFactor;
  6468. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6469. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6470. result._markAsUpdated();
  6471. };
  6472. /**
  6473. * Computes a complete transformation matrix
  6474. * @param viewport defines the viewport to use
  6475. * @param world defines the world matrix
  6476. * @param view defines the view matrix
  6477. * @param projection defines the projection matrix
  6478. * @param zmin defines the near clip plane
  6479. * @param zmax defines the far clip plane
  6480. * @returns the transformation matrix
  6481. */
  6482. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6483. var cw = viewport.width;
  6484. var ch = viewport.height;
  6485. var cx = viewport.x;
  6486. var cy = viewport.y;
  6487. 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);
  6488. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6489. };
  6490. /**
  6491. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6492. * @param matrix defines the matrix to use
  6493. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6494. */
  6495. Matrix.GetAsMatrix2x2 = function (matrix) {
  6496. return new Float32Array([
  6497. matrix.m[0], matrix.m[1],
  6498. matrix.m[4], matrix.m[5]
  6499. ]);
  6500. };
  6501. /**
  6502. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6503. * @param matrix defines the matrix to use
  6504. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6505. */
  6506. Matrix.GetAsMatrix3x3 = function (matrix) {
  6507. return new Float32Array([
  6508. matrix.m[0], matrix.m[1], matrix.m[2],
  6509. matrix.m[4], matrix.m[5], matrix.m[6],
  6510. matrix.m[8], matrix.m[9], matrix.m[10]
  6511. ]);
  6512. };
  6513. /**
  6514. * Compute the transpose of a given matrix
  6515. * @param matrix defines the matrix to transpose
  6516. * @returns the new matrix
  6517. */
  6518. Matrix.Transpose = function (matrix) {
  6519. var result = new Matrix();
  6520. Matrix.TransposeToRef(matrix, result);
  6521. return result;
  6522. };
  6523. /**
  6524. * Compute the transpose of a matrix and store it in a target matrix
  6525. * @param matrix defines the matrix to transpose
  6526. * @param result defines the target matrix
  6527. */
  6528. Matrix.TransposeToRef = function (matrix, result) {
  6529. result.m[0] = matrix.m[0];
  6530. result.m[1] = matrix.m[4];
  6531. result.m[2] = matrix.m[8];
  6532. result.m[3] = matrix.m[12];
  6533. result.m[4] = matrix.m[1];
  6534. result.m[5] = matrix.m[5];
  6535. result.m[6] = matrix.m[9];
  6536. result.m[7] = matrix.m[13];
  6537. result.m[8] = matrix.m[2];
  6538. result.m[9] = matrix.m[6];
  6539. result.m[10] = matrix.m[10];
  6540. result.m[11] = matrix.m[14];
  6541. result.m[12] = matrix.m[3];
  6542. result.m[13] = matrix.m[7];
  6543. result.m[14] = matrix.m[11];
  6544. result.m[15] = matrix.m[15];
  6545. };
  6546. /**
  6547. * Computes a reflection matrix from a plane
  6548. * @param plane defines the reflection plane
  6549. * @returns a new matrix
  6550. */
  6551. Matrix.Reflection = function (plane) {
  6552. var matrix = new Matrix();
  6553. Matrix.ReflectionToRef(plane, matrix);
  6554. return matrix;
  6555. };
  6556. /**
  6557. * Computes a reflection matrix from a plane
  6558. * @param plane defines the reflection plane
  6559. * @param result defines the target matrix
  6560. */
  6561. Matrix.ReflectionToRef = function (plane, result) {
  6562. plane.normalize();
  6563. var x = plane.normal.x;
  6564. var y = plane.normal.y;
  6565. var z = plane.normal.z;
  6566. var temp = -2 * x;
  6567. var temp2 = -2 * y;
  6568. var temp3 = -2 * z;
  6569. result.m[0] = (temp * x) + 1;
  6570. result.m[1] = temp2 * x;
  6571. result.m[2] = temp3 * x;
  6572. result.m[3] = 0.0;
  6573. result.m[4] = temp * y;
  6574. result.m[5] = (temp2 * y) + 1;
  6575. result.m[6] = temp3 * y;
  6576. result.m[7] = 0.0;
  6577. result.m[8] = temp * z;
  6578. result.m[9] = temp2 * z;
  6579. result.m[10] = (temp3 * z) + 1;
  6580. result.m[11] = 0.0;
  6581. result.m[12] = temp * plane.d;
  6582. result.m[13] = temp2 * plane.d;
  6583. result.m[14] = temp3 * plane.d;
  6584. result.m[15] = 1.0;
  6585. result._markAsUpdated();
  6586. };
  6587. /**
  6588. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6589. * @param xaxis defines the value of the 1st axis
  6590. * @param yaxis defines the value of the 2nd axis
  6591. * @param zaxis defines the value of the 3rd axis
  6592. * @param result defines the target matrix
  6593. */
  6594. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6595. result.m[0] = xaxis.x;
  6596. result.m[1] = xaxis.y;
  6597. result.m[2] = xaxis.z;
  6598. result.m[3] = 0.0;
  6599. result.m[4] = yaxis.x;
  6600. result.m[5] = yaxis.y;
  6601. result.m[6] = yaxis.z;
  6602. result.m[7] = 0.0;
  6603. result.m[8] = zaxis.x;
  6604. result.m[9] = zaxis.y;
  6605. result.m[10] = zaxis.z;
  6606. result.m[11] = 0.0;
  6607. result.m[12] = 0.0;
  6608. result.m[13] = 0.0;
  6609. result.m[14] = 0.0;
  6610. result.m[15] = 1.0;
  6611. result._markAsUpdated();
  6612. };
  6613. /**
  6614. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6615. * @param quat defines the quaternion to use
  6616. * @param result defines the target matrix
  6617. */
  6618. Matrix.FromQuaternionToRef = function (quat, result) {
  6619. var xx = quat.x * quat.x;
  6620. var yy = quat.y * quat.y;
  6621. var zz = quat.z * quat.z;
  6622. var xy = quat.x * quat.y;
  6623. var zw = quat.z * quat.w;
  6624. var zx = quat.z * quat.x;
  6625. var yw = quat.y * quat.w;
  6626. var yz = quat.y * quat.z;
  6627. var xw = quat.x * quat.w;
  6628. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6629. result.m[1] = 2.0 * (xy + zw);
  6630. result.m[2] = 2.0 * (zx - yw);
  6631. result.m[3] = 0.0;
  6632. result.m[4] = 2.0 * (xy - zw);
  6633. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6634. result.m[6] = 2.0 * (yz + xw);
  6635. result.m[7] = 0.0;
  6636. result.m[8] = 2.0 * (zx + yw);
  6637. result.m[9] = 2.0 * (yz - xw);
  6638. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6639. result.m[11] = 0.0;
  6640. result.m[12] = 0.0;
  6641. result.m[13] = 0.0;
  6642. result.m[14] = 0.0;
  6643. result.m[15] = 1.0;
  6644. result._markAsUpdated();
  6645. };
  6646. Matrix._tempQuaternion = new Quaternion();
  6647. Matrix._xAxis = Vector3.Zero();
  6648. Matrix._yAxis = Vector3.Zero();
  6649. Matrix._zAxis = Vector3.Zero();
  6650. Matrix._updateFlagSeed = 0;
  6651. Matrix._identityReadOnly = Matrix.Identity();
  6652. return Matrix;
  6653. }());
  6654. BABYLON.Matrix = Matrix;
  6655. var Plane = /** @class */ (function () {
  6656. /**
  6657. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6658. */
  6659. function Plane(a, b, c, d) {
  6660. this.normal = new Vector3(a, b, c);
  6661. this.d = d;
  6662. }
  6663. /**
  6664. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6665. */
  6666. Plane.prototype.asArray = function () {
  6667. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6668. };
  6669. // Methods
  6670. /**
  6671. * Returns a new plane copied from the current Plane.
  6672. */
  6673. Plane.prototype.clone = function () {
  6674. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6675. };
  6676. /**
  6677. * Returns the string "Plane".
  6678. */
  6679. Plane.prototype.getClassName = function () {
  6680. return "Plane";
  6681. };
  6682. /**
  6683. * Returns the Plane hash code.
  6684. */
  6685. Plane.prototype.getHashCode = function () {
  6686. var hash = this.normal.getHashCode();
  6687. hash = (hash * 397) ^ (this.d || 0);
  6688. return hash;
  6689. };
  6690. /**
  6691. * Normalize the current Plane in place.
  6692. * Returns the updated Plane.
  6693. */
  6694. Plane.prototype.normalize = function () {
  6695. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6696. var magnitude = 0.0;
  6697. if (norm !== 0) {
  6698. magnitude = 1.0 / norm;
  6699. }
  6700. this.normal.x *= magnitude;
  6701. this.normal.y *= magnitude;
  6702. this.normal.z *= magnitude;
  6703. this.d *= magnitude;
  6704. return this;
  6705. };
  6706. /**
  6707. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6708. */
  6709. Plane.prototype.transform = function (transformation) {
  6710. var transposedMatrix = Matrix.Transpose(transformation);
  6711. var x = this.normal.x;
  6712. var y = this.normal.y;
  6713. var z = this.normal.z;
  6714. var d = this.d;
  6715. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6716. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6717. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6718. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6719. return new Plane(normalX, normalY, normalZ, finalD);
  6720. };
  6721. /**
  6722. * Returns the dot product (float) of the point coordinates and the plane normal.
  6723. */
  6724. Plane.prototype.dotCoordinate = function (point) {
  6725. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6726. };
  6727. /**
  6728. * Updates the current Plane from the plane defined by the three given points.
  6729. * Returns the updated Plane.
  6730. */
  6731. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6732. var x1 = point2.x - point1.x;
  6733. var y1 = point2.y - point1.y;
  6734. var z1 = point2.z - point1.z;
  6735. var x2 = point3.x - point1.x;
  6736. var y2 = point3.y - point1.y;
  6737. var z2 = point3.z - point1.z;
  6738. var yz = (y1 * z2) - (z1 * y2);
  6739. var xz = (z1 * x2) - (x1 * z2);
  6740. var xy = (x1 * y2) - (y1 * x2);
  6741. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6742. var invPyth;
  6743. if (pyth !== 0) {
  6744. invPyth = 1.0 / pyth;
  6745. }
  6746. else {
  6747. invPyth = 0.0;
  6748. }
  6749. this.normal.x = yz * invPyth;
  6750. this.normal.y = xz * invPyth;
  6751. this.normal.z = xy * invPyth;
  6752. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6753. return this;
  6754. };
  6755. /**
  6756. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6757. */
  6758. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6759. var dot = Vector3.Dot(this.normal, direction);
  6760. return (dot <= epsilon);
  6761. };
  6762. /**
  6763. * Returns the signed distance (float) from the given point to the Plane.
  6764. */
  6765. Plane.prototype.signedDistanceTo = function (point) {
  6766. return Vector3.Dot(point, this.normal) + this.d;
  6767. };
  6768. // Statics
  6769. /**
  6770. * Returns a new Plane from the given array.
  6771. */
  6772. Plane.FromArray = function (array) {
  6773. return new Plane(array[0], array[1], array[2], array[3]);
  6774. };
  6775. /**
  6776. * Returns a new Plane defined by the three given points.
  6777. */
  6778. Plane.FromPoints = function (point1, point2, point3) {
  6779. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6780. result.copyFromPoints(point1, point2, point3);
  6781. return result;
  6782. };
  6783. /**
  6784. * Returns a new Plane the normal vector to this plane at the given origin point.
  6785. * Note : the vector "normal" is updated because normalized.
  6786. */
  6787. Plane.FromPositionAndNormal = function (origin, normal) {
  6788. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6789. normal.normalize();
  6790. result.normal = normal;
  6791. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6792. return result;
  6793. };
  6794. /**
  6795. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6796. */
  6797. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6798. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6799. return Vector3.Dot(point, normal) + d;
  6800. };
  6801. return Plane;
  6802. }());
  6803. BABYLON.Plane = Plane;
  6804. var Viewport = /** @class */ (function () {
  6805. /**
  6806. * Creates a Viewport object located at (x, y) and sized (width, height).
  6807. */
  6808. function Viewport(x, y, width, height) {
  6809. this.x = x;
  6810. this.y = y;
  6811. this.width = width;
  6812. this.height = height;
  6813. }
  6814. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6815. if (renderWidthOrEngine.getRenderWidth) {
  6816. var engine = renderWidthOrEngine;
  6817. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6818. }
  6819. var renderWidth = renderWidthOrEngine;
  6820. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6821. };
  6822. /**
  6823. * Returns a new Viewport copied from the current one.
  6824. */
  6825. Viewport.prototype.clone = function () {
  6826. return new Viewport(this.x, this.y, this.width, this.height);
  6827. };
  6828. return Viewport;
  6829. }());
  6830. BABYLON.Viewport = Viewport;
  6831. var Frustum = /** @class */ (function () {
  6832. function Frustum() {
  6833. }
  6834. /**
  6835. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6836. */
  6837. Frustum.GetPlanes = function (transform) {
  6838. var frustumPlanes = [];
  6839. for (var index = 0; index < 6; index++) {
  6840. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6841. }
  6842. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6843. return frustumPlanes;
  6844. };
  6845. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6847. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6848. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6849. frustumPlane.d = transform.m[15] + transform.m[14];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6854. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6855. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6856. frustumPlane.d = transform.m[15] - transform.m[14];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6861. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6862. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6863. frustumPlane.d = transform.m[15] + transform.m[12];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6868. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6869. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6870. frustumPlane.d = transform.m[15] - transform.m[12];
  6871. frustumPlane.normalize();
  6872. };
  6873. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6874. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6875. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6876. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6877. frustumPlane.d = transform.m[15] - transform.m[13];
  6878. frustumPlane.normalize();
  6879. };
  6880. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6881. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6882. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6883. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6884. frustumPlane.d = transform.m[15] + transform.m[13];
  6885. frustumPlane.normalize();
  6886. };
  6887. /**
  6888. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6889. */
  6890. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6891. // Near
  6892. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6893. // Far
  6894. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6895. // Left
  6896. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6897. // Right
  6898. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6899. // Top
  6900. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6901. // Bottom
  6902. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6903. };
  6904. return Frustum;
  6905. }());
  6906. BABYLON.Frustum = Frustum;
  6907. /** Defines supported spaces */
  6908. var Space;
  6909. (function (Space) {
  6910. /** Local (object) space */
  6911. Space[Space["LOCAL"] = 0] = "LOCAL";
  6912. /** World space */
  6913. Space[Space["WORLD"] = 1] = "WORLD";
  6914. /** Bone space */
  6915. Space[Space["BONE"] = 2] = "BONE";
  6916. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6917. /** Defines the 3 main axes */
  6918. var Axis = /** @class */ (function () {
  6919. function Axis() {
  6920. }
  6921. /** X axis */
  6922. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6923. /** Y axis */
  6924. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6925. /** Z axis */
  6926. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6927. return Axis;
  6928. }());
  6929. BABYLON.Axis = Axis;
  6930. ;
  6931. var BezierCurve = /** @class */ (function () {
  6932. function BezierCurve() {
  6933. }
  6934. /**
  6935. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6936. */
  6937. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6938. // Extract X (which is equal to time here)
  6939. var f0 = 1 - 3 * x2 + 3 * x1;
  6940. var f1 = 3 * x2 - 6 * x1;
  6941. var f2 = 3 * x1;
  6942. var refinedT = t;
  6943. for (var i = 0; i < 5; i++) {
  6944. var refinedT2 = refinedT * refinedT;
  6945. var refinedT3 = refinedT2 * refinedT;
  6946. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6947. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6948. refinedT -= (x - t) * slope;
  6949. refinedT = Math.min(1, Math.max(0, refinedT));
  6950. }
  6951. // Resolve cubic bezier for the given x
  6952. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6953. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6954. Math.pow(refinedT, 3);
  6955. };
  6956. return BezierCurve;
  6957. }());
  6958. BABYLON.BezierCurve = BezierCurve;
  6959. /**
  6960. * Defines potential orientation for back face culling
  6961. */
  6962. var Orientation;
  6963. (function (Orientation) {
  6964. /**
  6965. * Clockwise
  6966. */
  6967. Orientation[Orientation["CW"] = 0] = "CW";
  6968. /** Counter clockwise */
  6969. Orientation[Orientation["CCW"] = 1] = "CCW";
  6970. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6971. /**
  6972. * Defines angle representation
  6973. */
  6974. var Angle = /** @class */ (function () {
  6975. /**
  6976. * Creates an Angle object of "radians" radians (float).
  6977. */
  6978. function Angle(radians) {
  6979. this._radians = radians;
  6980. if (this._radians < 0.0)
  6981. this._radians += (2.0 * Math.PI);
  6982. }
  6983. /**
  6984. * Get value in degrees
  6985. * @returns the Angle value in degrees (float)
  6986. */
  6987. Angle.prototype.degrees = function () {
  6988. return this._radians * 180.0 / Math.PI;
  6989. };
  6990. /**
  6991. * Get value in radians
  6992. * @returns the Angle value in radians (float)
  6993. */
  6994. Angle.prototype.radians = function () {
  6995. return this._radians;
  6996. };
  6997. /**
  6998. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6999. * @param a defines first vector
  7000. * @param b defines second vector
  7001. * @returns a new Angle
  7002. */
  7003. Angle.BetweenTwoPoints = function (a, b) {
  7004. var delta = b.subtract(a);
  7005. var theta = Math.atan2(delta.y, delta.x);
  7006. return new Angle(theta);
  7007. };
  7008. /**
  7009. * Gets a new Angle object from the given float in radians
  7010. * @param radians defines the angle value in radians
  7011. * @returns a new Angle
  7012. */
  7013. Angle.FromRadians = function (radians) {
  7014. return new Angle(radians);
  7015. };
  7016. /**
  7017. * Gets a new Angle object from the given float in degrees
  7018. * @param degrees defines the angle value in degrees
  7019. * @returns a new Angle
  7020. */
  7021. Angle.FromDegrees = function (degrees) {
  7022. return new Angle(degrees * Math.PI / 180.0);
  7023. };
  7024. return Angle;
  7025. }());
  7026. BABYLON.Angle = Angle;
  7027. /**
  7028. * This represents an arc in a 2d space.
  7029. */
  7030. var Arc2 = /** @class */ (function () {
  7031. /**
  7032. * Creates an Arc object from the three given points : start, middle and end.
  7033. * @param startPoint Defines the start point of the arc
  7034. * @param midPoint Defines the midlle point of the arc
  7035. * @param endPoint Defines the end point of the arc
  7036. */
  7037. function Arc2(
  7038. /** Defines the start point of the arc */
  7039. startPoint,
  7040. /** Defines the mid point of the arc */
  7041. midPoint,
  7042. /** Defines the end point of the arc */
  7043. endPoint) {
  7044. this.startPoint = startPoint;
  7045. this.midPoint = midPoint;
  7046. this.endPoint = endPoint;
  7047. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7048. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7049. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7050. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7051. 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);
  7052. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7053. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7054. var a1 = this.startAngle.degrees();
  7055. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7056. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7057. // angles correction
  7058. if (a2 - a1 > +180.0)
  7059. a2 -= 360.0;
  7060. if (a2 - a1 < -180.0)
  7061. a2 += 360.0;
  7062. if (a3 - a2 > +180.0)
  7063. a3 -= 360.0;
  7064. if (a3 - a2 < -180.0)
  7065. a3 += 360.0;
  7066. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7067. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7068. }
  7069. return Arc2;
  7070. }());
  7071. BABYLON.Arc2 = Arc2;
  7072. var Path2 = /** @class */ (function () {
  7073. /**
  7074. * Creates a Path2 object from the starting 2D coordinates x and y.
  7075. */
  7076. function Path2(x, y) {
  7077. this._points = new Array();
  7078. this._length = 0.0;
  7079. this.closed = false;
  7080. this._points.push(new Vector2(x, y));
  7081. }
  7082. /**
  7083. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7084. * Returns the updated Path2.
  7085. */
  7086. Path2.prototype.addLineTo = function (x, y) {
  7087. if (this.closed) {
  7088. return this;
  7089. }
  7090. var newPoint = new Vector2(x, y);
  7091. var previousPoint = this._points[this._points.length - 1];
  7092. this._points.push(newPoint);
  7093. this._length += newPoint.subtract(previousPoint).length();
  7094. return this;
  7095. };
  7096. /**
  7097. * 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.
  7098. * Returns the updated Path2.
  7099. */
  7100. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7101. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7102. if (this.closed) {
  7103. return this;
  7104. }
  7105. var startPoint = this._points[this._points.length - 1];
  7106. var midPoint = new Vector2(midX, midY);
  7107. var endPoint = new Vector2(endX, endY);
  7108. var arc = new Arc2(startPoint, midPoint, endPoint);
  7109. var increment = arc.angle.radians() / numberOfSegments;
  7110. if (arc.orientation === Orientation.CW)
  7111. increment *= -1;
  7112. var currentAngle = arc.startAngle.radians() + increment;
  7113. for (var i = 0; i < numberOfSegments; i++) {
  7114. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7115. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7116. this.addLineTo(x, y);
  7117. currentAngle += increment;
  7118. }
  7119. return this;
  7120. };
  7121. /**
  7122. * Closes the Path2.
  7123. * Returns the Path2.
  7124. */
  7125. Path2.prototype.close = function () {
  7126. this.closed = true;
  7127. return this;
  7128. };
  7129. /**
  7130. * Returns the Path2 total length (float).
  7131. */
  7132. Path2.prototype.length = function () {
  7133. var result = this._length;
  7134. if (!this.closed) {
  7135. var lastPoint = this._points[this._points.length - 1];
  7136. var firstPoint = this._points[0];
  7137. result += (firstPoint.subtract(lastPoint).length());
  7138. }
  7139. return result;
  7140. };
  7141. /**
  7142. * Returns the Path2 internal array of points.
  7143. */
  7144. Path2.prototype.getPoints = function () {
  7145. return this._points;
  7146. };
  7147. /**
  7148. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7149. */
  7150. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7151. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7152. return Vector2.Zero();
  7153. }
  7154. var lengthPosition = normalizedLengthPosition * this.length();
  7155. var previousOffset = 0;
  7156. for (var i = 0; i < this._points.length; i++) {
  7157. var j = (i + 1) % this._points.length;
  7158. var a = this._points[i];
  7159. var b = this._points[j];
  7160. var bToA = b.subtract(a);
  7161. var nextOffset = (bToA.length() + previousOffset);
  7162. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7163. var dir = bToA.normalize();
  7164. var localOffset = lengthPosition - previousOffset;
  7165. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7166. }
  7167. previousOffset = nextOffset;
  7168. }
  7169. return Vector2.Zero();
  7170. };
  7171. /**
  7172. * Returns a new Path2 starting at the coordinates (x, y).
  7173. */
  7174. Path2.StartingAt = function (x, y) {
  7175. return new Path2(x, y);
  7176. };
  7177. return Path2;
  7178. }());
  7179. BABYLON.Path2 = Path2;
  7180. var Path3D = /** @class */ (function () {
  7181. /**
  7182. * new Path3D(path, normal, raw)
  7183. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7184. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7185. * path : an array of Vector3, the curve axis of the Path3D
  7186. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7187. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7188. */
  7189. function Path3D(path, firstNormal, raw) {
  7190. if (firstNormal === void 0) { firstNormal = null; }
  7191. this.path = path;
  7192. this._curve = new Array();
  7193. this._distances = new Array();
  7194. this._tangents = new Array();
  7195. this._normals = new Array();
  7196. this._binormals = new Array();
  7197. for (var p = 0; p < path.length; p++) {
  7198. this._curve[p] = path[p].clone(); // hard copy
  7199. }
  7200. this._raw = raw || false;
  7201. this._compute(firstNormal);
  7202. }
  7203. /**
  7204. * Returns the Path3D array of successive Vector3 designing its curve.
  7205. */
  7206. Path3D.prototype.getCurve = function () {
  7207. return this._curve;
  7208. };
  7209. /**
  7210. * Returns an array populated with tangent vectors on each Path3D curve point.
  7211. */
  7212. Path3D.prototype.getTangents = function () {
  7213. return this._tangents;
  7214. };
  7215. /**
  7216. * Returns an array populated with normal vectors on each Path3D curve point.
  7217. */
  7218. Path3D.prototype.getNormals = function () {
  7219. return this._normals;
  7220. };
  7221. /**
  7222. * Returns an array populated with binormal vectors on each Path3D curve point.
  7223. */
  7224. Path3D.prototype.getBinormals = function () {
  7225. return this._binormals;
  7226. };
  7227. /**
  7228. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7229. */
  7230. Path3D.prototype.getDistances = function () {
  7231. return this._distances;
  7232. };
  7233. /**
  7234. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7235. * Returns the same object updated.
  7236. */
  7237. Path3D.prototype.update = function (path, firstNormal) {
  7238. if (firstNormal === void 0) { firstNormal = null; }
  7239. for (var p = 0; p < path.length; p++) {
  7240. this._curve[p].x = path[p].x;
  7241. this._curve[p].y = path[p].y;
  7242. this._curve[p].z = path[p].z;
  7243. }
  7244. this._compute(firstNormal);
  7245. return this;
  7246. };
  7247. // private function compute() : computes tangents, normals and binormals
  7248. Path3D.prototype._compute = function (firstNormal) {
  7249. var l = this._curve.length;
  7250. // first and last tangents
  7251. this._tangents[0] = this._getFirstNonNullVector(0);
  7252. if (!this._raw) {
  7253. this._tangents[0].normalize();
  7254. }
  7255. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7256. if (!this._raw) {
  7257. this._tangents[l - 1].normalize();
  7258. }
  7259. // normals and binormals at first point : arbitrary vector with _normalVector()
  7260. var tg0 = this._tangents[0];
  7261. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7262. this._normals[0] = pp0;
  7263. if (!this._raw) {
  7264. this._normals[0].normalize();
  7265. }
  7266. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7267. if (!this._raw) {
  7268. this._binormals[0].normalize();
  7269. }
  7270. this._distances[0] = 0.0;
  7271. // normals and binormals : next points
  7272. var prev; // previous vector (segment)
  7273. var cur; // current vector (segment)
  7274. var curTang; // current tangent
  7275. // previous normal
  7276. var prevBinor; // previous binormal
  7277. for (var i = 1; i < l; i++) {
  7278. // tangents
  7279. prev = this._getLastNonNullVector(i);
  7280. if (i < l - 1) {
  7281. cur = this._getFirstNonNullVector(i);
  7282. this._tangents[i] = prev.add(cur);
  7283. this._tangents[i].normalize();
  7284. }
  7285. this._distances[i] = this._distances[i - 1] + prev.length();
  7286. // normals and binormals
  7287. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7288. curTang = this._tangents[i];
  7289. prevBinor = this._binormals[i - 1];
  7290. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7291. if (!this._raw) {
  7292. this._normals[i].normalize();
  7293. }
  7294. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7295. if (!this._raw) {
  7296. this._binormals[i].normalize();
  7297. }
  7298. }
  7299. };
  7300. // private function getFirstNonNullVector(index)
  7301. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7302. Path3D.prototype._getFirstNonNullVector = function (index) {
  7303. var i = 1;
  7304. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7305. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7306. i++;
  7307. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7308. }
  7309. return nNVector;
  7310. };
  7311. // private function getLastNonNullVector(index)
  7312. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7313. Path3D.prototype._getLastNonNullVector = function (index) {
  7314. var i = 1;
  7315. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7316. while (nLVector.length() === 0 && index > i + 1) {
  7317. i++;
  7318. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7319. }
  7320. return nLVector;
  7321. };
  7322. // private function normalVector(v0, vt, va) :
  7323. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7324. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7325. Path3D.prototype._normalVector = function (v0, vt, va) {
  7326. var normal0;
  7327. var tgl = vt.length();
  7328. if (tgl === 0.0) {
  7329. tgl = 1.0;
  7330. }
  7331. if (va === undefined || va === null) {
  7332. var point;
  7333. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7334. point = new Vector3(0.0, -1.0, 0.0);
  7335. }
  7336. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7337. point = new Vector3(1.0, 0.0, 0.0);
  7338. }
  7339. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7340. point = new Vector3(0.0, 0.0, 1.0);
  7341. }
  7342. else {
  7343. point = Vector3.Zero();
  7344. }
  7345. normal0 = Vector3.Cross(vt, point);
  7346. }
  7347. else {
  7348. normal0 = Vector3.Cross(vt, va);
  7349. Vector3.CrossToRef(normal0, vt, normal0);
  7350. }
  7351. normal0.normalize();
  7352. return normal0;
  7353. };
  7354. return Path3D;
  7355. }());
  7356. BABYLON.Path3D = Path3D;
  7357. var Curve3 = /** @class */ (function () {
  7358. /**
  7359. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7360. * A Curve3 is designed from a series of successive Vector3.
  7361. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7362. */
  7363. function Curve3(points) {
  7364. this._length = 0.0;
  7365. this._points = points;
  7366. this._length = this._computeLength(points);
  7367. }
  7368. /**
  7369. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7370. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7371. * @param v1 (Vector3) the control point
  7372. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7376. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7377. var bez = new Array();
  7378. var equation = function (t, val0, val1, val2) {
  7379. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7380. return res;
  7381. };
  7382. for (var i = 0; i <= nbPoints; i++) {
  7383. 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)));
  7384. }
  7385. return new Curve3(bez);
  7386. };
  7387. /**
  7388. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7389. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7390. * @param v1 (Vector3) the first control point
  7391. * @param v2 (Vector3) the second control point
  7392. * @param v3 (Vector3) the end point of the Cubic Bezier
  7393. * @param nbPoints (integer) the wanted number of points in the curve
  7394. */
  7395. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7396. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7397. var bez = new Array();
  7398. var equation = function (t, val0, val1, val2, val3) {
  7399. 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;
  7400. return res;
  7401. };
  7402. for (var i = 0; i <= nbPoints; i++) {
  7403. 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)));
  7404. }
  7405. return new Curve3(bez);
  7406. };
  7407. /**
  7408. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7409. * @param p1 (Vector3) the origin point of the Hermite Spline
  7410. * @param t1 (Vector3) the tangent vector at the origin point
  7411. * @param p2 (Vector3) the end point of the Hermite Spline
  7412. * @param t2 (Vector3) the tangent vector at the end point
  7413. * @param nbPoints (integer) the wanted number of points in the curve
  7414. */
  7415. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7416. var hermite = new Array();
  7417. var step = 1.0 / nbPoints;
  7418. for (var i = 0; i <= nbPoints; i++) {
  7419. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7420. }
  7421. return new Curve3(hermite);
  7422. };
  7423. /**
  7424. * Returns a Curve3 object along a CatmullRom Spline curve :
  7425. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7426. * @param nbPoints (integer) the wanted number of points between each curve control points
  7427. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7428. */
  7429. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7430. var catmullRom = new Array();
  7431. var step = 1.0 / nbPoints;
  7432. var amount = 0.0;
  7433. if (closed) {
  7434. var pointsCount = points.length;
  7435. for (var i = 0; i < pointsCount; i++) {
  7436. amount = 0;
  7437. for (var c = 0; c < nbPoints; c++) {
  7438. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7439. amount += step;
  7440. }
  7441. }
  7442. catmullRom.push(catmullRom[0]);
  7443. }
  7444. else {
  7445. var totalPoints = new Array();
  7446. totalPoints.push(points[0].clone());
  7447. Array.prototype.push.apply(totalPoints, points);
  7448. totalPoints.push(points[points.length - 1].clone());
  7449. for (var i = 0; i < totalPoints.length - 3; i++) {
  7450. amount = 0;
  7451. for (var c = 0; c < nbPoints; c++) {
  7452. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7453. amount += step;
  7454. }
  7455. }
  7456. i--;
  7457. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7458. }
  7459. return new Curve3(catmullRom);
  7460. };
  7461. /**
  7462. * Returns the Curve3 stored array of successive Vector3
  7463. */
  7464. Curve3.prototype.getPoints = function () {
  7465. return this._points;
  7466. };
  7467. /**
  7468. * Returns the computed length (float) of the curve.
  7469. */
  7470. Curve3.prototype.length = function () {
  7471. return this._length;
  7472. };
  7473. /**
  7474. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7475. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7476. * curveA and curveB keep unchanged.
  7477. */
  7478. Curve3.prototype.continue = function (curve) {
  7479. var lastPoint = this._points[this._points.length - 1];
  7480. var continuedPoints = this._points.slice();
  7481. var curvePoints = curve.getPoints();
  7482. for (var i = 1; i < curvePoints.length; i++) {
  7483. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7484. }
  7485. var continuedCurve = new Curve3(continuedPoints);
  7486. return continuedCurve;
  7487. };
  7488. Curve3.prototype._computeLength = function (path) {
  7489. var l = 0;
  7490. for (var i = 1; i < path.length; i++) {
  7491. l += (path[i].subtract(path[i - 1])).length();
  7492. }
  7493. return l;
  7494. };
  7495. return Curve3;
  7496. }());
  7497. BABYLON.Curve3 = Curve3;
  7498. // Vertex formats
  7499. var PositionNormalVertex = /** @class */ (function () {
  7500. function PositionNormalVertex(position, normal) {
  7501. if (position === void 0) { position = Vector3.Zero(); }
  7502. if (normal === void 0) { normal = Vector3.Up(); }
  7503. this.position = position;
  7504. this.normal = normal;
  7505. }
  7506. PositionNormalVertex.prototype.clone = function () {
  7507. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7508. };
  7509. return PositionNormalVertex;
  7510. }());
  7511. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7512. var PositionNormalTextureVertex = /** @class */ (function () {
  7513. function PositionNormalTextureVertex(position, normal, uv) {
  7514. if (position === void 0) { position = Vector3.Zero(); }
  7515. if (normal === void 0) { normal = Vector3.Up(); }
  7516. if (uv === void 0) { uv = Vector2.Zero(); }
  7517. this.position = position;
  7518. this.normal = normal;
  7519. this.uv = uv;
  7520. }
  7521. PositionNormalTextureVertex.prototype.clone = function () {
  7522. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7523. };
  7524. return PositionNormalTextureVertex;
  7525. }());
  7526. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7527. // Temporary pre-allocated objects for engine internal use
  7528. // usage in any internal function :
  7529. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7530. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7531. var Tmp = /** @class */ (function () {
  7532. function Tmp() {
  7533. }
  7534. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7535. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7536. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7537. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7538. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7539. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7540. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7541. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7542. Matrix.Zero(), Matrix.Zero(),
  7543. Matrix.Zero(), Matrix.Zero(),
  7544. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7545. return Tmp;
  7546. }());
  7547. BABYLON.Tmp = Tmp;
  7548. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7549. var MathTmp = /** @class */ (function () {
  7550. function MathTmp() {
  7551. }
  7552. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7553. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7554. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7555. return MathTmp;
  7556. }());
  7557. })(BABYLON || (BABYLON = {}));
  7558. //# sourceMappingURL=babylon.math.js.map
  7559. var BABYLON;
  7560. (function (BABYLON) {
  7561. var Scalar = /** @class */ (function () {
  7562. function Scalar() {
  7563. }
  7564. /**
  7565. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7566. */
  7567. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7568. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7569. var num = a - b;
  7570. return -epsilon <= num && num <= epsilon;
  7571. };
  7572. /**
  7573. * Returns a string : the upper case translation of the number i to hexadecimal.
  7574. */
  7575. Scalar.ToHex = function (i) {
  7576. var str = i.toString(16);
  7577. if (i <= 15) {
  7578. return ("0" + str).toUpperCase();
  7579. }
  7580. return str.toUpperCase();
  7581. };
  7582. /**
  7583. * Returns -1 if value is negative and +1 is value is positive.
  7584. * Returns the value itself if it's equal to zero.
  7585. */
  7586. Scalar.Sign = function (value) {
  7587. value = +value; // convert to a number
  7588. if (value === 0 || isNaN(value))
  7589. return value;
  7590. return value > 0 ? 1 : -1;
  7591. };
  7592. /**
  7593. * Returns the value itself if it's between min and max.
  7594. * Returns min if the value is lower than min.
  7595. * Returns max if the value is greater than max.
  7596. */
  7597. Scalar.Clamp = function (value, min, max) {
  7598. if (min === void 0) { min = 0; }
  7599. if (max === void 0) { max = 1; }
  7600. return Math.min(max, Math.max(min, value));
  7601. };
  7602. /**
  7603. * Returns the log2 of value.
  7604. */
  7605. Scalar.Log2 = function (value) {
  7606. return Math.log(value) * Math.LOG2E;
  7607. };
  7608. /**
  7609. * Loops the value, so that it is never larger than length and never smaller than 0.
  7610. *
  7611. * This is similar to the modulo operator but it works with floating point numbers.
  7612. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7613. * With t = 5 and length = 2.5, the result would be 0.0.
  7614. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7615. */
  7616. Scalar.Repeat = function (value, length) {
  7617. return value - Math.floor(value / length) * length;
  7618. };
  7619. /**
  7620. * Normalize the value between 0.0 and 1.0 using min and max values
  7621. */
  7622. Scalar.Normalize = function (value, min, max) {
  7623. return (value - min) / (max - min);
  7624. };
  7625. /**
  7626. * Denormalize the value from 0.0 and 1.0 using min and max values
  7627. */
  7628. Scalar.Denormalize = function (normalized, min, max) {
  7629. return (normalized * (max - min) + min);
  7630. };
  7631. /**
  7632. * Calculates the shortest difference between two given angles given in degrees.
  7633. */
  7634. Scalar.DeltaAngle = function (current, target) {
  7635. var num = Scalar.Repeat(target - current, 360.0);
  7636. if (num > 180.0) {
  7637. num -= 360.0;
  7638. }
  7639. return num;
  7640. };
  7641. /**
  7642. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7643. *
  7644. * The returned value will move back and forth between 0 and length
  7645. */
  7646. Scalar.PingPong = function (tx, length) {
  7647. var t = Scalar.Repeat(tx, length * 2.0);
  7648. return length - Math.abs(t - length);
  7649. };
  7650. /**
  7651. * Interpolates between min and max with smoothing at the limits.
  7652. *
  7653. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7654. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7655. */
  7656. Scalar.SmoothStep = function (from, to, tx) {
  7657. var t = Scalar.Clamp(tx);
  7658. t = -2.0 * t * t * t + 3.0 * t * t;
  7659. return to * t + from * (1.0 - t);
  7660. };
  7661. /**
  7662. * Moves a value current towards target.
  7663. *
  7664. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7665. * Negative values of maxDelta pushes the value away from target.
  7666. */
  7667. Scalar.MoveTowards = function (current, target, maxDelta) {
  7668. var result = 0;
  7669. if (Math.abs(target - current) <= maxDelta) {
  7670. result = target;
  7671. }
  7672. else {
  7673. result = current + Scalar.Sign(target - current) * maxDelta;
  7674. }
  7675. return result;
  7676. };
  7677. /**
  7678. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7679. *
  7680. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7681. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7682. */
  7683. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7684. var num = Scalar.DeltaAngle(current, target);
  7685. var result = 0;
  7686. if (-maxDelta < num && num < maxDelta) {
  7687. result = target;
  7688. }
  7689. else {
  7690. target = current + num;
  7691. result = Scalar.MoveTowards(current, target, maxDelta);
  7692. }
  7693. return result;
  7694. };
  7695. /**
  7696. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7697. */
  7698. Scalar.Lerp = function (start, end, amount) {
  7699. return start + ((end - start) * amount);
  7700. };
  7701. /**
  7702. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7703. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7704. */
  7705. Scalar.LerpAngle = function (start, end, amount) {
  7706. var num = Scalar.Repeat(end - start, 360.0);
  7707. if (num > 180.0) {
  7708. num -= 360.0;
  7709. }
  7710. return start + num * Scalar.Clamp(amount);
  7711. };
  7712. /**
  7713. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7714. */
  7715. Scalar.InverseLerp = function (a, b, value) {
  7716. var result = 0;
  7717. if (a != b) {
  7718. result = Scalar.Clamp((value - a) / (b - a));
  7719. }
  7720. else {
  7721. result = 0.0;
  7722. }
  7723. return result;
  7724. };
  7725. /**
  7726. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7727. */
  7728. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7729. var squared = amount * amount;
  7730. var cubed = amount * squared;
  7731. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7732. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7733. var part3 = (cubed - (2.0 * squared)) + amount;
  7734. var part4 = cubed - squared;
  7735. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7736. };
  7737. /**
  7738. * Returns a random float number between and min and max values
  7739. */
  7740. Scalar.RandomRange = function (min, max) {
  7741. if (min === max)
  7742. return min;
  7743. return ((Math.random() * (max - min)) + min);
  7744. };
  7745. /**
  7746. * This function returns percentage of a number in a given range.
  7747. *
  7748. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7749. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7750. */
  7751. Scalar.RangeToPercent = function (number, min, max) {
  7752. return ((number - min) / (max - min));
  7753. };
  7754. /**
  7755. * This function returns number that corresponds to the percentage in a given range.
  7756. *
  7757. * PercentToRange(0.34,0,100) will return 34.
  7758. */
  7759. Scalar.PercentToRange = function (percent, min, max) {
  7760. return ((max - min) * percent + min);
  7761. };
  7762. /**
  7763. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7764. * @param angle The angle to normalize in radian.
  7765. * @return The converted angle.
  7766. */
  7767. Scalar.NormalizeRadians = function (angle) {
  7768. // More precise but slower version kept for reference.
  7769. // angle = angle % Tools.TwoPi;
  7770. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7771. //if (angle > Math.PI) {
  7772. // angle -= Tools.TwoPi;
  7773. //}
  7774. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7775. return angle;
  7776. };
  7777. /**
  7778. * Two pi constants convenient for computation.
  7779. */
  7780. Scalar.TwoPi = Math.PI * 2;
  7781. return Scalar;
  7782. }());
  7783. BABYLON.Scalar = Scalar;
  7784. })(BABYLON || (BABYLON = {}));
  7785. //# sourceMappingURL=babylon.math.scalar.js.map
  7786. //# sourceMappingURL=babylon.mixins.js.map
  7787. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7788. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7789. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7790. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7791. //# sourceMappingURL=babylon.webgl2.js.map
  7792. var BABYLON;
  7793. (function (BABYLON) {
  7794. var __decoratorInitialStore = {};
  7795. var __mergedStore = {};
  7796. var _copySource = function (creationFunction, source, instanciate) {
  7797. var destination = creationFunction();
  7798. // Tags
  7799. if (BABYLON.Tags) {
  7800. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7801. }
  7802. var classStore = getMergedStore(destination);
  7803. // Properties
  7804. for (var property in classStore) {
  7805. var propertyDescriptor = classStore[property];
  7806. var sourceProperty = source[property];
  7807. var propertyType = propertyDescriptor.type;
  7808. if (sourceProperty !== undefined && sourceProperty !== null) {
  7809. switch (propertyType) {
  7810. case 0: // Value
  7811. case 6: // Mesh reference
  7812. case 11: // Camera reference
  7813. destination[property] = sourceProperty;
  7814. break;
  7815. case 1: // Texture
  7816. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7817. break;
  7818. case 2: // Color3
  7819. case 3: // FresnelParameters
  7820. case 4: // Vector2
  7821. case 5: // Vector3
  7822. case 7: // Color Curves
  7823. case 10: // Quaternion
  7824. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7825. break;
  7826. }
  7827. }
  7828. }
  7829. return destination;
  7830. };
  7831. function getDirectStore(target) {
  7832. var classKey = target.getClassName();
  7833. if (!__decoratorInitialStore[classKey]) {
  7834. __decoratorInitialStore[classKey] = {};
  7835. }
  7836. return __decoratorInitialStore[classKey];
  7837. }
  7838. /**
  7839. * Return the list of properties flagged as serializable
  7840. * @param target: host object
  7841. */
  7842. function getMergedStore(target) {
  7843. var classKey = target.getClassName();
  7844. if (__mergedStore[classKey]) {
  7845. return __mergedStore[classKey];
  7846. }
  7847. __mergedStore[classKey] = {};
  7848. var store = __mergedStore[classKey];
  7849. var currentTarget = target;
  7850. var currentKey = classKey;
  7851. while (currentKey) {
  7852. var initialStore = __decoratorInitialStore[currentKey];
  7853. for (var property in initialStore) {
  7854. store[property] = initialStore[property];
  7855. }
  7856. var parent_1 = void 0;
  7857. var done = false;
  7858. do {
  7859. parent_1 = Object.getPrototypeOf(currentTarget);
  7860. if (!parent_1.getClassName) {
  7861. done = true;
  7862. break;
  7863. }
  7864. if (parent_1.getClassName() !== currentKey) {
  7865. break;
  7866. }
  7867. currentTarget = parent_1;
  7868. } while (parent_1);
  7869. if (done) {
  7870. break;
  7871. }
  7872. currentKey = parent_1.getClassName();
  7873. currentTarget = parent_1;
  7874. }
  7875. return store;
  7876. }
  7877. function generateSerializableMember(type, sourceName) {
  7878. return function (target, propertyKey) {
  7879. var classStore = getDirectStore(target);
  7880. if (!classStore[propertyKey]) {
  7881. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7882. }
  7883. };
  7884. }
  7885. function generateExpandMember(setCallback, targetKey) {
  7886. if (targetKey === void 0) { targetKey = null; }
  7887. return function (target, propertyKey) {
  7888. var key = targetKey || ("_" + propertyKey);
  7889. Object.defineProperty(target, propertyKey, {
  7890. get: function () {
  7891. return this[key];
  7892. },
  7893. set: function (value) {
  7894. if (this[key] === value) {
  7895. return;
  7896. }
  7897. this[key] = value;
  7898. target[setCallback].apply(this);
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. };
  7904. }
  7905. function expandToProperty(callback, targetKey) {
  7906. if (targetKey === void 0) { targetKey = null; }
  7907. return generateExpandMember(callback, targetKey);
  7908. }
  7909. BABYLON.expandToProperty = expandToProperty;
  7910. function serialize(sourceName) {
  7911. return generateSerializableMember(0, sourceName); // value member
  7912. }
  7913. BABYLON.serialize = serialize;
  7914. function serializeAsTexture(sourceName) {
  7915. return generateSerializableMember(1, sourceName); // texture member
  7916. }
  7917. BABYLON.serializeAsTexture = serializeAsTexture;
  7918. function serializeAsColor3(sourceName) {
  7919. return generateSerializableMember(2, sourceName); // color3 member
  7920. }
  7921. BABYLON.serializeAsColor3 = serializeAsColor3;
  7922. function serializeAsFresnelParameters(sourceName) {
  7923. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7924. }
  7925. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7926. function serializeAsVector2(sourceName) {
  7927. return generateSerializableMember(4, sourceName); // vector2 member
  7928. }
  7929. BABYLON.serializeAsVector2 = serializeAsVector2;
  7930. function serializeAsVector3(sourceName) {
  7931. return generateSerializableMember(5, sourceName); // vector3 member
  7932. }
  7933. BABYLON.serializeAsVector3 = serializeAsVector3;
  7934. function serializeAsMeshReference(sourceName) {
  7935. return generateSerializableMember(6, sourceName); // mesh reference member
  7936. }
  7937. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7938. function serializeAsColorCurves(sourceName) {
  7939. return generateSerializableMember(7, sourceName); // color curves
  7940. }
  7941. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7942. function serializeAsColor4(sourceName) {
  7943. return generateSerializableMember(8, sourceName); // color 4
  7944. }
  7945. BABYLON.serializeAsColor4 = serializeAsColor4;
  7946. function serializeAsImageProcessingConfiguration(sourceName) {
  7947. return generateSerializableMember(9, sourceName); // image processing
  7948. }
  7949. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7950. function serializeAsQuaternion(sourceName) {
  7951. return generateSerializableMember(10, sourceName); // quaternion member
  7952. }
  7953. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7954. /**
  7955. * Decorator used to define property that can be serialized as reference to a camera
  7956. * @param sourceName defines the name of the property to decorate
  7957. */
  7958. function serializeAsCameraReference(sourceName) {
  7959. return generateSerializableMember(11, sourceName); // camera reference member
  7960. }
  7961. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7962. var SerializationHelper = /** @class */ (function () {
  7963. function SerializationHelper() {
  7964. }
  7965. SerializationHelper.Serialize = function (entity, serializationObject) {
  7966. if (!serializationObject) {
  7967. serializationObject = {};
  7968. }
  7969. // Tags
  7970. if (BABYLON.Tags) {
  7971. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7972. }
  7973. var serializedProperties = getMergedStore(entity);
  7974. // Properties
  7975. for (var property in serializedProperties) {
  7976. var propertyDescriptor = serializedProperties[property];
  7977. var targetPropertyName = propertyDescriptor.sourceName || property;
  7978. var propertyType = propertyDescriptor.type;
  7979. var sourceProperty = entity[property];
  7980. if (sourceProperty !== undefined && sourceProperty !== null) {
  7981. switch (propertyType) {
  7982. case 0: // Value
  7983. serializationObject[targetPropertyName] = sourceProperty;
  7984. break;
  7985. case 1: // Texture
  7986. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7987. break;
  7988. case 2: // Color3
  7989. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7990. break;
  7991. case 3: // FresnelParameters
  7992. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7993. break;
  7994. case 4: // Vector2
  7995. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7996. break;
  7997. case 5: // Vector3
  7998. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7999. break;
  8000. case 6: // Mesh reference
  8001. serializationObject[targetPropertyName] = sourceProperty.id;
  8002. break;
  8003. case 7: // Color Curves
  8004. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8005. break;
  8006. case 8: // Color 4
  8007. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8008. break;
  8009. case 9: // Image Processing
  8010. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8011. break;
  8012. case 10: // Quaternion
  8013. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8014. break;
  8015. case 11: // Camera reference
  8016. serializationObject[targetPropertyName] = sourceProperty.id;
  8017. break;
  8018. }
  8019. }
  8020. }
  8021. return serializationObject;
  8022. };
  8023. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8024. if (rootUrl === void 0) { rootUrl = null; }
  8025. var destination = creationFunction();
  8026. if (!rootUrl) {
  8027. rootUrl = "";
  8028. }
  8029. // Tags
  8030. if (BABYLON.Tags) {
  8031. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8032. }
  8033. var classStore = getMergedStore(destination);
  8034. // Properties
  8035. for (var property in classStore) {
  8036. var propertyDescriptor = classStore[property];
  8037. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8038. var propertyType = propertyDescriptor.type;
  8039. if (sourceProperty !== undefined && sourceProperty !== null) {
  8040. var dest = destination;
  8041. switch (propertyType) {
  8042. case 0: // Value
  8043. dest[property] = sourceProperty;
  8044. break;
  8045. case 1: // Texture
  8046. if (scene) {
  8047. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8048. }
  8049. break;
  8050. case 2: // Color3
  8051. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8052. break;
  8053. case 3: // FresnelParameters
  8054. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8055. break;
  8056. case 4: // Vector2
  8057. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8058. break;
  8059. case 5: // Vector3
  8060. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8061. break;
  8062. case 6: // Mesh reference
  8063. if (scene) {
  8064. dest[property] = scene.getLastMeshByID(sourceProperty);
  8065. }
  8066. break;
  8067. case 7: // Color Curves
  8068. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8069. break;
  8070. case 8: // Color 4
  8071. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8072. break;
  8073. case 9: // Image Processing
  8074. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8075. break;
  8076. case 10: // Quaternion
  8077. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8078. break;
  8079. case 11: // Camera reference
  8080. if (scene) {
  8081. dest[property] = scene.getCameraByID(sourceProperty);
  8082. }
  8083. break;
  8084. }
  8085. }
  8086. }
  8087. return destination;
  8088. };
  8089. SerializationHelper.Clone = function (creationFunction, source) {
  8090. return _copySource(creationFunction, source, false);
  8091. };
  8092. SerializationHelper.Instanciate = function (creationFunction, source) {
  8093. return _copySource(creationFunction, source, true);
  8094. };
  8095. return SerializationHelper;
  8096. }());
  8097. BABYLON.SerializationHelper = SerializationHelper;
  8098. })(BABYLON || (BABYLON = {}));
  8099. //# sourceMappingURL=babylon.decorators.js.map
  8100. var BABYLON;
  8101. (function (BABYLON) {
  8102. /**
  8103. * Wrapper class for promise with external resolve and reject.
  8104. */
  8105. var Deferred = /** @class */ (function () {
  8106. /**
  8107. * Constructor for this deferred object.
  8108. */
  8109. function Deferred() {
  8110. var _this = this;
  8111. this.promise = new Promise(function (resolve, reject) {
  8112. _this._resolve = resolve;
  8113. _this._reject = reject;
  8114. });
  8115. }
  8116. Object.defineProperty(Deferred.prototype, "resolve", {
  8117. /**
  8118. * The resolve method of the promise associated with this deferred object.
  8119. */
  8120. get: function () {
  8121. return this._resolve;
  8122. },
  8123. enumerable: true,
  8124. configurable: true
  8125. });
  8126. Object.defineProperty(Deferred.prototype, "reject", {
  8127. /**
  8128. * The reject method of the promise associated with this deferred object.
  8129. */
  8130. get: function () {
  8131. return this._reject;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. return Deferred;
  8137. }());
  8138. BABYLON.Deferred = Deferred;
  8139. })(BABYLON || (BABYLON = {}));
  8140. //# sourceMappingURL=babylon.deferred.js.map
  8141. var BABYLON;
  8142. (function (BABYLON) {
  8143. /**
  8144. * A class serves as a medium between the observable and its observers
  8145. */
  8146. var EventState = /** @class */ (function () {
  8147. /**
  8148. * Create a new EventState
  8149. * @param mask defines the mask associated with this state
  8150. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8151. * @param target defines the original target of the state
  8152. * @param currentTarget defines the current target of the state
  8153. */
  8154. function EventState(mask, skipNextObservers, target, currentTarget) {
  8155. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8156. this.initalize(mask, skipNextObservers, target, currentTarget);
  8157. }
  8158. /**
  8159. * Initialize the current event state
  8160. * @param mask defines the mask associated with this state
  8161. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8162. * @param target defines the original target of the state
  8163. * @param currentTarget defines the current target of the state
  8164. * @returns the current event state
  8165. */
  8166. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8167. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8168. this.mask = mask;
  8169. this.skipNextObservers = skipNextObservers;
  8170. this.target = target;
  8171. this.currentTarget = currentTarget;
  8172. return this;
  8173. };
  8174. return EventState;
  8175. }());
  8176. BABYLON.EventState = EventState;
  8177. /**
  8178. * Represent an Observer registered to a given Observable object.
  8179. */
  8180. var Observer = /** @class */ (function () {
  8181. /**
  8182. * Creates a new observer
  8183. * @param callback defines the callback to call when the observer is notified
  8184. * @param mask defines the mask of the observer (used to filter notifications)
  8185. * @param scope defines the current scope used to restore the JS context
  8186. */
  8187. function Observer(
  8188. /**
  8189. * Defines the callback to call when the observer is notified
  8190. */
  8191. callback,
  8192. /**
  8193. * Defines the mask of the observer (used to filter notifications)
  8194. */
  8195. mask,
  8196. /**
  8197. * Defines the current scope used to restore the JS context
  8198. */
  8199. scope) {
  8200. if (scope === void 0) { scope = null; }
  8201. this.callback = callback;
  8202. this.mask = mask;
  8203. this.scope = scope;
  8204. /** @hidden */
  8205. this._willBeUnregistered = false;
  8206. /**
  8207. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8208. */
  8209. this.unregisterOnNextCall = false;
  8210. }
  8211. return Observer;
  8212. }());
  8213. BABYLON.Observer = Observer;
  8214. /**
  8215. * Represent a list of observers registered to multiple Observables object.
  8216. */
  8217. var MultiObserver = /** @class */ (function () {
  8218. function MultiObserver() {
  8219. }
  8220. /**
  8221. * Release associated resources
  8222. */
  8223. MultiObserver.prototype.dispose = function () {
  8224. if (this._observers && this._observables) {
  8225. for (var index = 0; index < this._observers.length; index++) {
  8226. this._observables[index].remove(this._observers[index]);
  8227. }
  8228. }
  8229. this._observers = null;
  8230. this._observables = null;
  8231. };
  8232. /**
  8233. * Raise a callback when one of the observable will notify
  8234. * @param observables defines a list of observables to watch
  8235. * @param callback defines the callback to call on notification
  8236. * @param mask defines the mask used to filter notifications
  8237. * @param scope defines the current scope used to restore the JS context
  8238. * @returns the new MultiObserver
  8239. */
  8240. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8241. if (mask === void 0) { mask = -1; }
  8242. if (scope === void 0) { scope = null; }
  8243. var result = new MultiObserver();
  8244. result._observers = new Array();
  8245. result._observables = observables;
  8246. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8247. var observable = observables_1[_i];
  8248. var observer = observable.add(callback, mask, false, scope);
  8249. if (observer) {
  8250. result._observers.push(observer);
  8251. }
  8252. }
  8253. return result;
  8254. };
  8255. return MultiObserver;
  8256. }());
  8257. BABYLON.MultiObserver = MultiObserver;
  8258. /**
  8259. * The Observable class is a simple implementation of the Observable pattern.
  8260. *
  8261. * 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.
  8262. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8263. * 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).
  8264. * 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.
  8265. */
  8266. var Observable = /** @class */ (function () {
  8267. /**
  8268. * Creates a new observable
  8269. * @param onObserverAdded defines a callback to call when a new observer is added
  8270. */
  8271. function Observable(onObserverAdded) {
  8272. this._observers = new Array();
  8273. this._eventState = new EventState(0);
  8274. if (onObserverAdded) {
  8275. this._onObserverAdded = onObserverAdded;
  8276. }
  8277. }
  8278. /**
  8279. * Create a new Observer with the specified callback
  8280. * @param callback the callback that will be executed for that Observer
  8281. * @param mask the mask used to filter observers
  8282. * @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.
  8283. * @param scope optional scope for the callback to be called from
  8284. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8285. * @returns the new observer created for the callback
  8286. */
  8287. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8288. if (mask === void 0) { mask = -1; }
  8289. if (insertFirst === void 0) { insertFirst = false; }
  8290. if (scope === void 0) { scope = null; }
  8291. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8292. if (!callback) {
  8293. return null;
  8294. }
  8295. var observer = new Observer(callback, mask, scope);
  8296. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8297. if (insertFirst) {
  8298. this._observers.unshift(observer);
  8299. }
  8300. else {
  8301. this._observers.push(observer);
  8302. }
  8303. if (this._onObserverAdded) {
  8304. this._onObserverAdded(observer);
  8305. }
  8306. return observer;
  8307. };
  8308. /**
  8309. * Create a new Observer with the specified callback and unregisters after the next notification
  8310. * @param callback the callback that will be executed for that Observer
  8311. * @returns the new observer created for the callback
  8312. */
  8313. Observable.prototype.addOnce = function (callback) {
  8314. return this.add(callback, undefined, undefined, undefined, true);
  8315. };
  8316. /**
  8317. * Remove an Observer from the Observable object
  8318. * @param observer the instance of the Observer to remove
  8319. * @returns false if it doesn't belong to this Observable
  8320. */
  8321. Observable.prototype.remove = function (observer) {
  8322. if (!observer) {
  8323. return false;
  8324. }
  8325. var index = this._observers.indexOf(observer);
  8326. if (index !== -1) {
  8327. this._deferUnregister(observer);
  8328. return true;
  8329. }
  8330. return false;
  8331. };
  8332. /**
  8333. * Remove a callback from the Observable object
  8334. * @param callback the callback to remove
  8335. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8336. * @returns false if it doesn't belong to this Observable
  8337. */
  8338. Observable.prototype.removeCallback = function (callback, scope) {
  8339. for (var index = 0; index < this._observers.length; index++) {
  8340. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8341. this._deferUnregister(this._observers[index]);
  8342. return true;
  8343. }
  8344. }
  8345. return false;
  8346. };
  8347. Observable.prototype._deferUnregister = function (observer) {
  8348. var _this = this;
  8349. observer.unregisterOnNextCall = false;
  8350. observer._willBeUnregistered = true;
  8351. BABYLON.Tools.SetImmediate(function () {
  8352. _this._remove(observer);
  8353. });
  8354. };
  8355. // This should only be called when not iterating over _observers to avoid callback skipping.
  8356. // Removes an observer from the _observer Array.
  8357. Observable.prototype._remove = function (observer) {
  8358. if (!observer) {
  8359. return false;
  8360. }
  8361. var index = this._observers.indexOf(observer);
  8362. if (index !== -1) {
  8363. this._observers.splice(index, 1);
  8364. return true;
  8365. }
  8366. return false;
  8367. };
  8368. /**
  8369. * Notify all Observers by calling their respective callback with the given data
  8370. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8371. * @param eventData defines the data to send to all observers
  8372. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8373. * @param target defines the original target of the state
  8374. * @param currentTarget defines the current target of the state
  8375. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8376. */
  8377. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8378. if (mask === void 0) { mask = -1; }
  8379. if (!this._observers.length) {
  8380. return true;
  8381. }
  8382. var state = this._eventState;
  8383. state.mask = mask;
  8384. state.target = target;
  8385. state.currentTarget = currentTarget;
  8386. state.skipNextObservers = false;
  8387. state.lastReturnValue = eventData;
  8388. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8389. var obs = _a[_i];
  8390. if (obs._willBeUnregistered) {
  8391. continue;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8396. }
  8397. else {
  8398. state.lastReturnValue = obs.callback(eventData, state);
  8399. }
  8400. if (obs.unregisterOnNextCall) {
  8401. this._deferUnregister(obs);
  8402. }
  8403. }
  8404. if (state.skipNextObservers) {
  8405. return false;
  8406. }
  8407. }
  8408. return true;
  8409. };
  8410. /**
  8411. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8412. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8413. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8414. * and it is crucial that all callbacks will be executed.
  8415. * The order of the callbacks is kept, callbacks are not executed parallel.
  8416. *
  8417. * @param eventData The data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. * @param target defines the callback target (see EventState)
  8420. * @param currentTarget defines he current object in the bubbling phase
  8421. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8422. */
  8423. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8424. var _this = this;
  8425. if (mask === void 0) { mask = -1; }
  8426. // create an empty promise
  8427. var p = Promise.resolve(eventData);
  8428. // no observers? return this promise.
  8429. if (!this._observers.length) {
  8430. return p;
  8431. }
  8432. var state = this._eventState;
  8433. state.mask = mask;
  8434. state.target = target;
  8435. state.currentTarget = currentTarget;
  8436. state.skipNextObservers = false;
  8437. // execute one callback after another (not using Promise.all, the order is important)
  8438. this._observers.forEach(function (obs) {
  8439. if (state.skipNextObservers) {
  8440. return;
  8441. }
  8442. if (obs._willBeUnregistered) {
  8443. return;
  8444. }
  8445. if (obs.mask & mask) {
  8446. if (obs.scope) {
  8447. p = p.then(function (lastReturnedValue) {
  8448. state.lastReturnValue = lastReturnedValue;
  8449. return obs.callback.apply(obs.scope, [eventData, state]);
  8450. });
  8451. }
  8452. else {
  8453. p = p.then(function (lastReturnedValue) {
  8454. state.lastReturnValue = lastReturnedValue;
  8455. return obs.callback(eventData, state);
  8456. });
  8457. }
  8458. if (obs.unregisterOnNextCall) {
  8459. _this._deferUnregister(obs);
  8460. }
  8461. }
  8462. });
  8463. // return the eventData
  8464. return p.then(function () { return eventData; });
  8465. };
  8466. /**
  8467. * Notify a specific observer
  8468. * @param observer defines the observer to notify
  8469. * @param eventData defines the data to be sent to each callback
  8470. * @param mask is used to filter observers defaults to -1
  8471. */
  8472. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8473. if (mask === void 0) { mask = -1; }
  8474. var state = this._eventState;
  8475. state.mask = mask;
  8476. state.skipNextObservers = false;
  8477. observer.callback(eventData, state);
  8478. };
  8479. /**
  8480. * Gets a boolean indicating if the observable has at least one observer
  8481. * @returns true is the Observable has at least one Observer registered
  8482. */
  8483. Observable.prototype.hasObservers = function () {
  8484. return this._observers.length > 0;
  8485. };
  8486. /**
  8487. * Clear the list of observers
  8488. */
  8489. Observable.prototype.clear = function () {
  8490. this._observers = new Array();
  8491. this._onObserverAdded = null;
  8492. };
  8493. /**
  8494. * Clone the current observable
  8495. * @returns a new observable
  8496. */
  8497. Observable.prototype.clone = function () {
  8498. var result = new Observable();
  8499. result._observers = this._observers.slice(0);
  8500. return result;
  8501. };
  8502. /**
  8503. * Does this observable handles observer registered with a given mask
  8504. * @param mask defines the mask to be tested
  8505. * @return whether or not one observer registered with the given mask is handeled
  8506. **/
  8507. Observable.prototype.hasSpecificMask = function (mask) {
  8508. if (mask === void 0) { mask = -1; }
  8509. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8510. var obs = _a[_i];
  8511. if (obs.mask & mask || obs.mask === mask) {
  8512. return true;
  8513. }
  8514. }
  8515. return false;
  8516. };
  8517. return Observable;
  8518. }());
  8519. BABYLON.Observable = Observable;
  8520. })(BABYLON || (BABYLON = {}));
  8521. //# sourceMappingURL=babylon.observable.js.map
  8522. var BABYLON;
  8523. (function (BABYLON) {
  8524. /**
  8525. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8526. */
  8527. var SmartArray = /** @class */ (function () {
  8528. /**
  8529. * Instantiates a Smart Array.
  8530. * @param capacity defines the default capacity of the array.
  8531. */
  8532. function SmartArray(capacity) {
  8533. /**
  8534. * The active length of the array.
  8535. */
  8536. this.length = 0;
  8537. this.data = new Array(capacity);
  8538. this._id = SmartArray._GlobalId++;
  8539. }
  8540. /**
  8541. * Pushes a value at the end of the active data.
  8542. * @param value defines the object to push in the array.
  8543. */
  8544. SmartArray.prototype.push = function (value) {
  8545. this.data[this.length++] = value;
  8546. if (this.length > this.data.length) {
  8547. this.data.length *= 2;
  8548. }
  8549. };
  8550. /**
  8551. * Iterates over the active data and apply the lambda to them.
  8552. * @param func defines the action to apply on each value.
  8553. */
  8554. SmartArray.prototype.forEach = function (func) {
  8555. for (var index = 0; index < this.length; index++) {
  8556. func(this.data[index]);
  8557. }
  8558. };
  8559. /**
  8560. * Sorts the full sets of data.
  8561. * @param compareFn defines the comparison function to apply.
  8562. */
  8563. SmartArray.prototype.sort = function (compareFn) {
  8564. this.data.sort(compareFn);
  8565. };
  8566. /**
  8567. * Resets the active data to an empty array.
  8568. */
  8569. SmartArray.prototype.reset = function () {
  8570. this.length = 0;
  8571. };
  8572. /**
  8573. * Releases all the data from the array as well as the array.
  8574. */
  8575. SmartArray.prototype.dispose = function () {
  8576. this.reset();
  8577. if (this.data) {
  8578. this.data.length = 0;
  8579. this.data = [];
  8580. }
  8581. };
  8582. /**
  8583. * Concats the active data with a given array.
  8584. * @param array defines the data to concatenate with.
  8585. */
  8586. SmartArray.prototype.concat = function (array) {
  8587. if (array.length === 0) {
  8588. return;
  8589. }
  8590. if (this.length + array.length > this.data.length) {
  8591. this.data.length = (this.length + array.length) * 2;
  8592. }
  8593. for (var index = 0; index < array.length; index++) {
  8594. this.data[this.length++] = (array.data || array)[index];
  8595. }
  8596. };
  8597. /**
  8598. * Returns the position of a value in the active data.
  8599. * @param value defines the value to find the index for
  8600. * @returns the index if found in the active data otherwise -1
  8601. */
  8602. SmartArray.prototype.indexOf = function (value) {
  8603. var position = this.data.indexOf(value);
  8604. if (position >= this.length) {
  8605. return -1;
  8606. }
  8607. return position;
  8608. };
  8609. /**
  8610. * Returns whether an element is part of the active data.
  8611. * @param value defines the value to look for
  8612. * @returns true if found in the active data otherwise false
  8613. */
  8614. SmartArray.prototype.contains = function (value) {
  8615. return this.indexOf(value) !== -1;
  8616. };
  8617. // Statics
  8618. SmartArray._GlobalId = 0;
  8619. return SmartArray;
  8620. }());
  8621. BABYLON.SmartArray = SmartArray;
  8622. /**
  8623. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8624. * The data in this array can only be present once
  8625. */
  8626. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8627. __extends(SmartArrayNoDuplicate, _super);
  8628. function SmartArrayNoDuplicate() {
  8629. var _this = _super !== null && _super.apply(this, arguments) || this;
  8630. _this._duplicateId = 0;
  8631. return _this;
  8632. }
  8633. /**
  8634. * Pushes a value at the end of the active data.
  8635. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8636. * @param value defines the object to push in the array.
  8637. */
  8638. SmartArrayNoDuplicate.prototype.push = function (value) {
  8639. _super.prototype.push.call(this, value);
  8640. if (!value.__smartArrayFlags) {
  8641. value.__smartArrayFlags = {};
  8642. }
  8643. value.__smartArrayFlags[this._id] = this._duplicateId;
  8644. };
  8645. /**
  8646. * Pushes a value at the end of the active data.
  8647. * If the data is already present, it won t be added again
  8648. * @param value defines the object to push in the array.
  8649. * @returns true if added false if it was already present
  8650. */
  8651. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8652. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8653. return false;
  8654. }
  8655. this.push(value);
  8656. return true;
  8657. };
  8658. /**
  8659. * Resets the active data to an empty array.
  8660. */
  8661. SmartArrayNoDuplicate.prototype.reset = function () {
  8662. _super.prototype.reset.call(this);
  8663. this._duplicateId++;
  8664. };
  8665. /**
  8666. * Concats the active data with a given array.
  8667. * This ensures no dupplicate will be present in the result.
  8668. * @param array defines the data to concatenate with.
  8669. */
  8670. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8671. if (array.length === 0) {
  8672. return;
  8673. }
  8674. if (this.length + array.length > this.data.length) {
  8675. this.data.length = (this.length + array.length) * 2;
  8676. }
  8677. for (var index = 0; index < array.length; index++) {
  8678. var item = (array.data || array)[index];
  8679. this.pushNoDuplicate(item);
  8680. }
  8681. };
  8682. return SmartArrayNoDuplicate;
  8683. }(SmartArray));
  8684. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8685. })(BABYLON || (BABYLON = {}));
  8686. //# sourceMappingURL=babylon.smartArray.js.map
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. /** Class used to store color4 gradient */
  8690. var ColorGradient = /** @class */ (function () {
  8691. function ColorGradient() {
  8692. }
  8693. /**
  8694. * Will get a color picked randomly between color1 and color2.
  8695. * If color2 is undefined then color1 will be used
  8696. * @param result defines the target Color4 to store the result in
  8697. */
  8698. ColorGradient.prototype.getColorToRef = function (result) {
  8699. if (!this.color2) {
  8700. result.copyFrom(this.color1);
  8701. return;
  8702. }
  8703. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8704. };
  8705. return ColorGradient;
  8706. }());
  8707. BABYLON.ColorGradient = ColorGradient;
  8708. /** Class used to store color 3 gradient */
  8709. var Color3Gradient = /** @class */ (function () {
  8710. function Color3Gradient() {
  8711. }
  8712. return Color3Gradient;
  8713. }());
  8714. BABYLON.Color3Gradient = Color3Gradient;
  8715. /** Class used to store factor gradient */
  8716. var FactorGradient = /** @class */ (function () {
  8717. function FactorGradient() {
  8718. }
  8719. /**
  8720. * Will get a number picked randomly between factor1 and factor2.
  8721. * If factor2 is undefined then factor1 will be used
  8722. * @returns the picked number
  8723. */
  8724. FactorGradient.prototype.getFactor = function () {
  8725. if (this.factor2 === undefined) {
  8726. return this.factor1;
  8727. }
  8728. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8729. };
  8730. return FactorGradient;
  8731. }());
  8732. BABYLON.FactorGradient = FactorGradient;
  8733. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8734. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8735. var LoadFileError = /** @class */ (function (_super) {
  8736. __extends(LoadFileError, _super);
  8737. function LoadFileError(message, request) {
  8738. var _this = _super.call(this, message) || this;
  8739. _this.request = request;
  8740. _this.name = "LoadFileError";
  8741. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8742. return _this;
  8743. }
  8744. // Polyfill for Object.setPrototypeOf if necessary.
  8745. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8746. return LoadFileError;
  8747. }(Error));
  8748. BABYLON.LoadFileError = LoadFileError;
  8749. var RetryStrategy = /** @class */ (function () {
  8750. function RetryStrategy() {
  8751. }
  8752. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8753. if (maxRetries === void 0) { maxRetries = 3; }
  8754. if (baseInterval === void 0) { baseInterval = 500; }
  8755. return function (url, request, retryIndex) {
  8756. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8757. return -1;
  8758. }
  8759. return Math.pow(2, retryIndex) * baseInterval;
  8760. };
  8761. };
  8762. return RetryStrategy;
  8763. }());
  8764. BABYLON.RetryStrategy = RetryStrategy;
  8765. // Screenshots
  8766. var screenshotCanvas;
  8767. var cloneValue = function (source, destinationObject) {
  8768. if (!source)
  8769. return null;
  8770. if (source instanceof BABYLON.Mesh) {
  8771. return null;
  8772. }
  8773. if (source instanceof BABYLON.SubMesh) {
  8774. return source.clone(destinationObject);
  8775. }
  8776. else if (source.clone) {
  8777. return source.clone();
  8778. }
  8779. return null;
  8780. };
  8781. var Tools = /** @class */ (function () {
  8782. function Tools() {
  8783. }
  8784. /**
  8785. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8786. * @param u defines the coordinate on X axis
  8787. * @param v defines the coordinate on Y axis
  8788. * @param width defines the width of the source data
  8789. * @param height defines the height of the source data
  8790. * @param pixels defines the source byte array
  8791. * @param color defines the output color
  8792. */
  8793. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8794. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8795. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8796. var position = (wrappedU + wrappedV * width) * 4;
  8797. color.r = pixels[position] / 255;
  8798. color.g = pixels[position + 1] / 255;
  8799. color.b = pixels[position + 2] / 255;
  8800. color.a = pixels[position + 3] / 255;
  8801. };
  8802. /**
  8803. * Interpolates between a and b via alpha
  8804. * @param a The lower value (returned when alpha = 0)
  8805. * @param b The upper value (returned when alpha = 1)
  8806. * @param alpha The interpolation-factor
  8807. * @return The mixed value
  8808. */
  8809. Tools.Mix = function (a, b, alpha) {
  8810. return a * (1 - alpha) + b * alpha;
  8811. };
  8812. Tools.Instantiate = function (className) {
  8813. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8814. return Tools.RegisteredExternalClasses[className];
  8815. }
  8816. var arr = className.split(".");
  8817. var fn = (window || this);
  8818. for (var i = 0, len = arr.length; i < len; i++) {
  8819. fn = fn[arr[i]];
  8820. }
  8821. if (typeof fn !== "function") {
  8822. return null;
  8823. }
  8824. return fn;
  8825. };
  8826. /**
  8827. * Provides a slice function that will work even on IE
  8828. * @param data defines the array to slice
  8829. * @param start defines the start of the data (optional)
  8830. * @param end defines the end of the data (optional)
  8831. * @returns the new sliced array
  8832. */
  8833. Tools.Slice = function (data, start, end) {
  8834. if (data.slice) {
  8835. return data.slice(start, end);
  8836. }
  8837. return Array.prototype.slice.call(data, start, end);
  8838. };
  8839. Tools.SetImmediate = function (action) {
  8840. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8841. window.setImmediate(action);
  8842. }
  8843. else {
  8844. setTimeout(action, 1);
  8845. }
  8846. };
  8847. Tools.IsExponentOfTwo = function (value) {
  8848. var count = 1;
  8849. do {
  8850. count *= 2;
  8851. } while (count < value);
  8852. return count === value;
  8853. };
  8854. /**
  8855. * Returns the nearest 32-bit single precision float representation of a Number
  8856. * @param value A Number. If the parameter is of a different type, it will get converted
  8857. * to a number or to NaN if it cannot be converted
  8858. * @returns number
  8859. */
  8860. Tools.FloatRound = function (value) {
  8861. if (Math.fround) {
  8862. return Math.fround(value);
  8863. }
  8864. return (Tools._tmpFloatArray[0] = value);
  8865. };
  8866. /**
  8867. * Find the next highest power of two.
  8868. * @param x Number to start search from.
  8869. * @return Next highest power of two.
  8870. */
  8871. Tools.CeilingPOT = function (x) {
  8872. x--;
  8873. x |= x >> 1;
  8874. x |= x >> 2;
  8875. x |= x >> 4;
  8876. x |= x >> 8;
  8877. x |= x >> 16;
  8878. x++;
  8879. return x;
  8880. };
  8881. /**
  8882. * Find the next lowest power of two.
  8883. * @param x Number to start search from.
  8884. * @return Next lowest power of two.
  8885. */
  8886. Tools.FloorPOT = function (x) {
  8887. x = x | (x >> 1);
  8888. x = x | (x >> 2);
  8889. x = x | (x >> 4);
  8890. x = x | (x >> 8);
  8891. x = x | (x >> 16);
  8892. return x - (x >> 1);
  8893. };
  8894. /**
  8895. * Find the nearest power of two.
  8896. * @param x Number to start search from.
  8897. * @return Next nearest power of two.
  8898. */
  8899. Tools.NearestPOT = function (x) {
  8900. var c = Tools.CeilingPOT(x);
  8901. var f = Tools.FloorPOT(x);
  8902. return (c - x) > (x - f) ? f : c;
  8903. };
  8904. Tools.GetExponentOfTwo = function (value, max, mode) {
  8905. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8906. var pot;
  8907. switch (mode) {
  8908. case BABYLON.Engine.SCALEMODE_FLOOR:
  8909. pot = Tools.FloorPOT(value);
  8910. break;
  8911. case BABYLON.Engine.SCALEMODE_NEAREST:
  8912. pot = Tools.NearestPOT(value);
  8913. break;
  8914. case BABYLON.Engine.SCALEMODE_CEILING:
  8915. default:
  8916. pot = Tools.CeilingPOT(value);
  8917. break;
  8918. }
  8919. return Math.min(pot, max);
  8920. };
  8921. Tools.GetFilename = function (path) {
  8922. var index = path.lastIndexOf("/");
  8923. if (index < 0)
  8924. return path;
  8925. return path.substring(index + 1);
  8926. };
  8927. /**
  8928. * Extracts the "folder" part of a path (everything before the filename).
  8929. * @param uri The URI to extract the info from
  8930. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8931. * @returns The "folder" part of the path
  8932. */
  8933. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8934. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8935. var index = uri.lastIndexOf("/");
  8936. if (index < 0) {
  8937. if (returnUnchangedIfNoSlash) {
  8938. return uri;
  8939. }
  8940. return "";
  8941. }
  8942. return uri.substring(0, index + 1);
  8943. };
  8944. Tools.GetDOMTextContent = function (element) {
  8945. var result = "";
  8946. var child = element.firstChild;
  8947. while (child) {
  8948. if (child.nodeType === 3) {
  8949. result += child.textContent;
  8950. }
  8951. child = child.nextSibling;
  8952. }
  8953. return result;
  8954. };
  8955. Tools.ToDegrees = function (angle) {
  8956. return angle * 180 / Math.PI;
  8957. };
  8958. Tools.ToRadians = function (angle) {
  8959. return angle * Math.PI / 180;
  8960. };
  8961. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8962. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8963. var output = "";
  8964. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8965. var i = 0;
  8966. var bytes = new Uint8Array(buffer);
  8967. while (i < bytes.length) {
  8968. chr1 = bytes[i++];
  8969. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8970. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8971. enc1 = chr1 >> 2;
  8972. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8973. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8974. enc4 = chr3 & 63;
  8975. if (isNaN(chr2)) {
  8976. enc3 = enc4 = 64;
  8977. }
  8978. else if (isNaN(chr3)) {
  8979. enc4 = 64;
  8980. }
  8981. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8982. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8983. }
  8984. return "data:image/png;base64," + output;
  8985. };
  8986. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8987. if (bias === void 0) { bias = null; }
  8988. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8989. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8990. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8991. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8992. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8993. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8994. }
  8995. if (bias) {
  8996. minimum.x -= minimum.x * bias.x + bias.y;
  8997. minimum.y -= minimum.y * bias.x + bias.y;
  8998. minimum.z -= minimum.z * bias.x + bias.y;
  8999. maximum.x += maximum.x * bias.x + bias.y;
  9000. maximum.y += maximum.y * bias.x + bias.y;
  9001. maximum.z += maximum.z * bias.x + bias.y;
  9002. }
  9003. return {
  9004. minimum: minimum,
  9005. maximum: maximum
  9006. };
  9007. };
  9008. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9009. if (bias === void 0) { bias = null; }
  9010. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9011. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9012. if (!stride) {
  9013. stride = 3;
  9014. }
  9015. for (var index = start; index < start + count; index++) {
  9016. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9017. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9018. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9019. }
  9020. if (bias) {
  9021. minimum.x -= minimum.x * bias.x + bias.y;
  9022. minimum.y -= minimum.y * bias.x + bias.y;
  9023. minimum.z -= minimum.z * bias.x + bias.y;
  9024. maximum.x += maximum.x * bias.x + bias.y;
  9025. maximum.y += maximum.y * bias.x + bias.y;
  9026. maximum.z += maximum.z * bias.x + bias.y;
  9027. }
  9028. return {
  9029. minimum: minimum,
  9030. maximum: maximum
  9031. };
  9032. };
  9033. Tools.Vector2ArrayFeeder = function (array) {
  9034. return function (index) {
  9035. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9036. var length = isFloatArray ? array.length / 2 : array.length;
  9037. if (index >= length) {
  9038. return null;
  9039. }
  9040. if (isFloatArray) {
  9041. var fa = array;
  9042. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9043. }
  9044. var a = array;
  9045. return a[index];
  9046. };
  9047. };
  9048. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9049. if (bias === void 0) { bias = null; }
  9050. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9051. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9052. var i = 0;
  9053. var cur = feeder(i++);
  9054. while (cur) {
  9055. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9056. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9057. cur = feeder(i++);
  9058. }
  9059. if (bias) {
  9060. minimum.x -= minimum.x * bias.x + bias.y;
  9061. minimum.y -= minimum.y * bias.x + bias.y;
  9062. maximum.x += maximum.x * bias.x + bias.y;
  9063. maximum.y += maximum.y * bias.x + bias.y;
  9064. }
  9065. return {
  9066. minimum: minimum,
  9067. maximum: maximum
  9068. };
  9069. };
  9070. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9071. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9072. return null;
  9073. return Array.isArray(obj) ? obj : [obj];
  9074. };
  9075. // Misc.
  9076. Tools.GetPointerPrefix = function () {
  9077. var eventPrefix = "pointer";
  9078. // Check if pointer events are supported
  9079. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9080. eventPrefix = "mouse";
  9081. }
  9082. return eventPrefix;
  9083. };
  9084. /**
  9085. * @param func - the function to be called
  9086. * @param requester - the object that will request the next frame. Falls back to window.
  9087. */
  9088. Tools.QueueNewFrame = function (func, requester) {
  9089. if (!Tools.IsWindowObjectExist()) {
  9090. return setTimeout(func, 16);
  9091. }
  9092. if (!requester) {
  9093. requester = window;
  9094. }
  9095. if (requester.requestAnimationFrame) {
  9096. return requester.requestAnimationFrame(func);
  9097. }
  9098. else if (requester.msRequestAnimationFrame) {
  9099. return requester.msRequestAnimationFrame(func);
  9100. }
  9101. else if (requester.webkitRequestAnimationFrame) {
  9102. return requester.webkitRequestAnimationFrame(func);
  9103. }
  9104. else if (requester.mozRequestAnimationFrame) {
  9105. return requester.mozRequestAnimationFrame(func);
  9106. }
  9107. else if (requester.oRequestAnimationFrame) {
  9108. return requester.oRequestAnimationFrame(func);
  9109. }
  9110. else {
  9111. return window.setTimeout(func, 16);
  9112. }
  9113. };
  9114. Tools.RequestFullscreen = function (element) {
  9115. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9116. if (!requestFunction)
  9117. return;
  9118. requestFunction.call(element);
  9119. };
  9120. Tools.ExitFullscreen = function () {
  9121. if (document.exitFullscreen) {
  9122. document.exitFullscreen();
  9123. }
  9124. else if (document.mozCancelFullScreen) {
  9125. document.mozCancelFullScreen();
  9126. }
  9127. else if (document.webkitCancelFullScreen) {
  9128. document.webkitCancelFullScreen();
  9129. }
  9130. else if (document.msCancelFullScreen) {
  9131. document.msCancelFullScreen();
  9132. }
  9133. };
  9134. Tools.SetCorsBehavior = function (url, element) {
  9135. if (url && url.indexOf("data:") === 0) {
  9136. return;
  9137. }
  9138. if (Tools.CorsBehavior) {
  9139. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9140. element.crossOrigin = Tools.CorsBehavior;
  9141. }
  9142. else {
  9143. var result = Tools.CorsBehavior(url);
  9144. if (result) {
  9145. element.crossOrigin = result;
  9146. }
  9147. }
  9148. }
  9149. };
  9150. // External files
  9151. Tools.CleanUrl = function (url) {
  9152. url = url.replace(/#/mg, "%23");
  9153. return url;
  9154. };
  9155. /**
  9156. * Loads an image as an HTMLImageElement.
  9157. * @param input url string, ArrayBuffer, or Blob to load
  9158. * @param onLoad callback called when the image successfully loads
  9159. * @param onError callback called when the image fails to load
  9160. * @param database database for caching
  9161. * @returns the HTMLImageElement of the loaded image
  9162. */
  9163. Tools.LoadImage = function (input, onLoad, onError, database) {
  9164. var url;
  9165. var usingObjectURL = false;
  9166. if (input instanceof ArrayBuffer) {
  9167. url = URL.createObjectURL(new Blob([input]));
  9168. usingObjectURL = true;
  9169. }
  9170. else if (input instanceof Blob) {
  9171. url = URL.createObjectURL(input);
  9172. usingObjectURL = true;
  9173. }
  9174. else {
  9175. url = Tools.CleanUrl(input);
  9176. url = Tools.PreprocessUrl(input);
  9177. }
  9178. var img = new Image();
  9179. Tools.SetCorsBehavior(url, img);
  9180. var loadHandler = function () {
  9181. if (usingObjectURL && img.src) {
  9182. URL.revokeObjectURL(img.src);
  9183. }
  9184. img.removeEventListener("load", loadHandler);
  9185. img.removeEventListener("error", errorHandler);
  9186. onLoad(img);
  9187. };
  9188. var errorHandler = function (err) {
  9189. if (usingObjectURL && img.src) {
  9190. URL.revokeObjectURL(img.src);
  9191. }
  9192. img.removeEventListener("load", loadHandler);
  9193. img.removeEventListener("error", errorHandler);
  9194. Tools.Error("Error while trying to load image: " + input);
  9195. if (onError) {
  9196. onError("Error while trying to load image: " + input, err);
  9197. }
  9198. };
  9199. img.addEventListener("load", loadHandler);
  9200. img.addEventListener("error", errorHandler);
  9201. var noIndexedDB = function () {
  9202. img.src = url;
  9203. };
  9204. var loadFromIndexedDB = function () {
  9205. if (database) {
  9206. database.loadImageFromDB(url, img);
  9207. }
  9208. };
  9209. //ANY database to do!
  9210. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9211. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9212. }
  9213. else {
  9214. if (url.indexOf("file:") !== -1) {
  9215. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9216. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9217. try {
  9218. var blobURL;
  9219. try {
  9220. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9221. }
  9222. catch (ex) {
  9223. // Chrome doesn't support oneTimeOnly parameter
  9224. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9225. }
  9226. img.src = blobURL;
  9227. usingObjectURL = true;
  9228. }
  9229. catch (e) {
  9230. img.src = "";
  9231. }
  9232. return img;
  9233. }
  9234. }
  9235. noIndexedDB();
  9236. }
  9237. return img;
  9238. };
  9239. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9240. url = Tools.CleanUrl(url);
  9241. url = Tools.PreprocessUrl(url);
  9242. // If file and file input are set
  9243. if (url.indexOf("file:") !== -1) {
  9244. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9245. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9246. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9247. }
  9248. }
  9249. var loadUrl = Tools.BaseUrl + url;
  9250. var aborted = false;
  9251. var fileRequest = {
  9252. onCompleteObservable: new BABYLON.Observable(),
  9253. abort: function () { return aborted = true; },
  9254. };
  9255. var requestFile = function () {
  9256. var request = new XMLHttpRequest();
  9257. var retryHandle = null;
  9258. fileRequest.abort = function () {
  9259. aborted = true;
  9260. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9261. request.abort();
  9262. }
  9263. if (retryHandle !== null) {
  9264. clearTimeout(retryHandle);
  9265. retryHandle = null;
  9266. }
  9267. };
  9268. var retryLoop = function (retryIndex) {
  9269. request.open('GET', loadUrl, true);
  9270. if (useArrayBuffer) {
  9271. request.responseType = "arraybuffer";
  9272. }
  9273. if (onProgress) {
  9274. request.addEventListener("progress", onProgress);
  9275. }
  9276. var onLoadEnd = function () {
  9277. request.removeEventListener("loadend", onLoadEnd);
  9278. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9279. fileRequest.onCompleteObservable.clear();
  9280. };
  9281. request.addEventListener("loadend", onLoadEnd);
  9282. var onReadyStateChange = function () {
  9283. if (aborted) {
  9284. return;
  9285. }
  9286. // In case of undefined state in some browsers.
  9287. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9288. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9289. request.removeEventListener("readystatechange", onReadyStateChange);
  9290. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9291. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9292. return;
  9293. }
  9294. var retryStrategy = Tools.DefaultRetryStrategy;
  9295. if (retryStrategy) {
  9296. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9297. if (waitTime !== -1) {
  9298. // Prevent the request from completing for retry.
  9299. request.removeEventListener("loadend", onLoadEnd);
  9300. request = new XMLHttpRequest();
  9301. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9302. return;
  9303. }
  9304. }
  9305. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9306. if (onError) {
  9307. onError(request, e);
  9308. }
  9309. else {
  9310. throw e;
  9311. }
  9312. }
  9313. };
  9314. request.addEventListener("readystatechange", onReadyStateChange);
  9315. request.send();
  9316. };
  9317. retryLoop(0);
  9318. };
  9319. // Caching all files
  9320. if (database && database.enableSceneOffline) {
  9321. var noIndexedDB_1 = function (request) {
  9322. if (request && request.status > 400) {
  9323. if (onError) {
  9324. onError(request);
  9325. }
  9326. }
  9327. else {
  9328. if (!aborted) {
  9329. requestFile();
  9330. }
  9331. }
  9332. };
  9333. var loadFromIndexedDB = function () {
  9334. // TODO: database needs to support aborting and should return a IFileRequest
  9335. if (aborted) {
  9336. return;
  9337. }
  9338. if (database) {
  9339. database.loadFileFromDB(url, function (data) {
  9340. if (!aborted) {
  9341. onSuccess(data);
  9342. }
  9343. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9344. }, onProgress ? function (event) {
  9345. if (!aborted) {
  9346. onProgress(event);
  9347. }
  9348. } : undefined, noIndexedDB_1, useArrayBuffer);
  9349. }
  9350. };
  9351. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9352. }
  9353. else {
  9354. requestFile();
  9355. }
  9356. return fileRequest;
  9357. };
  9358. /**
  9359. * Load a script (identified by an url). When the url returns, the
  9360. * content of this file is added into a new script element, attached to the DOM (body element)
  9361. */
  9362. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9363. if (!Tools.IsWindowObjectExist()) {
  9364. return;
  9365. }
  9366. var head = document.getElementsByTagName('head')[0];
  9367. var script = document.createElement('script');
  9368. script.type = 'text/javascript';
  9369. script.src = scriptUrl;
  9370. script.onload = function () {
  9371. if (onSuccess) {
  9372. onSuccess();
  9373. }
  9374. };
  9375. script.onerror = function (e) {
  9376. if (onError) {
  9377. onError("Unable to load script '" + scriptUrl + "'", e);
  9378. }
  9379. };
  9380. head.appendChild(script);
  9381. };
  9382. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9383. var reader = new FileReader();
  9384. var request = {
  9385. onCompleteObservable: new BABYLON.Observable(),
  9386. abort: function () { return reader.abort(); },
  9387. };
  9388. reader.onloadend = function (e) {
  9389. request.onCompleteObservable.notifyObservers(request);
  9390. };
  9391. reader.onload = function (e) {
  9392. //target doesn't have result from ts 1.3
  9393. callback(e.target['result']);
  9394. };
  9395. reader.onprogress = progressCallback;
  9396. reader.readAsDataURL(fileToLoad);
  9397. return request;
  9398. };
  9399. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9400. var reader = new FileReader();
  9401. var request = {
  9402. onCompleteObservable: new BABYLON.Observable(),
  9403. abort: function () { return reader.abort(); },
  9404. };
  9405. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9406. reader.onerror = function (e) {
  9407. Tools.Log("Error while reading file: " + fileToLoad.name);
  9408. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9409. };
  9410. reader.onload = function (e) {
  9411. //target doesn't have result from ts 1.3
  9412. callback(e.target['result']);
  9413. };
  9414. if (progressCallBack) {
  9415. reader.onprogress = progressCallBack;
  9416. }
  9417. if (!useArrayBuffer) {
  9418. // Asynchronous read
  9419. reader.readAsText(fileToLoad);
  9420. }
  9421. else {
  9422. reader.readAsArrayBuffer(fileToLoad);
  9423. }
  9424. return request;
  9425. };
  9426. //returns a downloadable url to a file content.
  9427. Tools.FileAsURL = function (content) {
  9428. var fileBlob = new Blob([content]);
  9429. var url = window.URL || window.webkitURL;
  9430. var link = url.createObjectURL(fileBlob);
  9431. return link;
  9432. };
  9433. // Misc.
  9434. Tools.Format = function (value, decimals) {
  9435. if (decimals === void 0) { decimals = 2; }
  9436. return value.toFixed(decimals);
  9437. };
  9438. Tools.CheckExtends = function (v, min, max) {
  9439. if (v.x < min.x)
  9440. min.x = v.x;
  9441. if (v.y < min.y)
  9442. min.y = v.y;
  9443. if (v.z < min.z)
  9444. min.z = v.z;
  9445. if (v.x > max.x)
  9446. max.x = v.x;
  9447. if (v.y > max.y)
  9448. max.y = v.y;
  9449. if (v.z > max.z)
  9450. max.z = v.z;
  9451. };
  9452. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9453. for (var prop in source) {
  9454. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9455. continue;
  9456. }
  9457. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9458. continue;
  9459. }
  9460. var sourceValue = source[prop];
  9461. var typeOfSourceValue = typeof sourceValue;
  9462. if (typeOfSourceValue === "function") {
  9463. continue;
  9464. }
  9465. try {
  9466. if (typeOfSourceValue === "object") {
  9467. if (sourceValue instanceof Array) {
  9468. destination[prop] = [];
  9469. if (sourceValue.length > 0) {
  9470. if (typeof sourceValue[0] == "object") {
  9471. for (var index = 0; index < sourceValue.length; index++) {
  9472. var clonedValue = cloneValue(sourceValue[index], destination);
  9473. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9474. destination[prop].push(clonedValue);
  9475. }
  9476. }
  9477. }
  9478. else {
  9479. destination[prop] = sourceValue.slice(0);
  9480. }
  9481. }
  9482. }
  9483. else {
  9484. destination[prop] = cloneValue(sourceValue, destination);
  9485. }
  9486. }
  9487. else {
  9488. destination[prop] = sourceValue;
  9489. }
  9490. }
  9491. catch (e) {
  9492. // Just ignore error (it could be because of a read-only property)
  9493. }
  9494. }
  9495. };
  9496. Tools.IsEmpty = function (obj) {
  9497. for (var i in obj) {
  9498. if (obj.hasOwnProperty(i)) {
  9499. return false;
  9500. }
  9501. }
  9502. return true;
  9503. };
  9504. Tools.RegisterTopRootEvents = function (events) {
  9505. for (var index = 0; index < events.length; index++) {
  9506. var event = events[index];
  9507. window.addEventListener(event.name, event.handler, false);
  9508. try {
  9509. if (window.parent) {
  9510. window.parent.addEventListener(event.name, event.handler, false);
  9511. }
  9512. }
  9513. catch (e) {
  9514. // Silently fails...
  9515. }
  9516. }
  9517. };
  9518. Tools.UnregisterTopRootEvents = function (events) {
  9519. for (var index = 0; index < events.length; index++) {
  9520. var event = events[index];
  9521. window.removeEventListener(event.name, event.handler);
  9522. try {
  9523. if (window.parent) {
  9524. window.parent.removeEventListener(event.name, event.handler);
  9525. }
  9526. }
  9527. catch (e) {
  9528. // Silently fails...
  9529. }
  9530. }
  9531. };
  9532. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9533. if (mimeType === void 0) { mimeType = "image/png"; }
  9534. // Read the contents of the framebuffer
  9535. var numberOfChannelsByLine = width * 4;
  9536. var halfHeight = height / 2;
  9537. //Reading datas from WebGL
  9538. var data = engine.readPixels(0, 0, width, height);
  9539. //To flip image on Y axis.
  9540. for (var i = 0; i < halfHeight; i++) {
  9541. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9542. var currentCell = j + i * numberOfChannelsByLine;
  9543. var targetLine = height - i - 1;
  9544. var targetCell = j + targetLine * numberOfChannelsByLine;
  9545. var temp = data[currentCell];
  9546. data[currentCell] = data[targetCell];
  9547. data[targetCell] = temp;
  9548. }
  9549. }
  9550. // Create a 2D canvas to store the result
  9551. if (!screenshotCanvas) {
  9552. screenshotCanvas = document.createElement('canvas');
  9553. }
  9554. screenshotCanvas.width = width;
  9555. screenshotCanvas.height = height;
  9556. var context = screenshotCanvas.getContext('2d');
  9557. if (context) {
  9558. // Copy the pixels to a 2D canvas
  9559. var imageData = context.createImageData(width, height);
  9560. var castData = (imageData.data);
  9561. castData.set(data);
  9562. context.putImageData(imageData, 0, 0);
  9563. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9564. }
  9565. };
  9566. /**
  9567. * Converts the canvas data to blob.
  9568. * This acts as a polyfill for browsers not supporting the to blob function.
  9569. * @param canvas Defines the canvas to extract the data from
  9570. * @param successCallback Defines the callback triggered once the data are available
  9571. * @param mimeType Defines the mime type of the result
  9572. */
  9573. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9574. if (mimeType === void 0) { mimeType = "image/png"; }
  9575. // We need HTMLCanvasElement.toBlob for HD screenshots
  9576. if (!canvas.toBlob) {
  9577. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9578. canvas.toBlob = function (callback, type, quality) {
  9579. var _this = this;
  9580. setTimeout(function () {
  9581. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9582. for (var i = 0; i < len; i++) {
  9583. arr[i] = binStr.charCodeAt(i);
  9584. }
  9585. callback(new Blob([arr]));
  9586. });
  9587. };
  9588. }
  9589. canvas.toBlob(function (blob) {
  9590. successCallback(blob);
  9591. }, mimeType);
  9592. };
  9593. /**
  9594. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9595. * @param successCallback Defines the callback triggered once the data are available
  9596. * @param mimeType Defines the mime type of the result
  9597. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9598. */
  9599. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9600. if (mimeType === void 0) { mimeType = "image/png"; }
  9601. if (successCallback) {
  9602. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9603. successCallback(base64Image);
  9604. }
  9605. else {
  9606. this.ToBlob(screenshotCanvas, function (blob) {
  9607. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9608. if (("download" in document.createElement("a"))) {
  9609. if (!fileName) {
  9610. var date = new Date();
  9611. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9612. fileName = "screenshot_" + stringDate + ".png";
  9613. }
  9614. Tools.Download(blob, fileName);
  9615. }
  9616. else {
  9617. var url = URL.createObjectURL(blob);
  9618. var newWindow = window.open("");
  9619. if (!newWindow)
  9620. return;
  9621. var img = newWindow.document.createElement("img");
  9622. img.onload = function () {
  9623. // no longer need to read the blob so it's revoked
  9624. URL.revokeObjectURL(url);
  9625. };
  9626. img.src = url;
  9627. newWindow.document.body.appendChild(img);
  9628. }
  9629. }, mimeType);
  9630. }
  9631. };
  9632. /**
  9633. * Downloads a blob in the browser
  9634. * @param blob defines the blob to download
  9635. * @param fileName defines the name of the downloaded file
  9636. */
  9637. Tools.Download = function (blob, fileName) {
  9638. if (navigator && navigator.msSaveBlob) {
  9639. navigator.msSaveBlob(blob, fileName);
  9640. return;
  9641. }
  9642. var url = window.URL.createObjectURL(blob);
  9643. var a = document.createElement("a");
  9644. document.body.appendChild(a);
  9645. a.style.display = "none";
  9646. a.href = url;
  9647. a.download = fileName;
  9648. a.addEventListener("click", function () {
  9649. if (a.parentElement) {
  9650. a.parentElement.removeChild(a);
  9651. }
  9652. });
  9653. a.click();
  9654. window.URL.revokeObjectURL(url);
  9655. };
  9656. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9657. if (mimeType === void 0) { mimeType = "image/png"; }
  9658. var width;
  9659. var height;
  9660. // If a precision value is specified
  9661. if (size.precision) {
  9662. width = Math.round(engine.getRenderWidth() * size.precision);
  9663. height = Math.round(width / engine.getAspectRatio(camera));
  9664. }
  9665. else if (size.width && size.height) {
  9666. width = size.width;
  9667. height = size.height;
  9668. }
  9669. //If passing only width, computing height to keep display canvas ratio.
  9670. else if (size.width && !size.height) {
  9671. width = size.width;
  9672. height = Math.round(width / engine.getAspectRatio(camera));
  9673. }
  9674. //If passing only height, computing width to keep display canvas ratio.
  9675. else if (size.height && !size.width) {
  9676. height = size.height;
  9677. width = Math.round(height * engine.getAspectRatio(camera));
  9678. }
  9679. //Assuming here that "size" parameter is a number
  9680. else if (!isNaN(size)) {
  9681. height = size;
  9682. width = size;
  9683. }
  9684. else {
  9685. Tools.Error("Invalid 'size' parameter !");
  9686. return;
  9687. }
  9688. if (!screenshotCanvas) {
  9689. screenshotCanvas = document.createElement('canvas');
  9690. }
  9691. screenshotCanvas.width = width;
  9692. screenshotCanvas.height = height;
  9693. var renderContext = screenshotCanvas.getContext("2d");
  9694. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9695. var newWidth = width;
  9696. var newHeight = newWidth / ratio;
  9697. if (newHeight > height) {
  9698. newHeight = height;
  9699. newWidth = newHeight * ratio;
  9700. }
  9701. var offsetX = Math.max(0, width - newWidth) / 2;
  9702. var offsetY = Math.max(0, height - newHeight) / 2;
  9703. var renderingCanvas = engine.getRenderingCanvas();
  9704. if (renderContext && renderingCanvas) {
  9705. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9706. }
  9707. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9708. };
  9709. /**
  9710. * Generates an image screenshot from the specified camera.
  9711. *
  9712. * @param engine The engine to use for rendering
  9713. * @param camera The camera to use for rendering
  9714. * @param size This parameter can be set to a single number or to an object with the
  9715. * following (optional) properties: precision, width, height. If a single number is passed,
  9716. * it will be used for both width and height. If an object is passed, the screenshot size
  9717. * will be derived from the parameters. The precision property is a multiplier allowing
  9718. * rendering at a higher or lower resolution.
  9719. * @param successCallback The callback receives a single parameter which contains the
  9720. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9721. * src parameter of an <img> to display it.
  9722. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9723. * Check your browser for supported MIME types.
  9724. * @param samples Texture samples (default: 1)
  9725. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9726. * @param fileName A name for for the downloaded file.
  9727. * @constructor
  9728. */
  9729. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9730. if (mimeType === void 0) { mimeType = "image/png"; }
  9731. if (samples === void 0) { samples = 1; }
  9732. if (antialiasing === void 0) { antialiasing = false; }
  9733. var width;
  9734. var height;
  9735. //If a precision value is specified
  9736. if (size.precision) {
  9737. width = Math.round(engine.getRenderWidth() * size.precision);
  9738. height = Math.round(width / engine.getAspectRatio(camera));
  9739. size = { width: width, height: height };
  9740. }
  9741. else if (size.width && size.height) {
  9742. width = size.width;
  9743. height = size.height;
  9744. }
  9745. //If passing only width, computing height to keep display canvas ratio.
  9746. else if (size.width && !size.height) {
  9747. width = size.width;
  9748. height = Math.round(width / engine.getAspectRatio(camera));
  9749. size = { width: width, height: height };
  9750. }
  9751. //If passing only height, computing width to keep display canvas ratio.
  9752. else if (size.height && !size.width) {
  9753. height = size.height;
  9754. width = Math.round(height * engine.getAspectRatio(camera));
  9755. size = { width: width, height: height };
  9756. }
  9757. //Assuming here that "size" parameter is a number
  9758. else if (!isNaN(size)) {
  9759. height = size;
  9760. width = size;
  9761. }
  9762. else {
  9763. Tools.Error("Invalid 'size' parameter !");
  9764. return;
  9765. }
  9766. var scene = camera.getScene();
  9767. var previousCamera = null;
  9768. if (scene.activeCamera !== camera) {
  9769. previousCamera = scene.activeCamera;
  9770. scene.activeCamera = camera;
  9771. }
  9772. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9773. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9774. texture.renderList = null;
  9775. texture.samples = samples;
  9776. if (antialiasing) {
  9777. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9778. }
  9779. texture.onAfterRenderObservable.add(function () {
  9780. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9781. });
  9782. scene.incrementRenderId();
  9783. scene.resetCachedMaterial();
  9784. texture.render(true);
  9785. texture.dispose();
  9786. if (previousCamera) {
  9787. scene.activeCamera = previousCamera;
  9788. }
  9789. camera.getProjectionMatrix(true); // Force cache refresh;
  9790. };
  9791. // XHR response validator for local file scenario
  9792. Tools.ValidateXHRData = function (xhr, dataType) {
  9793. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9794. if (dataType === void 0) { dataType = 7; }
  9795. try {
  9796. if (dataType & 1) {
  9797. if (xhr.responseText && xhr.responseText.length > 0) {
  9798. return true;
  9799. }
  9800. else if (dataType === 1) {
  9801. return false;
  9802. }
  9803. }
  9804. if (dataType & 2) {
  9805. // Check header width and height since there is no "TGA" magic number
  9806. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9807. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9808. return true;
  9809. }
  9810. else if (dataType === 2) {
  9811. return false;
  9812. }
  9813. }
  9814. if (dataType & 4) {
  9815. // Check for the "DDS" magic number
  9816. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9817. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9818. return true;
  9819. }
  9820. else {
  9821. return false;
  9822. }
  9823. }
  9824. }
  9825. catch (e) {
  9826. // Global protection
  9827. }
  9828. return false;
  9829. };
  9830. /**
  9831. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9832. * Be aware Math.random() could cause collisions, but:
  9833. * "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"
  9834. */
  9835. Tools.RandomId = function () {
  9836. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9837. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9838. return v.toString(16);
  9839. });
  9840. };
  9841. /**
  9842. * Test if the given uri is a base64 string.
  9843. * @param uri The uri to test
  9844. * @return True if the uri is a base64 string or false otherwise.
  9845. */
  9846. Tools.IsBase64 = function (uri) {
  9847. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9848. };
  9849. /**
  9850. * Decode the given base64 uri.
  9851. * @param uri The uri to decode
  9852. * @return The decoded base64 data.
  9853. */
  9854. Tools.DecodeBase64 = function (uri) {
  9855. var decodedString = atob(uri.split(",")[1]);
  9856. var bufferLength = decodedString.length;
  9857. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9858. for (var i = 0; i < bufferLength; i++) {
  9859. bufferView[i] = decodedString.charCodeAt(i);
  9860. }
  9861. return bufferView.buffer;
  9862. };
  9863. Object.defineProperty(Tools, "NoneLogLevel", {
  9864. get: function () {
  9865. return Tools._NoneLogLevel;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(Tools, "MessageLogLevel", {
  9871. get: function () {
  9872. return Tools._MessageLogLevel;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Tools, "WarningLogLevel", {
  9878. get: function () {
  9879. return Tools._WarningLogLevel;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Tools, "ErrorLogLevel", {
  9885. get: function () {
  9886. return Tools._ErrorLogLevel;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Tools, "AllLogLevel", {
  9892. get: function () {
  9893. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Tools._AddLogEntry = function (entry) {
  9899. Tools._LogCache = entry + Tools._LogCache;
  9900. if (Tools.OnNewCacheEntry) {
  9901. Tools.OnNewCacheEntry(entry);
  9902. }
  9903. };
  9904. Tools._FormatMessage = function (message) {
  9905. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9906. var date = new Date();
  9907. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9908. };
  9909. Tools._LogDisabled = function (message) {
  9910. // nothing to do
  9911. };
  9912. Tools._LogEnabled = function (message) {
  9913. var formattedMessage = Tools._FormatMessage(message);
  9914. console.log("BJS - " + formattedMessage);
  9915. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9916. Tools._AddLogEntry(entry);
  9917. };
  9918. Tools._WarnDisabled = function (message) {
  9919. // nothing to do
  9920. };
  9921. Tools._WarnEnabled = function (message) {
  9922. var formattedMessage = Tools._FormatMessage(message);
  9923. console.warn("BJS - " + formattedMessage);
  9924. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9925. Tools._AddLogEntry(entry);
  9926. };
  9927. Tools._ErrorDisabled = function (message) {
  9928. // nothing to do
  9929. };
  9930. Tools._ErrorEnabled = function (message) {
  9931. Tools.errorsCount++;
  9932. var formattedMessage = Tools._FormatMessage(message);
  9933. console.error("BJS - " + formattedMessage);
  9934. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9935. Tools._AddLogEntry(entry);
  9936. };
  9937. Object.defineProperty(Tools, "LogCache", {
  9938. get: function () {
  9939. return Tools._LogCache;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Tools.ClearLogCache = function () {
  9945. Tools._LogCache = "";
  9946. Tools.errorsCount = 0;
  9947. };
  9948. Object.defineProperty(Tools, "LogLevels", {
  9949. set: function (level) {
  9950. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9951. Tools.Log = Tools._LogEnabled;
  9952. }
  9953. else {
  9954. Tools.Log = Tools._LogDisabled;
  9955. }
  9956. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9957. Tools.Warn = Tools._WarnEnabled;
  9958. }
  9959. else {
  9960. Tools.Warn = Tools._WarnDisabled;
  9961. }
  9962. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9963. Tools.Error = Tools._ErrorEnabled;
  9964. }
  9965. else {
  9966. Tools.Error = Tools._ErrorDisabled;
  9967. }
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. /**
  9973. * Check if the loaded document was accessed via `file:`-Protocol.
  9974. * @returns boolean
  9975. */
  9976. Tools.IsFileURL = function () {
  9977. return location.protocol === "file:";
  9978. };
  9979. Tools.IsWindowObjectExist = function () {
  9980. return (typeof window) !== "undefined";
  9981. };
  9982. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9983. get: function () {
  9984. return Tools._PerformanceNoneLogLevel;
  9985. },
  9986. enumerable: true,
  9987. configurable: true
  9988. });
  9989. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9990. get: function () {
  9991. return Tools._PerformanceUserMarkLogLevel;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9997. get: function () {
  9998. return Tools._PerformanceConsoleLogLevel;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10004. set: function (level) {
  10005. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10006. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10007. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10008. return;
  10009. }
  10010. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10011. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10012. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10013. return;
  10014. }
  10015. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10016. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10017. },
  10018. enumerable: true,
  10019. configurable: true
  10020. });
  10021. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10022. };
  10023. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10024. };
  10025. Tools._StartUserMark = function (counterName, condition) {
  10026. if (condition === void 0) { condition = true; }
  10027. if (!Tools._performance) {
  10028. if (!Tools.IsWindowObjectExist()) {
  10029. return;
  10030. }
  10031. Tools._performance = window.performance;
  10032. }
  10033. if (!condition || !Tools._performance.mark) {
  10034. return;
  10035. }
  10036. Tools._performance.mark(counterName + "-Begin");
  10037. };
  10038. Tools._EndUserMark = function (counterName, condition) {
  10039. if (condition === void 0) { condition = true; }
  10040. if (!condition || !Tools._performance.mark) {
  10041. return;
  10042. }
  10043. Tools._performance.mark(counterName + "-End");
  10044. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10045. };
  10046. Tools._StartPerformanceConsole = function (counterName, condition) {
  10047. if (condition === void 0) { condition = true; }
  10048. if (!condition) {
  10049. return;
  10050. }
  10051. Tools._StartUserMark(counterName, condition);
  10052. if (console.time) {
  10053. console.time(counterName);
  10054. }
  10055. };
  10056. Tools._EndPerformanceConsole = function (counterName, condition) {
  10057. if (condition === void 0) { condition = true; }
  10058. if (!condition) {
  10059. return;
  10060. }
  10061. Tools._EndUserMark(counterName, condition);
  10062. if (console.time) {
  10063. console.timeEnd(counterName);
  10064. }
  10065. };
  10066. Object.defineProperty(Tools, "Now", {
  10067. get: function () {
  10068. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10069. return window.performance.now();
  10070. }
  10071. return Date.now();
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. /**
  10077. * This method will return the name of the class used to create the instance of the given object.
  10078. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10079. * @param object the object to get the class name from
  10080. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10081. */
  10082. Tools.GetClassName = function (object, isType) {
  10083. if (isType === void 0) { isType = false; }
  10084. var name = null;
  10085. if (!isType && object.getClassName) {
  10086. name = object.getClassName();
  10087. }
  10088. else {
  10089. if (object instanceof Object) {
  10090. var classObj = isType ? object : Object.getPrototypeOf(object);
  10091. name = classObj.constructor["__bjsclassName__"];
  10092. }
  10093. if (!name) {
  10094. name = typeof object;
  10095. }
  10096. }
  10097. return name;
  10098. };
  10099. Tools.First = function (array, predicate) {
  10100. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10101. var el = array_1[_i];
  10102. if (predicate(el)) {
  10103. return el;
  10104. }
  10105. }
  10106. return null;
  10107. };
  10108. /**
  10109. * This method will return the name of the full name of the class, including its owning module (if any).
  10110. * 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).
  10111. * @param object the object to get the class name from
  10112. * @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.
  10113. */
  10114. Tools.getFullClassName = function (object, isType) {
  10115. if (isType === void 0) { isType = false; }
  10116. var className = null;
  10117. var moduleName = null;
  10118. if (!isType && object.getClassName) {
  10119. className = object.getClassName();
  10120. }
  10121. else {
  10122. if (object instanceof Object) {
  10123. var classObj = isType ? object : Object.getPrototypeOf(object);
  10124. className = classObj.constructor["__bjsclassName__"];
  10125. moduleName = classObj.constructor["__bjsmoduleName__"];
  10126. }
  10127. if (!className) {
  10128. className = typeof object;
  10129. }
  10130. }
  10131. if (!className) {
  10132. return null;
  10133. }
  10134. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10135. };
  10136. /**
  10137. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10138. * @param array
  10139. */
  10140. Tools.arrayOrStringFeeder = function (array) {
  10141. return function (index) {
  10142. if (index >= array.length) {
  10143. return null;
  10144. }
  10145. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10146. if (val && val.getHashCode) {
  10147. val = val.getHashCode();
  10148. }
  10149. if (typeof val === "string") {
  10150. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10151. }
  10152. return val;
  10153. };
  10154. };
  10155. /**
  10156. * Compute the hashCode of a stream of number
  10157. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10158. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10159. * @return the hash code computed
  10160. */
  10161. Tools.hashCodeFromStream = function (feeder) {
  10162. // Based from here: http://stackoverflow.com/a/7616484/802124
  10163. var hash = 0;
  10164. var index = 0;
  10165. var chr = feeder(index++);
  10166. while (chr != null) {
  10167. hash = ((hash << 5) - hash) + chr;
  10168. hash |= 0; // Convert to 32bit integer
  10169. chr = feeder(index++);
  10170. }
  10171. return hash;
  10172. };
  10173. /**
  10174. * Returns a promise that resolves after the given amount of time.
  10175. * @param delay Number of milliseconds to delay
  10176. * @returns Promise that resolves after the given amount of time
  10177. */
  10178. Tools.DelayAsync = function (delay) {
  10179. return new Promise(function (resolve) {
  10180. setTimeout(function () {
  10181. resolve();
  10182. }, delay);
  10183. });
  10184. };
  10185. /**
  10186. * Gets the current gradient from an array of IValueGradient
  10187. * @param ratio defines the current ratio to get
  10188. * @param gradients defines the array of IValueGradient
  10189. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10190. */
  10191. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10192. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10193. var currentGradient = gradients[gradientIndex];
  10194. var nextGradient = gradients[gradientIndex + 1];
  10195. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10196. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10197. updateFunc(currentGradient, nextGradient, scale);
  10198. return;
  10199. }
  10200. }
  10201. // Use last index if over
  10202. var lastIndex = gradients.length - 1;
  10203. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10204. };
  10205. Tools.BaseUrl = "";
  10206. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10207. /**
  10208. * Default behaviour for cors in the application.
  10209. * It can be a string if the expected behavior is identical in the entire app.
  10210. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10211. */
  10212. Tools.CorsBehavior = "anonymous";
  10213. Tools.UseFallbackTexture = true;
  10214. /**
  10215. * Use this object to register external classes like custom textures or material
  10216. * to allow the laoders to instantiate them
  10217. */
  10218. Tools.RegisteredExternalClasses = {};
  10219. // Used in case of a texture loading problem
  10220. 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";
  10221. Tools._tmpFloatArray = new Float32Array(1);
  10222. Tools.PreprocessUrl = function (url) {
  10223. return url;
  10224. };
  10225. // Logs
  10226. Tools._NoneLogLevel = 0;
  10227. Tools._MessageLogLevel = 1;
  10228. Tools._WarningLogLevel = 2;
  10229. Tools._ErrorLogLevel = 4;
  10230. Tools._LogCache = "";
  10231. Tools.errorsCount = 0;
  10232. Tools.Log = Tools._LogEnabled;
  10233. Tools.Warn = Tools._WarnEnabled;
  10234. Tools.Error = Tools._ErrorEnabled;
  10235. // Performances
  10236. Tools._PerformanceNoneLogLevel = 0;
  10237. Tools._PerformanceUserMarkLogLevel = 1;
  10238. Tools._PerformanceConsoleLogLevel = 2;
  10239. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10240. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10241. return Tools;
  10242. }());
  10243. BABYLON.Tools = Tools;
  10244. /**
  10245. * This class is used to track a performance counter which is number based.
  10246. * The user has access to many properties which give statistics of different nature
  10247. *
  10248. * The implementer can track two kinds of Performance Counter: time and count
  10249. * 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.
  10250. * 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.
  10251. */
  10252. var PerfCounter = /** @class */ (function () {
  10253. function PerfCounter() {
  10254. this._startMonitoringTime = 0;
  10255. this._min = 0;
  10256. this._max = 0;
  10257. this._average = 0;
  10258. this._lastSecAverage = 0;
  10259. this._current = 0;
  10260. this._totalValueCount = 0;
  10261. this._totalAccumulated = 0;
  10262. this._lastSecAccumulated = 0;
  10263. this._lastSecTime = 0;
  10264. this._lastSecValueCount = 0;
  10265. }
  10266. Object.defineProperty(PerfCounter.prototype, "min", {
  10267. /**
  10268. * Returns the smallest value ever
  10269. */
  10270. get: function () {
  10271. return this._min;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. Object.defineProperty(PerfCounter.prototype, "max", {
  10277. /**
  10278. * Returns the biggest value ever
  10279. */
  10280. get: function () {
  10281. return this._max;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. Object.defineProperty(PerfCounter.prototype, "average", {
  10287. /**
  10288. * Returns the average value since the performance counter is running
  10289. */
  10290. get: function () {
  10291. return this._average;
  10292. },
  10293. enumerable: true,
  10294. configurable: true
  10295. });
  10296. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10297. /**
  10298. * Returns the average value of the last second the counter was monitored
  10299. */
  10300. get: function () {
  10301. return this._lastSecAverage;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Object.defineProperty(PerfCounter.prototype, "current", {
  10307. /**
  10308. * Returns the current value
  10309. */
  10310. get: function () {
  10311. return this._current;
  10312. },
  10313. enumerable: true,
  10314. configurable: true
  10315. });
  10316. Object.defineProperty(PerfCounter.prototype, "total", {
  10317. get: function () {
  10318. return this._totalAccumulated;
  10319. },
  10320. enumerable: true,
  10321. configurable: true
  10322. });
  10323. Object.defineProperty(PerfCounter.prototype, "count", {
  10324. get: function () {
  10325. return this._totalValueCount;
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. /**
  10331. * Call this method to start monitoring a new frame.
  10332. * 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.
  10333. */
  10334. PerfCounter.prototype.fetchNewFrame = function () {
  10335. this._totalValueCount++;
  10336. this._current = 0;
  10337. this._lastSecValueCount++;
  10338. };
  10339. /**
  10340. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10341. * @param newCount the count value to add to the monitored count
  10342. * @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.
  10343. */
  10344. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10345. if (!PerfCounter.Enabled) {
  10346. return;
  10347. }
  10348. this._current += newCount;
  10349. if (fetchResult) {
  10350. this._fetchResult();
  10351. }
  10352. };
  10353. /**
  10354. * Start monitoring this performance counter
  10355. */
  10356. PerfCounter.prototype.beginMonitoring = function () {
  10357. if (!PerfCounter.Enabled) {
  10358. return;
  10359. }
  10360. this._startMonitoringTime = Tools.Now;
  10361. };
  10362. /**
  10363. * Compute the time lapsed since the previous beginMonitoring() call.
  10364. * @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
  10365. */
  10366. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10367. if (newFrame === void 0) { newFrame = true; }
  10368. if (!PerfCounter.Enabled) {
  10369. return;
  10370. }
  10371. if (newFrame) {
  10372. this.fetchNewFrame();
  10373. }
  10374. var currentTime = Tools.Now;
  10375. this._current = currentTime - this._startMonitoringTime;
  10376. if (newFrame) {
  10377. this._fetchResult();
  10378. }
  10379. };
  10380. PerfCounter.prototype._fetchResult = function () {
  10381. this._totalAccumulated += this._current;
  10382. this._lastSecAccumulated += this._current;
  10383. // Min/Max update
  10384. this._min = Math.min(this._min, this._current);
  10385. this._max = Math.max(this._max, this._current);
  10386. this._average = this._totalAccumulated / this._totalValueCount;
  10387. // Reset last sec?
  10388. var now = Tools.Now;
  10389. if ((now - this._lastSecTime) > 1000) {
  10390. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10391. this._lastSecTime = now;
  10392. this._lastSecAccumulated = 0;
  10393. this._lastSecValueCount = 0;
  10394. }
  10395. };
  10396. PerfCounter.Enabled = true;
  10397. return PerfCounter;
  10398. }());
  10399. BABYLON.PerfCounter = PerfCounter;
  10400. /**
  10401. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10402. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10403. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10404. * @param name The name of the class, case should be preserved
  10405. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10406. */
  10407. function className(name, module) {
  10408. return function (target) {
  10409. target["__bjsclassName__"] = name;
  10410. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10411. };
  10412. }
  10413. BABYLON.className = className;
  10414. /**
  10415. * An implementation of a loop for asynchronous functions.
  10416. */
  10417. var AsyncLoop = /** @class */ (function () {
  10418. /**
  10419. * Constroctor.
  10420. * @param iterations the number of iterations.
  10421. * @param _fn the function to run each iteration
  10422. * @param _successCallback the callback that will be called upon succesful execution
  10423. * @param offset starting offset.
  10424. */
  10425. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10426. if (offset === void 0) { offset = 0; }
  10427. this.iterations = iterations;
  10428. this._fn = _fn;
  10429. this._successCallback = _successCallback;
  10430. this.index = offset - 1;
  10431. this._done = false;
  10432. }
  10433. /**
  10434. * Execute the next iteration. Must be called after the last iteration was finished.
  10435. */
  10436. AsyncLoop.prototype.executeNext = function () {
  10437. if (!this._done) {
  10438. if (this.index + 1 < this.iterations) {
  10439. ++this.index;
  10440. this._fn(this);
  10441. }
  10442. else {
  10443. this.breakLoop();
  10444. }
  10445. }
  10446. };
  10447. /**
  10448. * Break the loop and run the success callback.
  10449. */
  10450. AsyncLoop.prototype.breakLoop = function () {
  10451. this._done = true;
  10452. this._successCallback();
  10453. };
  10454. /**
  10455. * Helper function
  10456. */
  10457. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10458. if (offset === void 0) { offset = 0; }
  10459. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10460. loop.executeNext();
  10461. return loop;
  10462. };
  10463. /**
  10464. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10465. * @param iterations total number of iterations
  10466. * @param syncedIterations number of synchronous iterations in each async iteration.
  10467. * @param fn the function to call each iteration.
  10468. * @param callback a success call back that will be called when iterating stops.
  10469. * @param breakFunction a break condition (optional)
  10470. * @param timeout timeout settings for the setTimeout function. default - 0.
  10471. * @constructor
  10472. */
  10473. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10474. if (timeout === void 0) { timeout = 0; }
  10475. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10476. if (breakFunction && breakFunction())
  10477. loop.breakLoop();
  10478. else {
  10479. setTimeout(function () {
  10480. for (var i = 0; i < syncedIterations; ++i) {
  10481. var iteration = (loop.index * syncedIterations) + i;
  10482. if (iteration >= iterations)
  10483. break;
  10484. fn(iteration);
  10485. if (breakFunction && breakFunction()) {
  10486. loop.breakLoop();
  10487. break;
  10488. }
  10489. }
  10490. loop.executeNext();
  10491. }, timeout);
  10492. }
  10493. }, callback);
  10494. };
  10495. return AsyncLoop;
  10496. }());
  10497. BABYLON.AsyncLoop = AsyncLoop;
  10498. })(BABYLON || (BABYLON = {}));
  10499. //# sourceMappingURL=babylon.tools.js.map
  10500. var BABYLON;
  10501. (function (BABYLON) {
  10502. var PromiseStates;
  10503. (function (PromiseStates) {
  10504. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10505. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10506. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10507. })(PromiseStates || (PromiseStates = {}));
  10508. var FulFillmentAgregator = /** @class */ (function () {
  10509. function FulFillmentAgregator() {
  10510. this.count = 0;
  10511. this.target = 0;
  10512. this.results = [];
  10513. }
  10514. return FulFillmentAgregator;
  10515. }());
  10516. var InternalPromise = /** @class */ (function () {
  10517. function InternalPromise(resolver) {
  10518. var _this = this;
  10519. this._state = PromiseStates.Pending;
  10520. this._children = new Array();
  10521. this._rejectWasConsumed = false;
  10522. if (!resolver) {
  10523. return;
  10524. }
  10525. try {
  10526. resolver(function (value) {
  10527. _this._resolve(value);
  10528. }, function (reason) {
  10529. _this._reject(reason);
  10530. });
  10531. }
  10532. catch (e) {
  10533. this._reject(e);
  10534. }
  10535. }
  10536. Object.defineProperty(InternalPromise.prototype, "_result", {
  10537. get: function () {
  10538. return this._resultValue;
  10539. },
  10540. set: function (value) {
  10541. this._resultValue = value;
  10542. if (this._parent && this._parent._result === undefined) {
  10543. this._parent._result = value;
  10544. }
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. InternalPromise.prototype.catch = function (onRejected) {
  10550. return this.then(undefined, onRejected);
  10551. };
  10552. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10553. var _this = this;
  10554. var newPromise = new InternalPromise();
  10555. newPromise._onFulfilled = onFulfilled;
  10556. newPromise._onRejected = onRejected;
  10557. // Composition
  10558. this._children.push(newPromise);
  10559. newPromise._parent = this;
  10560. if (this._state !== PromiseStates.Pending) {
  10561. BABYLON.Tools.SetImmediate(function () {
  10562. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10563. var returnedValue = newPromise._resolve(_this._result);
  10564. if (returnedValue !== undefined && returnedValue !== null) {
  10565. if (returnedValue._state !== undefined) {
  10566. var returnedPromise = returnedValue;
  10567. newPromise._children.push(returnedPromise);
  10568. returnedPromise._parent = newPromise;
  10569. newPromise = returnedPromise;
  10570. }
  10571. else {
  10572. newPromise._result = returnedValue;
  10573. }
  10574. }
  10575. }
  10576. else {
  10577. newPromise._reject(_this._reason);
  10578. }
  10579. });
  10580. }
  10581. return newPromise;
  10582. };
  10583. InternalPromise.prototype._moveChildren = function (children) {
  10584. var _this = this;
  10585. var _a;
  10586. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10587. this._children.forEach(function (child) {
  10588. child._parent = _this;
  10589. });
  10590. if (this._state === PromiseStates.Fulfilled) {
  10591. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10592. var child = _b[_i];
  10593. child._resolve(this._result);
  10594. }
  10595. }
  10596. else if (this._state === PromiseStates.Rejected) {
  10597. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10598. var child = _d[_c];
  10599. child._reject(this._reason);
  10600. }
  10601. }
  10602. };
  10603. InternalPromise.prototype._resolve = function (value) {
  10604. try {
  10605. this._state = PromiseStates.Fulfilled;
  10606. var returnedValue = null;
  10607. if (this._onFulfilled) {
  10608. returnedValue = this._onFulfilled(value);
  10609. }
  10610. if (returnedValue !== undefined && returnedValue !== null) {
  10611. if (returnedValue._state !== undefined) {
  10612. // Transmit children
  10613. var returnedPromise = returnedValue;
  10614. returnedPromise._parent = this;
  10615. returnedPromise._moveChildren(this._children);
  10616. value = returnedPromise._result;
  10617. }
  10618. else {
  10619. value = returnedValue;
  10620. }
  10621. }
  10622. this._result = value;
  10623. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10624. var child = _a[_i];
  10625. child._resolve(value);
  10626. }
  10627. this._children.length = 0;
  10628. delete this._onFulfilled;
  10629. delete this._onRejected;
  10630. }
  10631. catch (e) {
  10632. this._reject(e, true);
  10633. }
  10634. };
  10635. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10636. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10637. this._state = PromiseStates.Rejected;
  10638. this._reason = reason;
  10639. if (this._onRejected && !onLocalThrow) {
  10640. try {
  10641. this._onRejected(reason);
  10642. this._rejectWasConsumed = true;
  10643. }
  10644. catch (e) {
  10645. reason = e;
  10646. }
  10647. }
  10648. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10649. var child = _a[_i];
  10650. if (this._rejectWasConsumed) {
  10651. child._resolve(null);
  10652. }
  10653. else {
  10654. child._reject(reason);
  10655. }
  10656. }
  10657. this._children.length = 0;
  10658. delete this._onFulfilled;
  10659. delete this._onRejected;
  10660. };
  10661. InternalPromise.resolve = function (value) {
  10662. var newPromise = new InternalPromise();
  10663. newPromise._resolve(value);
  10664. return newPromise;
  10665. };
  10666. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10667. promise.then(function (value) {
  10668. agregator.results[index] = value;
  10669. agregator.count++;
  10670. if (agregator.count === agregator.target) {
  10671. agregator.rootPromise._resolve(agregator.results);
  10672. }
  10673. return null;
  10674. }, function (reason) {
  10675. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10676. agregator.rootPromise._reject(reason);
  10677. }
  10678. });
  10679. };
  10680. InternalPromise.all = function (promises) {
  10681. var newPromise = new InternalPromise();
  10682. var agregator = new FulFillmentAgregator();
  10683. agregator.target = promises.length;
  10684. agregator.rootPromise = newPromise;
  10685. if (promises.length) {
  10686. for (var index = 0; index < promises.length; index++) {
  10687. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10688. }
  10689. }
  10690. else {
  10691. newPromise._resolve([]);
  10692. }
  10693. return newPromise;
  10694. };
  10695. InternalPromise.race = function (promises) {
  10696. var newPromise = new InternalPromise();
  10697. if (promises.length) {
  10698. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10699. var promise = promises_1[_i];
  10700. promise.then(function (value) {
  10701. if (newPromise) {
  10702. newPromise._resolve(value);
  10703. newPromise = null;
  10704. }
  10705. return null;
  10706. }, function (reason) {
  10707. if (newPromise) {
  10708. newPromise._reject(reason);
  10709. newPromise = null;
  10710. }
  10711. });
  10712. }
  10713. }
  10714. return newPromise;
  10715. };
  10716. return InternalPromise;
  10717. }());
  10718. /**
  10719. * Helper class that provides a small promise polyfill
  10720. */
  10721. var PromisePolyfill = /** @class */ (function () {
  10722. function PromisePolyfill() {
  10723. }
  10724. /**
  10725. * Static function used to check if the polyfill is required
  10726. * If this is the case then the function will inject the polyfill to window.Promise
  10727. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10728. */
  10729. PromisePolyfill.Apply = function (force) {
  10730. if (force === void 0) { force = false; }
  10731. if (force || typeof Promise === 'undefined') {
  10732. var root = window;
  10733. root.Promise = InternalPromise;
  10734. }
  10735. };
  10736. return PromisePolyfill;
  10737. }());
  10738. BABYLON.PromisePolyfill = PromisePolyfill;
  10739. })(BABYLON || (BABYLON = {}));
  10740. //# sourceMappingURL=babylon.promise.js.map
  10741. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10742. var BABYLON;
  10743. (function (BABYLON) {
  10744. /**
  10745. * Helper class to push actions to a pool of workers.
  10746. */
  10747. var WorkerPool = /** @class */ (function () {
  10748. /**
  10749. * Constructor
  10750. * @param workers Array of workers to use for actions
  10751. */
  10752. function WorkerPool(workers) {
  10753. this._pendingActions = new Array();
  10754. this._workerInfos = workers.map(function (worker) { return ({
  10755. worker: worker,
  10756. active: false
  10757. }); });
  10758. }
  10759. /**
  10760. * Terminates all workers and clears any pending actions.
  10761. */
  10762. WorkerPool.prototype.dispose = function () {
  10763. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10764. var workerInfo = _a[_i];
  10765. workerInfo.worker.terminate();
  10766. }
  10767. delete this._workerInfos;
  10768. delete this._pendingActions;
  10769. };
  10770. /**
  10771. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10772. * pended until a worker has completed its action.
  10773. * @param action The action to perform. Call onComplete when the action is complete.
  10774. */
  10775. WorkerPool.prototype.push = function (action) {
  10776. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10777. var workerInfo = _a[_i];
  10778. if (!workerInfo.active) {
  10779. this._execute(workerInfo, action);
  10780. return;
  10781. }
  10782. }
  10783. this._pendingActions.push(action);
  10784. };
  10785. WorkerPool.prototype._execute = function (workerInfo, action) {
  10786. var _this = this;
  10787. workerInfo.active = true;
  10788. action(workerInfo.worker, function () {
  10789. workerInfo.active = false;
  10790. var nextAction = _this._pendingActions.shift();
  10791. if (nextAction) {
  10792. _this._execute(workerInfo, nextAction);
  10793. }
  10794. });
  10795. };
  10796. return WorkerPool;
  10797. }());
  10798. BABYLON.WorkerPool = WorkerPool;
  10799. })(BABYLON || (BABYLON = {}));
  10800. //# sourceMappingURL=babylon.workerPool.js.map
  10801. var BABYLON;
  10802. (function (BABYLON) {
  10803. /**
  10804. * @hidden
  10805. **/
  10806. var _AlphaState = /** @class */ (function () {
  10807. /**
  10808. * Initializes the state.
  10809. */
  10810. function _AlphaState() {
  10811. this._isAlphaBlendDirty = false;
  10812. this._isBlendFunctionParametersDirty = false;
  10813. this._isBlendEquationParametersDirty = false;
  10814. this._isBlendConstantsDirty = false;
  10815. this._alphaBlend = false;
  10816. this._blendFunctionParameters = new Array(4);
  10817. this._blendEquationParameters = new Array(2);
  10818. this._blendConstants = new Array(4);
  10819. this.reset();
  10820. }
  10821. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10822. get: function () {
  10823. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10829. get: function () {
  10830. return this._alphaBlend;
  10831. },
  10832. set: function (value) {
  10833. if (this._alphaBlend === value) {
  10834. return;
  10835. }
  10836. this._alphaBlend = value;
  10837. this._isAlphaBlendDirty = true;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10843. if (this._blendConstants[0] === r &&
  10844. this._blendConstants[1] === g &&
  10845. this._blendConstants[2] === b &&
  10846. this._blendConstants[3] === a) {
  10847. return;
  10848. }
  10849. this._blendConstants[0] = r;
  10850. this._blendConstants[1] = g;
  10851. this._blendConstants[2] = b;
  10852. this._blendConstants[3] = a;
  10853. this._isBlendConstantsDirty = true;
  10854. };
  10855. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10856. if (this._blendFunctionParameters[0] === value0 &&
  10857. this._blendFunctionParameters[1] === value1 &&
  10858. this._blendFunctionParameters[2] === value2 &&
  10859. this._blendFunctionParameters[3] === value3) {
  10860. return;
  10861. }
  10862. this._blendFunctionParameters[0] = value0;
  10863. this._blendFunctionParameters[1] = value1;
  10864. this._blendFunctionParameters[2] = value2;
  10865. this._blendFunctionParameters[3] = value3;
  10866. this._isBlendFunctionParametersDirty = true;
  10867. };
  10868. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10869. if (this._blendEquationParameters[0] === rgb &&
  10870. this._blendEquationParameters[1] === alpha) {
  10871. return;
  10872. }
  10873. this._blendEquationParameters[0] = rgb;
  10874. this._blendEquationParameters[1] = alpha;
  10875. this._isBlendEquationParametersDirty = true;
  10876. };
  10877. _AlphaState.prototype.reset = function () {
  10878. this._alphaBlend = false;
  10879. this._blendFunctionParameters[0] = null;
  10880. this._blendFunctionParameters[1] = null;
  10881. this._blendFunctionParameters[2] = null;
  10882. this._blendFunctionParameters[3] = null;
  10883. this._blendEquationParameters[0] = null;
  10884. this._blendEquationParameters[1] = null;
  10885. this._blendConstants[0] = null;
  10886. this._blendConstants[1] = null;
  10887. this._blendConstants[2] = null;
  10888. this._blendConstants[3] = null;
  10889. this._isAlphaBlendDirty = true;
  10890. this._isBlendFunctionParametersDirty = false;
  10891. this._isBlendEquationParametersDirty = false;
  10892. this._isBlendConstantsDirty = false;
  10893. };
  10894. _AlphaState.prototype.apply = function (gl) {
  10895. if (!this.isDirty) {
  10896. return;
  10897. }
  10898. // Alpha blend
  10899. if (this._isAlphaBlendDirty) {
  10900. if (this._alphaBlend) {
  10901. gl.enable(gl.BLEND);
  10902. }
  10903. else {
  10904. gl.disable(gl.BLEND);
  10905. }
  10906. this._isAlphaBlendDirty = false;
  10907. }
  10908. // Alpha function
  10909. if (this._isBlendFunctionParametersDirty) {
  10910. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10911. this._isBlendFunctionParametersDirty = false;
  10912. }
  10913. // Alpha equation
  10914. if (this._isBlendEquationParametersDirty) {
  10915. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10916. this._isBlendEquationParametersDirty = false;
  10917. }
  10918. // Constants
  10919. if (this._isBlendConstantsDirty) {
  10920. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10921. this._isBlendConstantsDirty = false;
  10922. }
  10923. };
  10924. return _AlphaState;
  10925. }());
  10926. BABYLON._AlphaState = _AlphaState;
  10927. })(BABYLON || (BABYLON = {}));
  10928. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10929. var BABYLON;
  10930. (function (BABYLON) {
  10931. /**
  10932. * @hidden
  10933. **/
  10934. var _DepthCullingState = /** @class */ (function () {
  10935. /**
  10936. * Initializes the state.
  10937. */
  10938. function _DepthCullingState() {
  10939. this._isDepthTestDirty = false;
  10940. this._isDepthMaskDirty = false;
  10941. this._isDepthFuncDirty = false;
  10942. this._isCullFaceDirty = false;
  10943. this._isCullDirty = false;
  10944. this._isZOffsetDirty = false;
  10945. this._isFrontFaceDirty = false;
  10946. this.reset();
  10947. }
  10948. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10949. get: function () {
  10950. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10956. get: function () {
  10957. return this._zOffset;
  10958. },
  10959. set: function (value) {
  10960. if (this._zOffset === value) {
  10961. return;
  10962. }
  10963. this._zOffset = value;
  10964. this._isZOffsetDirty = true;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10970. get: function () {
  10971. return this._cullFace;
  10972. },
  10973. set: function (value) {
  10974. if (this._cullFace === value) {
  10975. return;
  10976. }
  10977. this._cullFace = value;
  10978. this._isCullFaceDirty = true;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10984. get: function () {
  10985. return this._cull;
  10986. },
  10987. set: function (value) {
  10988. if (this._cull === value) {
  10989. return;
  10990. }
  10991. this._cull = value;
  10992. this._isCullDirty = true;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10998. get: function () {
  10999. return this._depthFunc;
  11000. },
  11001. set: function (value) {
  11002. if (this._depthFunc === value) {
  11003. return;
  11004. }
  11005. this._depthFunc = value;
  11006. this._isDepthFuncDirty = true;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11012. get: function () {
  11013. return this._depthMask;
  11014. },
  11015. set: function (value) {
  11016. if (this._depthMask === value) {
  11017. return;
  11018. }
  11019. this._depthMask = value;
  11020. this._isDepthMaskDirty = true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11026. get: function () {
  11027. return this._depthTest;
  11028. },
  11029. set: function (value) {
  11030. if (this._depthTest === value) {
  11031. return;
  11032. }
  11033. this._depthTest = value;
  11034. this._isDepthTestDirty = true;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11040. get: function () {
  11041. return this._frontFace;
  11042. },
  11043. set: function (value) {
  11044. if (this._frontFace === value) {
  11045. return;
  11046. }
  11047. this._frontFace = value;
  11048. this._isFrontFaceDirty = true;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. _DepthCullingState.prototype.reset = function () {
  11054. this._depthMask = true;
  11055. this._depthTest = true;
  11056. this._depthFunc = null;
  11057. this._cullFace = null;
  11058. this._cull = null;
  11059. this._zOffset = 0;
  11060. this._frontFace = null;
  11061. this._isDepthTestDirty = true;
  11062. this._isDepthMaskDirty = true;
  11063. this._isDepthFuncDirty = false;
  11064. this._isCullFaceDirty = false;
  11065. this._isCullDirty = false;
  11066. this._isZOffsetDirty = false;
  11067. this._isFrontFaceDirty = false;
  11068. };
  11069. _DepthCullingState.prototype.apply = function (gl) {
  11070. if (!this.isDirty) {
  11071. return;
  11072. }
  11073. // Cull
  11074. if (this._isCullDirty) {
  11075. if (this.cull) {
  11076. gl.enable(gl.CULL_FACE);
  11077. }
  11078. else {
  11079. gl.disable(gl.CULL_FACE);
  11080. }
  11081. this._isCullDirty = false;
  11082. }
  11083. // Cull face
  11084. if (this._isCullFaceDirty) {
  11085. gl.cullFace(this.cullFace);
  11086. this._isCullFaceDirty = false;
  11087. }
  11088. // Depth mask
  11089. if (this._isDepthMaskDirty) {
  11090. gl.depthMask(this.depthMask);
  11091. this._isDepthMaskDirty = false;
  11092. }
  11093. // Depth test
  11094. if (this._isDepthTestDirty) {
  11095. if (this.depthTest) {
  11096. gl.enable(gl.DEPTH_TEST);
  11097. }
  11098. else {
  11099. gl.disable(gl.DEPTH_TEST);
  11100. }
  11101. this._isDepthTestDirty = false;
  11102. }
  11103. // Depth func
  11104. if (this._isDepthFuncDirty) {
  11105. gl.depthFunc(this.depthFunc);
  11106. this._isDepthFuncDirty = false;
  11107. }
  11108. // zOffset
  11109. if (this._isZOffsetDirty) {
  11110. if (this.zOffset) {
  11111. gl.enable(gl.POLYGON_OFFSET_FILL);
  11112. gl.polygonOffset(this.zOffset, 0);
  11113. }
  11114. else {
  11115. gl.disable(gl.POLYGON_OFFSET_FILL);
  11116. }
  11117. this._isZOffsetDirty = false;
  11118. }
  11119. // Front face
  11120. if (this._isFrontFaceDirty) {
  11121. gl.frontFace(this.frontFace);
  11122. this._isFrontFaceDirty = false;
  11123. }
  11124. };
  11125. return _DepthCullingState;
  11126. }());
  11127. BABYLON._DepthCullingState = _DepthCullingState;
  11128. })(BABYLON || (BABYLON = {}));
  11129. //# sourceMappingURL=babylon.depthCullingState.js.map
  11130. var BABYLON;
  11131. (function (BABYLON) {
  11132. /**
  11133. * @hidden
  11134. **/
  11135. var _StencilState = /** @class */ (function () {
  11136. function _StencilState() {
  11137. this._isStencilTestDirty = false;
  11138. this._isStencilMaskDirty = false;
  11139. this._isStencilFuncDirty = false;
  11140. this._isStencilOpDirty = false;
  11141. this.reset();
  11142. }
  11143. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11144. get: function () {
  11145. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11151. get: function () {
  11152. return this._stencilFunc;
  11153. },
  11154. set: function (value) {
  11155. if (this._stencilFunc === value) {
  11156. return;
  11157. }
  11158. this._stencilFunc = value;
  11159. this._isStencilFuncDirty = true;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11165. get: function () {
  11166. return this._stencilFuncRef;
  11167. },
  11168. set: function (value) {
  11169. if (this._stencilFuncRef === value) {
  11170. return;
  11171. }
  11172. this._stencilFuncRef = value;
  11173. this._isStencilFuncDirty = true;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11179. get: function () {
  11180. return this._stencilFuncMask;
  11181. },
  11182. set: function (value) {
  11183. if (this._stencilFuncMask === value) {
  11184. return;
  11185. }
  11186. this._stencilFuncMask = value;
  11187. this._isStencilFuncDirty = true;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11193. get: function () {
  11194. return this._stencilOpStencilFail;
  11195. },
  11196. set: function (value) {
  11197. if (this._stencilOpStencilFail === value) {
  11198. return;
  11199. }
  11200. this._stencilOpStencilFail = value;
  11201. this._isStencilOpDirty = true;
  11202. },
  11203. enumerable: true,
  11204. configurable: true
  11205. });
  11206. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11207. get: function () {
  11208. return this._stencilOpDepthFail;
  11209. },
  11210. set: function (value) {
  11211. if (this._stencilOpDepthFail === value) {
  11212. return;
  11213. }
  11214. this._stencilOpDepthFail = value;
  11215. this._isStencilOpDirty = true;
  11216. },
  11217. enumerable: true,
  11218. configurable: true
  11219. });
  11220. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11221. get: function () {
  11222. return this._stencilOpStencilDepthPass;
  11223. },
  11224. set: function (value) {
  11225. if (this._stencilOpStencilDepthPass === value) {
  11226. return;
  11227. }
  11228. this._stencilOpStencilDepthPass = value;
  11229. this._isStencilOpDirty = true;
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11235. get: function () {
  11236. return this._stencilMask;
  11237. },
  11238. set: function (value) {
  11239. if (this._stencilMask === value) {
  11240. return;
  11241. }
  11242. this._stencilMask = value;
  11243. this._isStencilMaskDirty = true;
  11244. },
  11245. enumerable: true,
  11246. configurable: true
  11247. });
  11248. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11249. get: function () {
  11250. return this._stencilTest;
  11251. },
  11252. set: function (value) {
  11253. if (this._stencilTest === value) {
  11254. return;
  11255. }
  11256. this._stencilTest = value;
  11257. this._isStencilTestDirty = true;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. _StencilState.prototype.reset = function () {
  11263. this._stencilTest = false;
  11264. this._stencilMask = 0xFF;
  11265. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11266. this._stencilFuncRef = 1;
  11267. this._stencilFuncMask = 0xFF;
  11268. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11269. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11270. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11271. this._isStencilTestDirty = true;
  11272. this._isStencilMaskDirty = true;
  11273. this._isStencilFuncDirty = true;
  11274. this._isStencilOpDirty = true;
  11275. };
  11276. _StencilState.prototype.apply = function (gl) {
  11277. if (!this.isDirty) {
  11278. return;
  11279. }
  11280. // Stencil test
  11281. if (this._isStencilTestDirty) {
  11282. if (this.stencilTest) {
  11283. gl.enable(gl.STENCIL_TEST);
  11284. }
  11285. else {
  11286. gl.disable(gl.STENCIL_TEST);
  11287. }
  11288. this._isStencilTestDirty = false;
  11289. }
  11290. // Stencil mask
  11291. if (this._isStencilMaskDirty) {
  11292. gl.stencilMask(this.stencilMask);
  11293. this._isStencilMaskDirty = false;
  11294. }
  11295. // Stencil func
  11296. if (this._isStencilFuncDirty) {
  11297. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11298. this._isStencilFuncDirty = false;
  11299. }
  11300. // Stencil op
  11301. if (this._isStencilOpDirty) {
  11302. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11303. this._isStencilOpDirty = false;
  11304. }
  11305. };
  11306. return _StencilState;
  11307. }());
  11308. BABYLON._StencilState = _StencilState;
  11309. })(BABYLON || (BABYLON = {}));
  11310. //# sourceMappingURL=babylon.stencilState.js.map
  11311. var __assign = (this && this.__assign) || function () {
  11312. __assign = Object.assign || function(t) {
  11313. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11314. s = arguments[i];
  11315. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11316. t[p] = s[p];
  11317. }
  11318. return t;
  11319. };
  11320. return __assign.apply(this, arguments);
  11321. };
  11322. var BABYLON;
  11323. (function (BABYLON) {
  11324. /**
  11325. * Keeps track of all the buffer info used in engine.
  11326. */
  11327. var BufferPointer = /** @class */ (function () {
  11328. function BufferPointer() {
  11329. }
  11330. return BufferPointer;
  11331. }());
  11332. /**
  11333. * Interface for attribute information associated with buffer instanciation
  11334. */
  11335. var InstancingAttributeInfo = /** @class */ (function () {
  11336. function InstancingAttributeInfo() {
  11337. }
  11338. return InstancingAttributeInfo;
  11339. }());
  11340. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11341. /**
  11342. * Define options used to create a render target texture
  11343. */
  11344. var RenderTargetCreationOptions = /** @class */ (function () {
  11345. function RenderTargetCreationOptions() {
  11346. }
  11347. return RenderTargetCreationOptions;
  11348. }());
  11349. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11350. /**
  11351. * Define options used to create a depth texture
  11352. */
  11353. var DepthTextureCreationOptions = /** @class */ (function () {
  11354. function DepthTextureCreationOptions() {
  11355. }
  11356. return DepthTextureCreationOptions;
  11357. }());
  11358. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11359. /**
  11360. * Class used to describe the capabilities of the engine relatively to the current browser
  11361. */
  11362. var EngineCapabilities = /** @class */ (function () {
  11363. function EngineCapabilities() {
  11364. }
  11365. return EngineCapabilities;
  11366. }());
  11367. BABYLON.EngineCapabilities = EngineCapabilities;
  11368. /**
  11369. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11370. */
  11371. var Engine = /** @class */ (function () {
  11372. /**
  11373. * Creates a new engine
  11374. * @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
  11375. * @param antialias defines enable antialiasing (default: false)
  11376. * @param options defines further options to be sent to the getContext() function
  11377. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11378. */
  11379. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11380. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11381. var _this = this;
  11382. // Public members
  11383. /**
  11384. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11385. */
  11386. this.forcePOTTextures = false;
  11387. /**
  11388. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11389. */
  11390. this.isFullscreen = false;
  11391. /**
  11392. * Gets a boolean indicating if the pointer is currently locked
  11393. */
  11394. this.isPointerLock = false;
  11395. /**
  11396. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11397. */
  11398. this.cullBackFaces = true;
  11399. /**
  11400. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11401. */
  11402. this.renderEvenInBackground = true;
  11403. /**
  11404. * Gets or sets a boolean indicating that cache can be kept between frames
  11405. */
  11406. this.preventCacheWipeBetweenFrames = false;
  11407. /**
  11408. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11409. **/
  11410. this.enableOfflineSupport = false;
  11411. /**
  11412. * 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)
  11413. **/
  11414. this.disableManifestCheck = false;
  11415. /**
  11416. * Gets the list of created scenes
  11417. */
  11418. this.scenes = new Array();
  11419. /**
  11420. * Gets the list of created postprocesses
  11421. */
  11422. this.postProcesses = new Array();
  11423. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11424. this.validateShaderPrograms = false;
  11425. // Observables
  11426. /**
  11427. * Observable event triggered each time the rendering canvas is resized
  11428. */
  11429. this.onResizeObservable = new BABYLON.Observable();
  11430. /**
  11431. * Observable event triggered each time the canvas loses focus
  11432. */
  11433. this.onCanvasBlurObservable = new BABYLON.Observable();
  11434. /**
  11435. * Observable event triggered each time the canvas gains focus
  11436. */
  11437. this.onCanvasFocusObservable = new BABYLON.Observable();
  11438. /**
  11439. * Observable event triggered each time the canvas receives pointerout event
  11440. */
  11441. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11442. /**
  11443. * Observable event triggered before each texture is initialized
  11444. */
  11445. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11446. //WebVR
  11447. this._vrDisplay = undefined;
  11448. this._vrSupported = false;
  11449. this._vrExclusivePointerMode = false;
  11450. // Uniform buffers list
  11451. /**
  11452. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11453. */
  11454. this.disableUniformBuffers = false;
  11455. /** @hidden */
  11456. this._uniformBuffers = new Array();
  11457. // Observables
  11458. /**
  11459. * Observable raised when the engine begins a new frame
  11460. */
  11461. this.onBeginFrameObservable = new BABYLON.Observable();
  11462. /**
  11463. * Observable raised when the engine ends the current frame
  11464. */
  11465. this.onEndFrameObservable = new BABYLON.Observable();
  11466. /**
  11467. * Observable raised when the engine is about to compile a shader
  11468. */
  11469. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11470. /**
  11471. * Observable raised when the engine has jsut compiled a shader
  11472. */
  11473. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11474. this._windowIsBackground = false;
  11475. this._webGLVersion = 1.0;
  11476. /** @hidden */
  11477. this._badOS = false;
  11478. /** @hidden */
  11479. this._badDesktopOS = false;
  11480. /**
  11481. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11482. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11483. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11484. */
  11485. this.disableTextureBindingOptimization = false;
  11486. /**
  11487. * Observable signaled when VR display mode changes
  11488. */
  11489. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11490. /**
  11491. * Observable signaled when VR request present is complete
  11492. */
  11493. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11494. /**
  11495. * Observable signaled when VR request present starts
  11496. */
  11497. this.onVRRequestPresentStart = new BABYLON.Observable();
  11498. this._colorWrite = true;
  11499. /** @hidden */
  11500. this._drawCalls = new BABYLON.PerfCounter();
  11501. /** @hidden */
  11502. this._textureCollisions = new BABYLON.PerfCounter();
  11503. this._renderingQueueLaunched = false;
  11504. this._activeRenderLoops = new Array();
  11505. // Deterministic lockstepMaxSteps
  11506. this._deterministicLockstep = false;
  11507. this._lockstepMaxSteps = 4;
  11508. // Lost context
  11509. /**
  11510. * Observable signaled when a context lost event is raised
  11511. */
  11512. this.onContextLostObservable = new BABYLON.Observable();
  11513. /**
  11514. * Observable signaled when a context restored event is raised
  11515. */
  11516. this.onContextRestoredObservable = new BABYLON.Observable();
  11517. this._contextWasLost = false;
  11518. this._doNotHandleContextLost = false;
  11519. // FPS
  11520. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11521. this._fps = 60;
  11522. this._deltaTime = 0;
  11523. /**
  11524. * Turn this value on if you want to pause FPS computation when in background
  11525. */
  11526. this.disablePerformanceMonitorInBackground = false;
  11527. // States
  11528. /** @hidden */
  11529. this._depthCullingState = new BABYLON._DepthCullingState();
  11530. /** @hidden */
  11531. this._stencilState = new BABYLON._StencilState();
  11532. /** @hidden */
  11533. this._alphaState = new BABYLON._AlphaState();
  11534. /** @hidden */
  11535. this._alphaMode = Engine.ALPHA_DISABLE;
  11536. // Cache
  11537. this._internalTexturesCache = new Array();
  11538. /** @hidden */
  11539. this._activeChannel = 0;
  11540. this._currentTextureChannel = -1;
  11541. /** @hidden */
  11542. this._boundTexturesCache = {};
  11543. this._compiledEffects = {};
  11544. this._vertexAttribArraysEnabled = [];
  11545. this._uintIndicesCurrentlySet = false;
  11546. this._currentBoundBuffer = new Array();
  11547. /** @hidden */
  11548. this._currentFramebuffer = null;
  11549. this._currentBufferPointers = new Array();
  11550. this._currentInstanceLocations = new Array();
  11551. this._currentInstanceBuffers = new Array();
  11552. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11553. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11554. this._vaoRecordInProgress = false;
  11555. this._mustWipeVertexAttributes = false;
  11556. this._nextFreeTextureSlots = new Array();
  11557. this._maxSimultaneousTextures = 0;
  11558. this._activeRequests = new Array();
  11559. // Hardware supported Compressed Textures
  11560. this._texturesSupported = new Array();
  11561. /**
  11562. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11563. */
  11564. this.premultipliedAlpha = true;
  11565. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11566. this._onVRFullScreenTriggered = function () {
  11567. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11568. //get the old size before we change
  11569. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11570. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11571. //get the width and height, change the render size
  11572. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11573. _this.setHardwareScalingLevel(1);
  11574. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11575. }
  11576. else {
  11577. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11578. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11579. }
  11580. };
  11581. this._unpackFlipYCached = null;
  11582. /**
  11583. * In case you are sharing the context with other applications, it might
  11584. * be interested to not cache the unpack flip y state to ensure a consistent
  11585. * value would be set.
  11586. */
  11587. this.enableUnpackFlipYCached = true;
  11588. this._boundUniforms = {};
  11589. // Register promises
  11590. BABYLON.PromisePolyfill.Apply();
  11591. var canvas = null;
  11592. Engine.Instances.push(this);
  11593. if (!canvasOrContext) {
  11594. return;
  11595. }
  11596. options = options || {};
  11597. if (canvasOrContext.getContext) {
  11598. canvas = canvasOrContext;
  11599. this._renderingCanvas = canvas;
  11600. if (antialias != null) {
  11601. options.antialias = antialias;
  11602. }
  11603. if (options.deterministicLockstep === undefined) {
  11604. options.deterministicLockstep = false;
  11605. }
  11606. if (options.lockstepMaxSteps === undefined) {
  11607. options.lockstepMaxSteps = 4;
  11608. }
  11609. if (options.preserveDrawingBuffer === undefined) {
  11610. options.preserveDrawingBuffer = false;
  11611. }
  11612. if (options.audioEngine === undefined) {
  11613. options.audioEngine = true;
  11614. }
  11615. if (options.stencil === undefined) {
  11616. options.stencil = true;
  11617. }
  11618. if (options.premultipliedAlpha === false) {
  11619. this.premultipliedAlpha = false;
  11620. }
  11621. this._deterministicLockstep = options.deterministicLockstep;
  11622. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11623. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11624. // Exceptions
  11625. if (navigator && navigator.userAgent) {
  11626. var ua = navigator.userAgent;
  11627. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11628. var exception = _a[_i];
  11629. var key = exception.key;
  11630. var targets = exception.targets;
  11631. if (ua.indexOf(key) > -1) {
  11632. if (exception.capture && exception.captureConstraint) {
  11633. var capture = exception.capture;
  11634. var constraint = exception.captureConstraint;
  11635. var regex = new RegExp(capture);
  11636. var matches = regex.exec(ua);
  11637. if (matches && matches.length > 0) {
  11638. var capturedValue = parseInt(matches[matches.length - 1]);
  11639. if (capturedValue >= constraint) {
  11640. continue;
  11641. }
  11642. }
  11643. }
  11644. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11645. var target = targets_1[_b];
  11646. switch (target) {
  11647. case "uniformBuffer":
  11648. this.disableUniformBuffers = true;
  11649. break;
  11650. case "textureBindingOptimization":
  11651. this.disableTextureBindingOptimization = true;
  11652. break;
  11653. }
  11654. }
  11655. }
  11656. }
  11657. }
  11658. // GL
  11659. if (!options.disableWebGL2Support) {
  11660. try {
  11661. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11662. if (this._gl) {
  11663. this._webGLVersion = 2.0;
  11664. }
  11665. }
  11666. catch (e) {
  11667. // Do nothing
  11668. }
  11669. }
  11670. if (!this._gl) {
  11671. if (!canvas) {
  11672. throw new Error("The provided canvas is null or undefined.");
  11673. }
  11674. try {
  11675. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11676. }
  11677. catch (e) {
  11678. throw new Error("WebGL not supported");
  11679. }
  11680. }
  11681. if (!this._gl) {
  11682. throw new Error("WebGL not supported");
  11683. }
  11684. this._onCanvasFocus = function () {
  11685. _this.onCanvasFocusObservable.notifyObservers(_this);
  11686. };
  11687. this._onCanvasBlur = function () {
  11688. _this.onCanvasBlurObservable.notifyObservers(_this);
  11689. };
  11690. canvas.addEventListener("focus", this._onCanvasFocus);
  11691. canvas.addEventListener("blur", this._onCanvasBlur);
  11692. this._onBlur = function () {
  11693. if (_this.disablePerformanceMonitorInBackground) {
  11694. _this._performanceMonitor.disable();
  11695. }
  11696. _this._windowIsBackground = true;
  11697. };
  11698. this._onFocus = function () {
  11699. if (_this.disablePerformanceMonitorInBackground) {
  11700. _this._performanceMonitor.enable();
  11701. }
  11702. _this._windowIsBackground = false;
  11703. };
  11704. this._onCanvasPointerOut = function (ev) {
  11705. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11706. };
  11707. window.addEventListener("blur", this._onBlur);
  11708. window.addEventListener("focus", this._onFocus);
  11709. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11710. // Context lost
  11711. if (!this._doNotHandleContextLost) {
  11712. this._onContextLost = function (evt) {
  11713. evt.preventDefault();
  11714. _this._contextWasLost = true;
  11715. BABYLON.Tools.Warn("WebGL context lost.");
  11716. _this.onContextLostObservable.notifyObservers(_this);
  11717. };
  11718. this._onContextRestored = function (evt) {
  11719. // Adding a timeout to avoid race condition at browser level
  11720. setTimeout(function () {
  11721. // Rebuild gl context
  11722. _this._initGLContext();
  11723. // Rebuild effects
  11724. _this._rebuildEffects();
  11725. // Rebuild textures
  11726. _this._rebuildInternalTextures();
  11727. // Rebuild buffers
  11728. _this._rebuildBuffers();
  11729. // Cache
  11730. _this.wipeCaches(true);
  11731. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11732. _this.onContextRestoredObservable.notifyObservers(_this);
  11733. _this._contextWasLost = false;
  11734. }, 0);
  11735. };
  11736. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11737. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11738. }
  11739. }
  11740. else {
  11741. this._gl = canvasOrContext;
  11742. this._renderingCanvas = this._gl.canvas;
  11743. if (this._gl.renderbufferStorageMultisample) {
  11744. this._webGLVersion = 2.0;
  11745. }
  11746. options.stencil = this._gl.getContextAttributes().stencil;
  11747. }
  11748. // Viewport
  11749. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11750. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11751. this.resize();
  11752. this._isStencilEnable = options.stencil ? true : false;
  11753. this._initGLContext();
  11754. if (canvas) {
  11755. // Fullscreen
  11756. this._onFullscreenChange = function () {
  11757. if (document.fullscreen !== undefined) {
  11758. _this.isFullscreen = document.fullscreen;
  11759. }
  11760. else if (document.mozFullScreen !== undefined) {
  11761. _this.isFullscreen = document.mozFullScreen;
  11762. }
  11763. else if (document.webkitIsFullScreen !== undefined) {
  11764. _this.isFullscreen = document.webkitIsFullScreen;
  11765. }
  11766. else if (document.msIsFullScreen !== undefined) {
  11767. _this.isFullscreen = document.msIsFullScreen;
  11768. }
  11769. // Pointer lock
  11770. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11771. canvas.requestPointerLock = canvas.requestPointerLock ||
  11772. canvas.msRequestPointerLock ||
  11773. canvas.mozRequestPointerLock ||
  11774. canvas.webkitRequestPointerLock;
  11775. if (canvas.requestPointerLock) {
  11776. canvas.requestPointerLock();
  11777. }
  11778. }
  11779. };
  11780. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11781. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11782. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11783. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11784. // Pointer lock
  11785. this._onPointerLockChange = function () {
  11786. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11787. document.webkitPointerLockElement === canvas ||
  11788. document.msPointerLockElement === canvas ||
  11789. document.pointerLockElement === canvas);
  11790. };
  11791. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11792. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11793. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11794. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11795. this._onVRDisplayPointerRestricted = function () {
  11796. if (canvas) {
  11797. canvas.requestPointerLock();
  11798. }
  11799. };
  11800. this._onVRDisplayPointerUnrestricted = function () {
  11801. document.exitPointerLock();
  11802. };
  11803. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11804. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11805. }
  11806. // Create Audio Engine if needed.
  11807. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11808. Engine.audioEngine = Engine.AudioEngineFactory();
  11809. }
  11810. // Prepare buffer pointers
  11811. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11812. this._currentBufferPointers[i] = new BufferPointer();
  11813. }
  11814. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11815. // Load WebVR Devices
  11816. if (options.autoEnableWebVR) {
  11817. this.initWebVR();
  11818. }
  11819. // Detect if we are running on a faulty buggy OS.
  11820. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11821. // Detect if we are running on a faulty buggy desktop OS.
  11822. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11823. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11824. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11825. }
  11826. Object.defineProperty(Engine, "LastCreatedEngine", {
  11827. /**
  11828. * Gets the latest created engine
  11829. */
  11830. get: function () {
  11831. if (Engine.Instances.length === 0) {
  11832. return null;
  11833. }
  11834. return Engine.Instances[Engine.Instances.length - 1];
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(Engine, "LastCreatedScene", {
  11840. /**
  11841. * Gets the latest created scene
  11842. */
  11843. get: function () {
  11844. var lastCreatedEngine = Engine.LastCreatedEngine;
  11845. if (!lastCreatedEngine) {
  11846. return null;
  11847. }
  11848. if (lastCreatedEngine.scenes.length === 0) {
  11849. return null;
  11850. }
  11851. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. /**
  11857. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11858. * @param flag defines which part of the materials must be marked as dirty
  11859. * @param predicate defines a predicate used to filter which materials should be affected
  11860. */
  11861. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11862. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11863. var engine = Engine.Instances[engineIndex];
  11864. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11865. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11866. }
  11867. }
  11868. };
  11869. Object.defineProperty(Engine, "Version", {
  11870. /**
  11871. * Returns the current version of the framework
  11872. */
  11873. get: function () {
  11874. return "3.3.0-beta.5";
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11880. /**
  11881. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11882. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11883. */
  11884. get: function () {
  11885. return this._vrExclusivePointerMode;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11891. /**
  11892. * Gets a boolean indicating that the engine supports uniform buffers
  11893. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11894. */
  11895. get: function () {
  11896. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11902. /**
  11903. * Gets a boolean indicating that only power of 2 textures are supported
  11904. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11905. */
  11906. get: function () {
  11907. return this._webGLVersion < 2 || this.forcePOTTextures;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11913. /**
  11914. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11915. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11916. */
  11917. get: function () {
  11918. return this._doNotHandleContextLost;
  11919. },
  11920. set: function (value) {
  11921. this._doNotHandleContextLost = value;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11927. /**
  11928. * Gets the performance monitor attached to this engine
  11929. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11930. */
  11931. get: function () {
  11932. return this._performanceMonitor;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11938. /**
  11939. * Gets the list of texture formats supported
  11940. */
  11941. get: function () {
  11942. return this._texturesSupported;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11948. /**
  11949. * Gets the list of texture formats in use
  11950. */
  11951. get: function () {
  11952. return this._textureFormatInUse;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine.prototype, "currentViewport", {
  11958. /**
  11959. * Gets the current viewport
  11960. */
  11961. get: function () {
  11962. return this._cachedViewport;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11968. /**
  11969. * Gets the default empty texture
  11970. */
  11971. get: function () {
  11972. if (!this._emptyTexture) {
  11973. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11974. }
  11975. return this._emptyTexture;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11981. /**
  11982. * Gets the default empty 3D texture
  11983. */
  11984. get: function () {
  11985. if (!this._emptyTexture3D) {
  11986. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11987. }
  11988. return this._emptyTexture3D;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11994. /**
  11995. * Gets the default empty cube texture
  11996. */
  11997. get: function () {
  11998. if (!this._emptyCubeTexture) {
  11999. var faceData = new Uint8Array(4);
  12000. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12001. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12002. }
  12003. return this._emptyCubeTexture;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Engine.prototype._rebuildInternalTextures = function () {
  12009. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12010. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12011. var internalTexture = currentState_1[_i];
  12012. internalTexture._rebuild();
  12013. }
  12014. };
  12015. Engine.prototype._rebuildEffects = function () {
  12016. for (var key in this._compiledEffects) {
  12017. var effect = this._compiledEffects[key];
  12018. effect._prepareEffect();
  12019. }
  12020. BABYLON.Effect.ResetCache();
  12021. };
  12022. Engine.prototype._rebuildBuffers = function () {
  12023. // Index / Vertex
  12024. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12025. var scene = _a[_i];
  12026. scene.resetCachedMaterial();
  12027. scene._rebuildGeometries();
  12028. scene._rebuildTextures();
  12029. }
  12030. // Uniforms
  12031. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12032. var uniformBuffer = _c[_b];
  12033. uniformBuffer._rebuild();
  12034. }
  12035. };
  12036. Engine.prototype._initGLContext = function () {
  12037. // Caps
  12038. this._caps = new EngineCapabilities();
  12039. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12040. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12041. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12042. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12043. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12044. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12045. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12046. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12047. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12048. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12049. // Infos
  12050. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12051. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12052. if (rendererInfo != null) {
  12053. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12054. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12055. }
  12056. if (!this._glVendor) {
  12057. this._glVendor = "Unknown vendor";
  12058. }
  12059. if (!this._glRenderer) {
  12060. this._glRenderer = "Unknown renderer";
  12061. }
  12062. // Constants
  12063. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12064. if (this._gl.RGBA16F !== 0x881A) {
  12065. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12066. }
  12067. if (this._gl.RGBA32F !== 0x8814) {
  12068. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12069. }
  12070. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12071. this._gl.DEPTH24_STENCIL8 = 35056;
  12072. }
  12073. // Extensions
  12074. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12075. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12076. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12077. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12078. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12079. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12080. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12081. 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');
  12082. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12083. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12084. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12085. this._caps.highPrecisionShaderSupported = true;
  12086. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12087. if (this._caps.timerQuery) {
  12088. if (this._webGLVersion === 1) {
  12089. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12090. }
  12091. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12092. }
  12093. // Checks if some of the format renders first to allow the use of webgl inspector.
  12094. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12095. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12096. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12097. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12098. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12099. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12100. if (this._webGLVersion > 1) {
  12101. this._gl.HALF_FLOAT_OES = 0x140B;
  12102. }
  12103. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12104. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12105. // Draw buffers
  12106. if (this._webGLVersion > 1) {
  12107. this._caps.drawBuffersExtension = true;
  12108. }
  12109. else {
  12110. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12111. if (drawBuffersExtension !== null) {
  12112. this._caps.drawBuffersExtension = true;
  12113. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12114. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12115. for (var i = 0; i < 16; i++) {
  12116. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12117. }
  12118. }
  12119. else {
  12120. this._caps.drawBuffersExtension = false;
  12121. }
  12122. }
  12123. // Depth Texture
  12124. if (this._webGLVersion > 1) {
  12125. this._caps.depthTextureExtension = true;
  12126. }
  12127. else {
  12128. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12129. if (depthTextureExtension != null) {
  12130. this._caps.depthTextureExtension = true;
  12131. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12132. }
  12133. }
  12134. // Vertex array object
  12135. if (this._webGLVersion > 1) {
  12136. this._caps.vertexArrayObject = true;
  12137. }
  12138. else {
  12139. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12140. if (vertexArrayObjectExtension != null) {
  12141. this._caps.vertexArrayObject = true;
  12142. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12143. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12144. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12145. }
  12146. else {
  12147. this._caps.vertexArrayObject = false;
  12148. }
  12149. }
  12150. // Instances count
  12151. if (this._webGLVersion > 1) {
  12152. this._caps.instancedArrays = true;
  12153. }
  12154. else {
  12155. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12156. if (instanceExtension != null) {
  12157. this._caps.instancedArrays = true;
  12158. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12159. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12160. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12161. }
  12162. else {
  12163. this._caps.instancedArrays = false;
  12164. }
  12165. }
  12166. // Intelligently add supported compressed formats in order to check for.
  12167. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12168. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12169. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12170. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12171. if (this._caps.astc)
  12172. this.texturesSupported.push('-astc.ktx');
  12173. if (this._caps.s3tc)
  12174. this.texturesSupported.push('-dxt.ktx');
  12175. if (this._caps.pvrtc)
  12176. this.texturesSupported.push('-pvrtc.ktx');
  12177. if (this._caps.etc2)
  12178. this.texturesSupported.push('-etc2.ktx');
  12179. if (this._caps.etc1)
  12180. this.texturesSupported.push('-etc1.ktx');
  12181. if (this._gl.getShaderPrecisionFormat) {
  12182. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12183. if (highp) {
  12184. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12185. }
  12186. }
  12187. // Depth buffer
  12188. this.setDepthBuffer(true);
  12189. this.setDepthFunctionToLessOrEqual();
  12190. this.setDepthWrite(true);
  12191. // Texture maps
  12192. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12193. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12194. this._nextFreeTextureSlots.push(slot);
  12195. }
  12196. };
  12197. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12198. /**
  12199. * Gets version of the current webGL context
  12200. */
  12201. get: function () {
  12202. return this._webGLVersion;
  12203. },
  12204. enumerable: true,
  12205. configurable: true
  12206. });
  12207. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12208. /**
  12209. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12210. */
  12211. get: function () {
  12212. return this._isStencilEnable;
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Engine.prototype._prepareWorkingCanvas = function () {
  12218. if (this._workingCanvas) {
  12219. return;
  12220. }
  12221. this._workingCanvas = document.createElement("canvas");
  12222. var context = this._workingCanvas.getContext("2d");
  12223. if (context) {
  12224. this._workingContext = context;
  12225. }
  12226. };
  12227. /**
  12228. * Reset the texture cache to empty state
  12229. */
  12230. Engine.prototype.resetTextureCache = function () {
  12231. for (var key in this._boundTexturesCache) {
  12232. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12233. continue;
  12234. }
  12235. var boundTexture = this._boundTexturesCache[key];
  12236. if (boundTexture) {
  12237. this._removeDesignatedSlot(boundTexture);
  12238. }
  12239. this._boundTexturesCache[key] = null;
  12240. }
  12241. if (!this.disableTextureBindingOptimization) {
  12242. this._nextFreeTextureSlots = [];
  12243. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12244. this._nextFreeTextureSlots.push(slot);
  12245. }
  12246. }
  12247. this._currentTextureChannel = -1;
  12248. };
  12249. /**
  12250. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12251. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12252. * @returns true if engine is in deterministic lock step mode
  12253. */
  12254. Engine.prototype.isDeterministicLockStep = function () {
  12255. return this._deterministicLockstep;
  12256. };
  12257. /**
  12258. * Gets the max steps when engine is running in deterministic lock step
  12259. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12260. * @returns the max steps
  12261. */
  12262. Engine.prototype.getLockstepMaxSteps = function () {
  12263. return this._lockstepMaxSteps;
  12264. };
  12265. /**
  12266. * Gets an object containing information about the current webGL context
  12267. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12268. */
  12269. Engine.prototype.getGlInfo = function () {
  12270. return {
  12271. vendor: this._glVendor,
  12272. renderer: this._glRenderer,
  12273. version: this._glVersion
  12274. };
  12275. };
  12276. /**
  12277. * Gets current aspect ratio
  12278. * @param camera defines the camera to use to get the aspect ratio
  12279. * @param useScreen defines if screen size must be used (or the current render target if any)
  12280. * @returns a number defining the aspect ratio
  12281. */
  12282. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12283. if (useScreen === void 0) { useScreen = false; }
  12284. var viewport = camera.viewport;
  12285. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12286. };
  12287. /**
  12288. * Gets current screen aspect ratio
  12289. * @returns a number defining the aspect ratio
  12290. */
  12291. Engine.prototype.getScreenAspectRatio = function () {
  12292. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12293. };
  12294. /**
  12295. * Gets the current render width
  12296. * @param useScreen defines if screen size must be used (or the current render target if any)
  12297. * @returns a number defining the current render width
  12298. */
  12299. Engine.prototype.getRenderWidth = function (useScreen) {
  12300. if (useScreen === void 0) { useScreen = false; }
  12301. if (!useScreen && this._currentRenderTarget) {
  12302. return this._currentRenderTarget.width;
  12303. }
  12304. return this._gl.drawingBufferWidth;
  12305. };
  12306. /**
  12307. * Gets the current render height
  12308. * @param useScreen defines if screen size must be used (or the current render target if any)
  12309. * @returns a number defining the current render height
  12310. */
  12311. Engine.prototype.getRenderHeight = function (useScreen) {
  12312. if (useScreen === void 0) { useScreen = false; }
  12313. if (!useScreen && this._currentRenderTarget) {
  12314. return this._currentRenderTarget.height;
  12315. }
  12316. return this._gl.drawingBufferHeight;
  12317. };
  12318. /**
  12319. * Gets the HTML canvas attached with the current webGL context
  12320. * @returns a HTML canvas
  12321. */
  12322. Engine.prototype.getRenderingCanvas = function () {
  12323. return this._renderingCanvas;
  12324. };
  12325. /**
  12326. * Gets the client rect of the HTML canvas attached with the current webGL context
  12327. * @returns a client rectanglee
  12328. */
  12329. Engine.prototype.getRenderingCanvasClientRect = function () {
  12330. if (!this._renderingCanvas) {
  12331. return null;
  12332. }
  12333. return this._renderingCanvas.getBoundingClientRect();
  12334. };
  12335. /**
  12336. * Defines the hardware scaling level.
  12337. * By default the hardware scaling level is computed from the window device ratio.
  12338. * 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.
  12339. * @param level defines the level to use
  12340. */
  12341. Engine.prototype.setHardwareScalingLevel = function (level) {
  12342. this._hardwareScalingLevel = level;
  12343. this.resize();
  12344. };
  12345. /**
  12346. * Gets the current hardware scaling level.
  12347. * By default the hardware scaling level is computed from the window device ratio.
  12348. * 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.
  12349. * @returns a number indicating the current hardware scaling level
  12350. */
  12351. Engine.prototype.getHardwareScalingLevel = function () {
  12352. return this._hardwareScalingLevel;
  12353. };
  12354. /**
  12355. * Gets the list of loaded textures
  12356. * @returns an array containing all loaded textures
  12357. */
  12358. Engine.prototype.getLoadedTexturesCache = function () {
  12359. return this._internalTexturesCache;
  12360. };
  12361. /**
  12362. * Gets the object containing all engine capabilities
  12363. * @returns the EngineCapabilities object
  12364. */
  12365. Engine.prototype.getCaps = function () {
  12366. return this._caps;
  12367. };
  12368. Object.defineProperty(Engine.prototype, "drawCalls", {
  12369. /** @hidden */
  12370. get: function () {
  12371. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12372. return 0;
  12373. },
  12374. enumerable: true,
  12375. configurable: true
  12376. });
  12377. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12378. /** @hidden */
  12379. get: function () {
  12380. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12381. return null;
  12382. },
  12383. enumerable: true,
  12384. configurable: true
  12385. });
  12386. /**
  12387. * Gets the current depth function
  12388. * @returns a number defining the depth function
  12389. */
  12390. Engine.prototype.getDepthFunction = function () {
  12391. return this._depthCullingState.depthFunc;
  12392. };
  12393. /**
  12394. * Sets the current depth function
  12395. * @param depthFunc defines the function to use
  12396. */
  12397. Engine.prototype.setDepthFunction = function (depthFunc) {
  12398. this._depthCullingState.depthFunc = depthFunc;
  12399. };
  12400. /**
  12401. * Sets the current depth function to GREATER
  12402. */
  12403. Engine.prototype.setDepthFunctionToGreater = function () {
  12404. this._depthCullingState.depthFunc = this._gl.GREATER;
  12405. };
  12406. /**
  12407. * Sets the current depth function to GEQUAL
  12408. */
  12409. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12410. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12411. };
  12412. /**
  12413. * Sets the current depth function to LESS
  12414. */
  12415. Engine.prototype.setDepthFunctionToLess = function () {
  12416. this._depthCullingState.depthFunc = this._gl.LESS;
  12417. };
  12418. /**
  12419. * Sets the current depth function to LEQUAL
  12420. */
  12421. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12422. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12423. };
  12424. /**
  12425. * Gets a boolean indicating if stencil buffer is enabled
  12426. * @returns the current stencil buffer state
  12427. */
  12428. Engine.prototype.getStencilBuffer = function () {
  12429. return this._stencilState.stencilTest;
  12430. };
  12431. /**
  12432. * Enable or disable the stencil buffer
  12433. * @param enable defines if the stencil buffer must be enabled or disabled
  12434. */
  12435. Engine.prototype.setStencilBuffer = function (enable) {
  12436. this._stencilState.stencilTest = enable;
  12437. };
  12438. /**
  12439. * Gets the current stencil mask
  12440. * @returns a number defining the new stencil mask to use
  12441. */
  12442. Engine.prototype.getStencilMask = function () {
  12443. return this._stencilState.stencilMask;
  12444. };
  12445. /**
  12446. * Sets the current stencil mask
  12447. * @param mask defines the new stencil mask to use
  12448. */
  12449. Engine.prototype.setStencilMask = function (mask) {
  12450. this._stencilState.stencilMask = mask;
  12451. };
  12452. /**
  12453. * Gets the current stencil function
  12454. * @returns a number defining the stencil function to use
  12455. */
  12456. Engine.prototype.getStencilFunction = function () {
  12457. return this._stencilState.stencilFunc;
  12458. };
  12459. /**
  12460. * Gets the current stencil reference value
  12461. * @returns a number defining the stencil reference value to use
  12462. */
  12463. Engine.prototype.getStencilFunctionReference = function () {
  12464. return this._stencilState.stencilFuncRef;
  12465. };
  12466. /**
  12467. * Gets the current stencil mask
  12468. * @returns a number defining the stencil mask to use
  12469. */
  12470. Engine.prototype.getStencilFunctionMask = function () {
  12471. return this._stencilState.stencilFuncMask;
  12472. };
  12473. /**
  12474. * Sets the current stencil function
  12475. * @param stencilFunc defines the new stencil function to use
  12476. */
  12477. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12478. this._stencilState.stencilFunc = stencilFunc;
  12479. };
  12480. /**
  12481. * Sets the current stencil reference
  12482. * @param reference defines the new stencil reference to use
  12483. */
  12484. Engine.prototype.setStencilFunctionReference = function (reference) {
  12485. this._stencilState.stencilFuncRef = reference;
  12486. };
  12487. /**
  12488. * Sets the current stencil mask
  12489. * @param mask defines the new stencil mask to use
  12490. */
  12491. Engine.prototype.setStencilFunctionMask = function (mask) {
  12492. this._stencilState.stencilFuncMask = mask;
  12493. };
  12494. /**
  12495. * Gets the current stencil operation when stencil fails
  12496. * @returns a number defining stencil operation to use when stencil fails
  12497. */
  12498. Engine.prototype.getStencilOperationFail = function () {
  12499. return this._stencilState.stencilOpStencilFail;
  12500. };
  12501. /**
  12502. * Gets the current stencil operation when depth fails
  12503. * @returns a number defining stencil operation to use when depth fails
  12504. */
  12505. Engine.prototype.getStencilOperationDepthFail = function () {
  12506. return this._stencilState.stencilOpDepthFail;
  12507. };
  12508. /**
  12509. * Gets the current stencil operation when stencil passes
  12510. * @returns a number defining stencil operation to use when stencil passes
  12511. */
  12512. Engine.prototype.getStencilOperationPass = function () {
  12513. return this._stencilState.stencilOpStencilDepthPass;
  12514. };
  12515. /**
  12516. * Sets the stencil operation to use when stencil fails
  12517. * @param operation defines the stencil operation to use when stencil fails
  12518. */
  12519. Engine.prototype.setStencilOperationFail = function (operation) {
  12520. this._stencilState.stencilOpStencilFail = operation;
  12521. };
  12522. /**
  12523. * Sets the stencil operation to use when depth fails
  12524. * @param operation defines the stencil operation to use when depth fails
  12525. */
  12526. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12527. this._stencilState.stencilOpDepthFail = operation;
  12528. };
  12529. /**
  12530. * Sets the stencil operation to use when stencil passes
  12531. * @param operation defines the stencil operation to use when stencil passes
  12532. */
  12533. Engine.prototype.setStencilOperationPass = function (operation) {
  12534. this._stencilState.stencilOpStencilDepthPass = operation;
  12535. };
  12536. /**
  12537. * Sets a boolean indicating if the dithering state is enabled or disabled
  12538. * @param value defines the dithering state
  12539. */
  12540. Engine.prototype.setDitheringState = function (value) {
  12541. if (value) {
  12542. this._gl.enable(this._gl.DITHER);
  12543. }
  12544. else {
  12545. this._gl.disable(this._gl.DITHER);
  12546. }
  12547. };
  12548. /**
  12549. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12550. * @param value defines the rasterizer state
  12551. */
  12552. Engine.prototype.setRasterizerState = function (value) {
  12553. if (value) {
  12554. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12555. }
  12556. else {
  12557. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12558. }
  12559. };
  12560. /**
  12561. * stop executing a render loop function and remove it from the execution array
  12562. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12563. */
  12564. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12565. if (!renderFunction) {
  12566. this._activeRenderLoops = [];
  12567. return;
  12568. }
  12569. var index = this._activeRenderLoops.indexOf(renderFunction);
  12570. if (index >= 0) {
  12571. this._activeRenderLoops.splice(index, 1);
  12572. }
  12573. };
  12574. /** @hidden */
  12575. Engine.prototype._renderLoop = function () {
  12576. if (!this._contextWasLost) {
  12577. var shouldRender = true;
  12578. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12579. shouldRender = false;
  12580. }
  12581. if (shouldRender) {
  12582. // Start new frame
  12583. this.beginFrame();
  12584. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12585. var renderFunction = this._activeRenderLoops[index];
  12586. renderFunction();
  12587. }
  12588. // Present
  12589. this.endFrame();
  12590. }
  12591. }
  12592. if (this._activeRenderLoops.length > 0) {
  12593. // Register new frame
  12594. var requester = null;
  12595. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12596. requester = this._vrDisplay;
  12597. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12598. }
  12599. else {
  12600. this._renderingQueueLaunched = false;
  12601. }
  12602. };
  12603. /**
  12604. * Register and execute a render loop. The engine can have more than one render function
  12605. * @param renderFunction defines the function to continuously execute
  12606. */
  12607. Engine.prototype.runRenderLoop = function (renderFunction) {
  12608. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12609. return;
  12610. }
  12611. this._activeRenderLoops.push(renderFunction);
  12612. if (!this._renderingQueueLaunched) {
  12613. this._renderingQueueLaunched = true;
  12614. this._bindedRenderFunction = this._renderLoop.bind(this);
  12615. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12616. }
  12617. };
  12618. /**
  12619. * Toggle full screen mode
  12620. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12621. * @param options defines an option object to be sent to the requestFullscreen function
  12622. */
  12623. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12624. if (this.isFullscreen) {
  12625. BABYLON.Tools.ExitFullscreen();
  12626. }
  12627. else {
  12628. this._pointerLockRequested = requestPointerLock;
  12629. if (this._renderingCanvas) {
  12630. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12631. }
  12632. }
  12633. };
  12634. /**
  12635. * Clear the current render buffer or the current render target (if any is set up)
  12636. * @param color defines the color to use
  12637. * @param backBuffer defines if the back buffer must be cleared
  12638. * @param depth defines if the depth buffer must be cleared
  12639. * @param stencil defines if the stencil buffer must be cleared
  12640. */
  12641. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12642. if (stencil === void 0) { stencil = false; }
  12643. this.applyStates();
  12644. var mode = 0;
  12645. if (backBuffer && color) {
  12646. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12647. mode |= this._gl.COLOR_BUFFER_BIT;
  12648. }
  12649. if (depth) {
  12650. this._gl.clearDepth(1.0);
  12651. mode |= this._gl.DEPTH_BUFFER_BIT;
  12652. }
  12653. if (stencil) {
  12654. this._gl.clearStencil(0);
  12655. mode |= this._gl.STENCIL_BUFFER_BIT;
  12656. }
  12657. this._gl.clear(mode);
  12658. };
  12659. /**
  12660. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12661. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12662. * @param y defines the y-coordinate of the corner of the clear rectangle
  12663. * @param width defines the width of the clear rectangle
  12664. * @param height defines the height of the clear rectangle
  12665. * @param clearColor defines the clear color
  12666. */
  12667. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12668. var gl = this._gl;
  12669. // Save state
  12670. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12671. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12672. // Change state
  12673. gl.enable(gl.SCISSOR_TEST);
  12674. gl.scissor(x, y, width, height);
  12675. // Clear
  12676. this.clear(clearColor, true, true, true);
  12677. // Restore state
  12678. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12679. if (curScissor === true) {
  12680. gl.enable(gl.SCISSOR_TEST);
  12681. }
  12682. else {
  12683. gl.disable(gl.SCISSOR_TEST);
  12684. }
  12685. };
  12686. /** @hidden */
  12687. Engine.prototype._viewport = function (x, y, width, height) {
  12688. if (x !== this._viewportCached.x ||
  12689. y !== this._viewportCached.y ||
  12690. width !== this._viewportCached.z ||
  12691. height !== this._viewportCached.w) {
  12692. this._viewportCached.x = x;
  12693. this._viewportCached.y = y;
  12694. this._viewportCached.z = width;
  12695. this._viewportCached.w = height;
  12696. this._gl.viewport(x, y, width, height);
  12697. }
  12698. };
  12699. /**
  12700. * Set the WebGL's viewport
  12701. * @param viewport defines the viewport element to be used
  12702. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12703. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12704. */
  12705. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12706. var width = requiredWidth || this.getRenderWidth();
  12707. var height = requiredHeight || this.getRenderHeight();
  12708. var x = viewport.x || 0;
  12709. var y = viewport.y || 0;
  12710. this._cachedViewport = viewport;
  12711. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12712. };
  12713. /**
  12714. * Directly set the WebGL Viewport
  12715. * @param x defines the x coordinate of the viewport (in screen space)
  12716. * @param y defines the y coordinate of the viewport (in screen space)
  12717. * @param width defines the width of the viewport (in screen space)
  12718. * @param height defines the height of the viewport (in screen space)
  12719. * @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
  12720. */
  12721. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12722. var currentViewport = this._cachedViewport;
  12723. this._cachedViewport = null;
  12724. this._viewport(x, y, width, height);
  12725. return currentViewport;
  12726. };
  12727. /**
  12728. * Begin a new frame
  12729. */
  12730. Engine.prototype.beginFrame = function () {
  12731. this.onBeginFrameObservable.notifyObservers(this);
  12732. this._measureFps();
  12733. };
  12734. /**
  12735. * Enf the current frame
  12736. */
  12737. Engine.prototype.endFrame = function () {
  12738. // Force a flush in case we are using a bad OS.
  12739. if (this._badOS) {
  12740. this.flushFramebuffer();
  12741. }
  12742. // Submit frame to the vr device, if enabled
  12743. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12744. // TODO: We should only submit the frame if we read frameData successfully.
  12745. this._vrDisplay.submitFrame();
  12746. }
  12747. this.onEndFrameObservable.notifyObservers(this);
  12748. };
  12749. /**
  12750. * Resize the view according to the canvas' size
  12751. */
  12752. Engine.prototype.resize = function () {
  12753. // We're not resizing the size of the canvas while in VR mode & presenting
  12754. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12755. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12756. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12757. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12758. }
  12759. };
  12760. /**
  12761. * Force a specific size of the canvas
  12762. * @param width defines the new canvas' width
  12763. * @param height defines the new canvas' height
  12764. */
  12765. Engine.prototype.setSize = function (width, height) {
  12766. if (!this._renderingCanvas) {
  12767. return;
  12768. }
  12769. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12770. return;
  12771. }
  12772. this._renderingCanvas.width = width;
  12773. this._renderingCanvas.height = height;
  12774. for (var index = 0; index < this.scenes.length; index++) {
  12775. var scene = this.scenes[index];
  12776. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12777. var cam = scene.cameras[camIndex];
  12778. cam._currentRenderId = 0;
  12779. }
  12780. }
  12781. if (this.onResizeObservable.hasObservers) {
  12782. this.onResizeObservable.notifyObservers(this);
  12783. }
  12784. };
  12785. // WebVR functions
  12786. /**
  12787. * Gets a boolean indicating if a webVR device was detected
  12788. * @returns true if a webVR device was detected
  12789. */
  12790. Engine.prototype.isVRDevicePresent = function () {
  12791. return !!this._vrDisplay;
  12792. };
  12793. /**
  12794. * Gets the current webVR device
  12795. * @returns the current webVR device (or null)
  12796. */
  12797. Engine.prototype.getVRDevice = function () {
  12798. return this._vrDisplay;
  12799. };
  12800. /**
  12801. * Initializes a webVR display and starts listening to display change events
  12802. * The onVRDisplayChangedObservable will be notified upon these changes
  12803. * @returns The onVRDisplayChangedObservable
  12804. */
  12805. Engine.prototype.initWebVR = function () {
  12806. this.initWebVRAsync();
  12807. return this.onVRDisplayChangedObservable;
  12808. };
  12809. /**
  12810. * Initializes a webVR display and starts listening to display change events
  12811. * The onVRDisplayChangedObservable will be notified upon these changes
  12812. * @returns A promise containing a VRDisplay and if vr is supported
  12813. */
  12814. Engine.prototype.initWebVRAsync = function () {
  12815. var _this = this;
  12816. var notifyObservers = function () {
  12817. var eventArgs = {
  12818. vrDisplay: _this._vrDisplay,
  12819. vrSupported: _this._vrSupported
  12820. };
  12821. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12822. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12823. };
  12824. if (!this._onVrDisplayConnect) {
  12825. this._onVrDisplayConnect = function (event) {
  12826. _this._vrDisplay = event.display;
  12827. notifyObservers();
  12828. };
  12829. this._onVrDisplayDisconnect = function () {
  12830. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12831. _this._vrDisplay = undefined;
  12832. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12833. notifyObservers();
  12834. };
  12835. this._onVrDisplayPresentChange = function () {
  12836. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12837. };
  12838. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12839. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12840. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12841. }
  12842. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12843. this._webVRInitPromise.then(notifyObservers);
  12844. return this._webVRInitPromise;
  12845. };
  12846. /**
  12847. * Call this function to switch to webVR mode
  12848. * Will do nothing if webVR is not supported or if there is no webVR device
  12849. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12850. */
  12851. Engine.prototype.enableVR = function () {
  12852. var _this = this;
  12853. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12854. var onResolved = function () {
  12855. _this.onVRRequestPresentComplete.notifyObservers(true);
  12856. _this._onVRFullScreenTriggered();
  12857. };
  12858. var onRejected = function () {
  12859. _this.onVRRequestPresentComplete.notifyObservers(false);
  12860. };
  12861. this.onVRRequestPresentStart.notifyObservers(this);
  12862. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12863. }
  12864. };
  12865. /**
  12866. * Call this function to leave webVR mode
  12867. * Will do nothing if webVR is not supported or if there is no webVR device
  12868. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12869. */
  12870. Engine.prototype.disableVR = function () {
  12871. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12872. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12873. }
  12874. };
  12875. Engine.prototype._getVRDisplaysAsync = function () {
  12876. var _this = this;
  12877. return new Promise(function (res, rej) {
  12878. if (navigator.getVRDisplays) {
  12879. navigator.getVRDisplays().then(function (devices) {
  12880. _this._vrSupported = true;
  12881. // note that devices may actually be an empty array. This is fine;
  12882. // we expect this._vrDisplay to be undefined in this case.
  12883. _this._vrDisplay = devices[0];
  12884. res({
  12885. vrDisplay: _this._vrDisplay,
  12886. vrSupported: _this._vrSupported
  12887. });
  12888. });
  12889. }
  12890. else {
  12891. _this._vrDisplay = undefined;
  12892. _this._vrSupported = false;
  12893. res({
  12894. vrDisplay: _this._vrDisplay,
  12895. vrSupported: _this._vrSupported
  12896. });
  12897. }
  12898. });
  12899. };
  12900. /**
  12901. * Binds the frame buffer to the specified texture.
  12902. * @param texture The texture to render to or null for the default canvas
  12903. * @param faceIndex The face of the texture to render to in case of cube texture
  12904. * @param requiredWidth The width of the target to render to
  12905. * @param requiredHeight The height of the target to render to
  12906. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12907. * @param depthStencilTexture The depth stencil texture to use to render
  12908. * @param lodLevel defines le lod level to bind to the frame buffer
  12909. */
  12910. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12911. if (lodLevel === void 0) { lodLevel = 0; }
  12912. if (this._currentRenderTarget) {
  12913. this.unBindFramebuffer(this._currentRenderTarget);
  12914. }
  12915. this._currentRenderTarget = texture;
  12916. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12917. var gl = this._gl;
  12918. if (texture.isCube) {
  12919. if (faceIndex === undefined) {
  12920. faceIndex = 0;
  12921. }
  12922. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12923. if (depthStencilTexture) {
  12924. if (depthStencilTexture._generateStencilBuffer) {
  12925. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12926. }
  12927. else {
  12928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12929. }
  12930. }
  12931. }
  12932. if (this._cachedViewport && !forceFullscreenViewport) {
  12933. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12934. }
  12935. else {
  12936. if (!requiredWidth) {
  12937. requiredWidth = texture.width;
  12938. if (lodLevel) {
  12939. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12940. }
  12941. }
  12942. if (!requiredHeight) {
  12943. requiredHeight = texture.height;
  12944. if (lodLevel) {
  12945. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12946. }
  12947. }
  12948. this._viewport(0, 0, requiredWidth, requiredHeight);
  12949. }
  12950. this.wipeCaches();
  12951. };
  12952. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12953. if (this._currentFramebuffer !== framebuffer) {
  12954. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12955. this._currentFramebuffer = framebuffer;
  12956. }
  12957. };
  12958. /**
  12959. * Unbind the current render target texture from the webGL context
  12960. * @param texture defines the render target texture to unbind
  12961. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12962. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12963. */
  12964. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12965. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12966. this._currentRenderTarget = null;
  12967. // If MSAA, we need to bitblt back to main texture
  12968. var gl = this._gl;
  12969. if (texture._MSAAFramebuffer) {
  12970. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12971. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12972. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12973. }
  12974. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12975. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12976. gl.generateMipmap(gl.TEXTURE_2D);
  12977. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12978. }
  12979. if (onBeforeUnbind) {
  12980. if (texture._MSAAFramebuffer) {
  12981. // Bind the correct framebuffer
  12982. this.bindUnboundFramebuffer(texture._framebuffer);
  12983. }
  12984. onBeforeUnbind();
  12985. }
  12986. this.bindUnboundFramebuffer(null);
  12987. };
  12988. /**
  12989. * Unbind a list of render target textures from the webGL context
  12990. * This is used only when drawBuffer extension or webGL2 are active
  12991. * @param textures defines the render target textures to unbind
  12992. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12993. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12994. */
  12995. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12996. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12997. this._currentRenderTarget = null;
  12998. // If MSAA, we need to bitblt back to main texture
  12999. var gl = this._gl;
  13000. if (textures[0]._MSAAFramebuffer) {
  13001. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13002. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13003. var attachments = textures[0]._attachments;
  13004. if (!attachments) {
  13005. attachments = new Array(textures.length);
  13006. textures[0]._attachments = attachments;
  13007. }
  13008. for (var i = 0; i < textures.length; i++) {
  13009. var texture = textures[i];
  13010. for (var j = 0; j < attachments.length; j++) {
  13011. attachments[j] = gl.NONE;
  13012. }
  13013. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13014. gl.readBuffer(attachments[i]);
  13015. gl.drawBuffers(attachments);
  13016. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13017. }
  13018. for (var i = 0; i < attachments.length; i++) {
  13019. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13020. }
  13021. gl.drawBuffers(attachments);
  13022. }
  13023. for (var i = 0; i < textures.length; i++) {
  13024. var texture = textures[i];
  13025. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13026. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13027. gl.generateMipmap(gl.TEXTURE_2D);
  13028. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13029. }
  13030. }
  13031. if (onBeforeUnbind) {
  13032. if (textures[0]._MSAAFramebuffer) {
  13033. // Bind the correct framebuffer
  13034. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13035. }
  13036. onBeforeUnbind();
  13037. }
  13038. this.bindUnboundFramebuffer(null);
  13039. };
  13040. /**
  13041. * Force the mipmap generation for the given render target texture
  13042. * @param texture defines the render target texture to use
  13043. */
  13044. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13045. if (texture.generateMipMaps) {
  13046. var gl = this._gl;
  13047. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13048. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13049. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13050. }
  13051. };
  13052. /**
  13053. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13054. */
  13055. Engine.prototype.flushFramebuffer = function () {
  13056. this._gl.flush();
  13057. };
  13058. /**
  13059. * Unbind the current render target and bind the default framebuffer
  13060. */
  13061. Engine.prototype.restoreDefaultFramebuffer = function () {
  13062. if (this._currentRenderTarget) {
  13063. this.unBindFramebuffer(this._currentRenderTarget);
  13064. }
  13065. else {
  13066. this.bindUnboundFramebuffer(null);
  13067. }
  13068. if (this._cachedViewport) {
  13069. this.setViewport(this._cachedViewport);
  13070. }
  13071. this.wipeCaches();
  13072. };
  13073. // UBOs
  13074. /**
  13075. * Create an uniform buffer
  13076. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13077. * @param elements defines the content of the uniform buffer
  13078. * @returns the webGL uniform buffer
  13079. */
  13080. Engine.prototype.createUniformBuffer = function (elements) {
  13081. var ubo = this._gl.createBuffer();
  13082. if (!ubo) {
  13083. throw new Error("Unable to create uniform buffer");
  13084. }
  13085. this.bindUniformBuffer(ubo);
  13086. if (elements instanceof Float32Array) {
  13087. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13088. }
  13089. else {
  13090. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13091. }
  13092. this.bindUniformBuffer(null);
  13093. ubo.references = 1;
  13094. return ubo;
  13095. };
  13096. /**
  13097. * Create a dynamic uniform buffer
  13098. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13099. * @param elements defines the content of the uniform buffer
  13100. * @returns the webGL uniform buffer
  13101. */
  13102. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13103. var ubo = this._gl.createBuffer();
  13104. if (!ubo) {
  13105. throw new Error("Unable to create dynamic uniform buffer");
  13106. }
  13107. this.bindUniformBuffer(ubo);
  13108. if (elements instanceof Float32Array) {
  13109. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13110. }
  13111. else {
  13112. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13113. }
  13114. this.bindUniformBuffer(null);
  13115. ubo.references = 1;
  13116. return ubo;
  13117. };
  13118. /**
  13119. * Update an existing uniform buffer
  13120. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13121. * @param uniformBuffer defines the target uniform buffer
  13122. * @param elements defines the content to update
  13123. * @param offset defines the offset in the uniform buffer where update should start
  13124. * @param count defines the size of the data to update
  13125. */
  13126. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13127. this.bindUniformBuffer(uniformBuffer);
  13128. if (offset === undefined) {
  13129. offset = 0;
  13130. }
  13131. if (count === undefined) {
  13132. if (elements instanceof Float32Array) {
  13133. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13134. }
  13135. else {
  13136. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13137. }
  13138. }
  13139. else {
  13140. if (elements instanceof Float32Array) {
  13141. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13142. }
  13143. else {
  13144. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13145. }
  13146. }
  13147. this.bindUniformBuffer(null);
  13148. };
  13149. // VBOs
  13150. Engine.prototype._resetVertexBufferBinding = function () {
  13151. this.bindArrayBuffer(null);
  13152. this._cachedVertexBuffers = null;
  13153. };
  13154. /**
  13155. * Creates a vertex buffer
  13156. * @param data the data for the vertex buffer
  13157. * @returns the new WebGL static buffer
  13158. */
  13159. Engine.prototype.createVertexBuffer = function (data) {
  13160. var vbo = this._gl.createBuffer();
  13161. if (!vbo) {
  13162. throw new Error("Unable to create vertex buffer");
  13163. }
  13164. this.bindArrayBuffer(vbo);
  13165. if (data instanceof Array) {
  13166. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13167. }
  13168. else {
  13169. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13170. }
  13171. this._resetVertexBufferBinding();
  13172. vbo.references = 1;
  13173. return vbo;
  13174. };
  13175. /**
  13176. * Creates a dynamic vertex buffer
  13177. * @param data the data for the dynamic vertex buffer
  13178. * @returns the new WebGL dynamic buffer
  13179. */
  13180. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13181. var vbo = this._gl.createBuffer();
  13182. if (!vbo) {
  13183. throw new Error("Unable to create dynamic vertex buffer");
  13184. }
  13185. this.bindArrayBuffer(vbo);
  13186. if (data instanceof Array) {
  13187. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13188. }
  13189. else {
  13190. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13191. }
  13192. this._resetVertexBufferBinding();
  13193. vbo.references = 1;
  13194. return vbo;
  13195. };
  13196. /**
  13197. * Update a dynamic index buffer
  13198. * @param indexBuffer defines the target index buffer
  13199. * @param indices defines the data to update
  13200. * @param offset defines the offset in the target index buffer where update should start
  13201. */
  13202. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13203. if (offset === void 0) { offset = 0; }
  13204. // Force cache update
  13205. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13206. this.bindIndexBuffer(indexBuffer);
  13207. var arrayBuffer;
  13208. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13209. arrayBuffer = indices;
  13210. }
  13211. else {
  13212. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13213. }
  13214. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13215. this._resetIndexBufferBinding();
  13216. };
  13217. /**
  13218. * Updates a dynamic vertex buffer.
  13219. * @param vertexBuffer the vertex buffer to update
  13220. * @param data the data used to update the vertex buffer
  13221. * @param byteOffset the byte offset of the data
  13222. * @param byteLength the byte length of the data
  13223. */
  13224. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13225. this.bindArrayBuffer(vertexBuffer);
  13226. if (byteOffset === undefined) {
  13227. byteOffset = 0;
  13228. }
  13229. if (byteLength === undefined) {
  13230. if (data instanceof Array) {
  13231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13232. }
  13233. else {
  13234. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13235. }
  13236. }
  13237. else {
  13238. if (data instanceof Array) {
  13239. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13240. }
  13241. else {
  13242. if (data instanceof ArrayBuffer) {
  13243. data = new Uint8Array(data, byteOffset, byteLength);
  13244. }
  13245. else {
  13246. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13247. }
  13248. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13249. }
  13250. }
  13251. this._resetVertexBufferBinding();
  13252. };
  13253. Engine.prototype._resetIndexBufferBinding = function () {
  13254. this.bindIndexBuffer(null);
  13255. this._cachedIndexBuffer = null;
  13256. };
  13257. /**
  13258. * Creates a new index buffer
  13259. * @param indices defines the content of the index buffer
  13260. * @param updatable defines if the index buffer must be updatable
  13261. * @returns a new webGL buffer
  13262. */
  13263. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13264. var vbo = this._gl.createBuffer();
  13265. if (!vbo) {
  13266. throw new Error("Unable to create index buffer");
  13267. }
  13268. this.bindIndexBuffer(vbo);
  13269. // Check for 32 bits indices
  13270. var arrayBuffer;
  13271. var need32Bits = false;
  13272. if (indices instanceof Uint16Array) {
  13273. arrayBuffer = indices;
  13274. }
  13275. else {
  13276. //check 32 bit support
  13277. if (this._caps.uintIndices) {
  13278. if (indices instanceof Uint32Array) {
  13279. arrayBuffer = indices;
  13280. need32Bits = true;
  13281. }
  13282. else {
  13283. //number[] or Int32Array, check if 32 bit is necessary
  13284. for (var index = 0; index < indices.length; index++) {
  13285. if (indices[index] > 65535) {
  13286. need32Bits = true;
  13287. break;
  13288. }
  13289. }
  13290. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13291. }
  13292. }
  13293. else {
  13294. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13295. arrayBuffer = new Uint16Array(indices);
  13296. }
  13297. }
  13298. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13299. this._resetIndexBufferBinding();
  13300. vbo.references = 1;
  13301. vbo.is32Bits = need32Bits;
  13302. return vbo;
  13303. };
  13304. /**
  13305. * Bind a webGL buffer to the webGL context
  13306. * @param buffer defines the buffer to bind
  13307. */
  13308. Engine.prototype.bindArrayBuffer = function (buffer) {
  13309. if (!this._vaoRecordInProgress) {
  13310. this._unbindVertexArrayObject();
  13311. }
  13312. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13313. };
  13314. /**
  13315. * Bind an uniform buffer to the current webGL context
  13316. * @param buffer defines the buffer to bind
  13317. */
  13318. Engine.prototype.bindUniformBuffer = function (buffer) {
  13319. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13320. };
  13321. /**
  13322. * Bind a buffer to the current webGL context at a given location
  13323. * @param buffer defines the buffer to bind
  13324. * @param location defines the index where to bind the buffer
  13325. */
  13326. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13327. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13328. };
  13329. /**
  13330. * Bind a specific block at a given index in a specific shader program
  13331. * @param shaderProgram defines the shader program
  13332. * @param blockName defines the block name
  13333. * @param index defines the index where to bind the block
  13334. */
  13335. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13336. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13337. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13338. };
  13339. ;
  13340. Engine.prototype.bindIndexBuffer = function (buffer) {
  13341. if (!this._vaoRecordInProgress) {
  13342. this._unbindVertexArrayObject();
  13343. }
  13344. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13345. };
  13346. Engine.prototype.bindBuffer = function (buffer, target) {
  13347. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13348. this._gl.bindBuffer(target, buffer);
  13349. this._currentBoundBuffer[target] = buffer;
  13350. }
  13351. };
  13352. /**
  13353. * update the bound buffer with the given data
  13354. * @param data defines the data to update
  13355. */
  13356. Engine.prototype.updateArrayBuffer = function (data) {
  13357. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13358. };
  13359. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13360. var pointer = this._currentBufferPointers[indx];
  13361. var changed = false;
  13362. if (!pointer.active) {
  13363. changed = true;
  13364. pointer.active = true;
  13365. pointer.index = indx;
  13366. pointer.size = size;
  13367. pointer.type = type;
  13368. pointer.normalized = normalized;
  13369. pointer.stride = stride;
  13370. pointer.offset = offset;
  13371. pointer.buffer = buffer;
  13372. }
  13373. else {
  13374. if (pointer.buffer !== buffer) {
  13375. pointer.buffer = buffer;
  13376. changed = true;
  13377. }
  13378. if (pointer.size !== size) {
  13379. pointer.size = size;
  13380. changed = true;
  13381. }
  13382. if (pointer.type !== type) {
  13383. pointer.type = type;
  13384. changed = true;
  13385. }
  13386. if (pointer.normalized !== normalized) {
  13387. pointer.normalized = normalized;
  13388. changed = true;
  13389. }
  13390. if (pointer.stride !== stride) {
  13391. pointer.stride = stride;
  13392. changed = true;
  13393. }
  13394. if (pointer.offset !== offset) {
  13395. pointer.offset = offset;
  13396. changed = true;
  13397. }
  13398. }
  13399. if (changed || this._vaoRecordInProgress) {
  13400. this.bindArrayBuffer(buffer);
  13401. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13402. }
  13403. };
  13404. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13405. if (indexBuffer == null) {
  13406. return;
  13407. }
  13408. if (this._cachedIndexBuffer !== indexBuffer) {
  13409. this._cachedIndexBuffer = indexBuffer;
  13410. this.bindIndexBuffer(indexBuffer);
  13411. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13412. }
  13413. };
  13414. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13415. var attributes = effect.getAttributesNames();
  13416. if (!this._vaoRecordInProgress) {
  13417. this._unbindVertexArrayObject();
  13418. }
  13419. this.unbindAllAttributes();
  13420. for (var index = 0; index < attributes.length; index++) {
  13421. var order = effect.getAttributeLocation(index);
  13422. if (order >= 0) {
  13423. var vertexBuffer = vertexBuffers[attributes[index]];
  13424. if (!vertexBuffer) {
  13425. continue;
  13426. }
  13427. this._gl.enableVertexAttribArray(order);
  13428. if (!this._vaoRecordInProgress) {
  13429. this._vertexAttribArraysEnabled[order] = true;
  13430. }
  13431. var buffer = vertexBuffer.getBuffer();
  13432. if (buffer) {
  13433. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13434. if (vertexBuffer.getIsInstanced()) {
  13435. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13436. if (!this._vaoRecordInProgress) {
  13437. this._currentInstanceLocations.push(order);
  13438. this._currentInstanceBuffers.push(buffer);
  13439. }
  13440. }
  13441. }
  13442. }
  13443. }
  13444. };
  13445. /**
  13446. * Records a vertex array object
  13447. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13448. * @param vertexBuffers defines the list of vertex buffers to store
  13449. * @param indexBuffer defines the index buffer to store
  13450. * @param effect defines the effect to store
  13451. * @returns the new vertex array object
  13452. */
  13453. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13454. var vao = this._gl.createVertexArray();
  13455. this._vaoRecordInProgress = true;
  13456. this._gl.bindVertexArray(vao);
  13457. this._mustWipeVertexAttributes = true;
  13458. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13459. this.bindIndexBuffer(indexBuffer);
  13460. this._vaoRecordInProgress = false;
  13461. this._gl.bindVertexArray(null);
  13462. return vao;
  13463. };
  13464. /**
  13465. * Bind a specific vertex array object
  13466. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13467. * @param vertexArrayObject defines the vertex array object to bind
  13468. * @param indexBuffer defines the index buffer to bind
  13469. */
  13470. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13471. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13472. this._cachedVertexArrayObject = vertexArrayObject;
  13473. this._gl.bindVertexArray(vertexArrayObject);
  13474. this._cachedVertexBuffers = null;
  13475. this._cachedIndexBuffer = null;
  13476. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13477. this._mustWipeVertexAttributes = true;
  13478. }
  13479. };
  13480. /**
  13481. * Bind webGl buffers directly to the webGL context
  13482. * @param vertexBuffer defines the vertex buffer to bind
  13483. * @param indexBuffer defines the index buffer to bind
  13484. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13485. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13486. * @param effect defines the effect associated with the vertex buffer
  13487. */
  13488. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13489. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13490. this._cachedVertexBuffers = vertexBuffer;
  13491. this._cachedEffectForVertexBuffers = effect;
  13492. var attributesCount = effect.getAttributesCount();
  13493. this._unbindVertexArrayObject();
  13494. this.unbindAllAttributes();
  13495. var offset = 0;
  13496. for (var index = 0; index < attributesCount; index++) {
  13497. if (index < vertexDeclaration.length) {
  13498. var order = effect.getAttributeLocation(index);
  13499. if (order >= 0) {
  13500. this._gl.enableVertexAttribArray(order);
  13501. this._vertexAttribArraysEnabled[order] = true;
  13502. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13503. }
  13504. offset += vertexDeclaration[index] * 4;
  13505. }
  13506. }
  13507. }
  13508. this._bindIndexBufferWithCache(indexBuffer);
  13509. };
  13510. Engine.prototype._unbindVertexArrayObject = function () {
  13511. if (!this._cachedVertexArrayObject) {
  13512. return;
  13513. }
  13514. this._cachedVertexArrayObject = null;
  13515. this._gl.bindVertexArray(null);
  13516. };
  13517. /**
  13518. * Bind a list of vertex buffers to the webGL context
  13519. * @param vertexBuffers defines the list of vertex buffers to bind
  13520. * @param indexBuffer defines the index buffer to bind
  13521. * @param effect defines the effect associated with the vertex buffers
  13522. */
  13523. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13524. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13525. this._cachedVertexBuffers = vertexBuffers;
  13526. this._cachedEffectForVertexBuffers = effect;
  13527. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13528. }
  13529. this._bindIndexBufferWithCache(indexBuffer);
  13530. };
  13531. /**
  13532. * Unbind all instance attributes
  13533. */
  13534. Engine.prototype.unbindInstanceAttributes = function () {
  13535. var boundBuffer;
  13536. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13537. var instancesBuffer = this._currentInstanceBuffers[i];
  13538. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13539. boundBuffer = instancesBuffer;
  13540. this.bindArrayBuffer(instancesBuffer);
  13541. }
  13542. var offsetLocation = this._currentInstanceLocations[i];
  13543. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13544. }
  13545. this._currentInstanceBuffers.length = 0;
  13546. this._currentInstanceLocations.length = 0;
  13547. };
  13548. /**
  13549. * Release and free the memory of a vertex array object
  13550. * @param vao defines the vertex array object to delete
  13551. */
  13552. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13553. this._gl.deleteVertexArray(vao);
  13554. };
  13555. /** @hidden */
  13556. Engine.prototype._releaseBuffer = function (buffer) {
  13557. buffer.references--;
  13558. if (buffer.references === 0) {
  13559. this._gl.deleteBuffer(buffer);
  13560. return true;
  13561. }
  13562. return false;
  13563. };
  13564. /**
  13565. * Creates a webGL buffer to use with instanciation
  13566. * @param capacity defines the size of the buffer
  13567. * @returns the webGL buffer
  13568. */
  13569. Engine.prototype.createInstancesBuffer = function (capacity) {
  13570. var buffer = this._gl.createBuffer();
  13571. if (!buffer) {
  13572. throw new Error("Unable to create instance buffer");
  13573. }
  13574. buffer.capacity = capacity;
  13575. this.bindArrayBuffer(buffer);
  13576. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13577. return buffer;
  13578. };
  13579. /**
  13580. * Delete a webGL buffer used with instanciation
  13581. * @param buffer defines the webGL buffer to delete
  13582. */
  13583. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13584. this._gl.deleteBuffer(buffer);
  13585. };
  13586. /**
  13587. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13588. * @param instancesBuffer defines the webGL buffer to update and bind
  13589. * @param data defines the data to store in the buffer
  13590. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13591. */
  13592. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13593. this.bindArrayBuffer(instancesBuffer);
  13594. if (data) {
  13595. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13596. }
  13597. if (offsetLocations[0].index !== undefined) {
  13598. var stride = 0;
  13599. for (var i = 0; i < offsetLocations.length; i++) {
  13600. var ai = offsetLocations[i];
  13601. stride += ai.attributeSize * 4;
  13602. }
  13603. for (var i = 0; i < offsetLocations.length; i++) {
  13604. var ai = offsetLocations[i];
  13605. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13606. this._gl.enableVertexAttribArray(ai.index);
  13607. this._vertexAttribArraysEnabled[ai.index] = true;
  13608. }
  13609. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13610. this._gl.vertexAttribDivisor(ai.index, 1);
  13611. this._currentInstanceLocations.push(ai.index);
  13612. this._currentInstanceBuffers.push(instancesBuffer);
  13613. }
  13614. }
  13615. else {
  13616. for (var index = 0; index < 4; index++) {
  13617. var offsetLocation = offsetLocations[index];
  13618. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13619. this._gl.enableVertexAttribArray(offsetLocation);
  13620. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13621. }
  13622. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13623. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13624. this._currentInstanceLocations.push(offsetLocation);
  13625. this._currentInstanceBuffers.push(instancesBuffer);
  13626. }
  13627. }
  13628. };
  13629. /**
  13630. * Apply all cached states (depth, culling, stencil and alpha)
  13631. */
  13632. Engine.prototype.applyStates = function () {
  13633. this._depthCullingState.apply(this._gl);
  13634. this._stencilState.apply(this._gl);
  13635. this._alphaState.apply(this._gl);
  13636. };
  13637. /**
  13638. * Send a draw order
  13639. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13640. * @param indexStart defines the starting index
  13641. * @param indexCount defines the number of index to draw
  13642. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13643. */
  13644. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13645. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13646. };
  13647. /**
  13648. * Draw a list of points
  13649. * @param verticesStart defines the index of first vertex to draw
  13650. * @param verticesCount defines the count of vertices to draw
  13651. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13652. */
  13653. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13654. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13655. };
  13656. /**
  13657. * Draw a list of unindexed primitives
  13658. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13659. * @param verticesStart defines the index of first vertex to draw
  13660. * @param verticesCount defines the count of vertices to draw
  13661. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13662. */
  13663. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13664. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13665. };
  13666. /**
  13667. * Draw a list of indexed primitives
  13668. * @param fillMode defines the primitive to use
  13669. * @param indexStart defines the starting index
  13670. * @param indexCount defines the number of index to draw
  13671. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13672. */
  13673. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13674. // Apply states
  13675. this.applyStates();
  13676. this._drawCalls.addCount(1, false);
  13677. // Render
  13678. var drawMode = this._drawMode(fillMode);
  13679. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13680. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13681. if (instancesCount) {
  13682. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13683. }
  13684. else {
  13685. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13686. }
  13687. };
  13688. /**
  13689. * Draw a list of unindexed primitives
  13690. * @param fillMode defines the primitive to use
  13691. * @param verticesStart defines the index of first vertex to draw
  13692. * @param verticesCount defines the count of vertices to draw
  13693. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13694. */
  13695. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13696. // Apply states
  13697. this.applyStates();
  13698. this._drawCalls.addCount(1, false);
  13699. var drawMode = this._drawMode(fillMode);
  13700. if (instancesCount) {
  13701. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13702. }
  13703. else {
  13704. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13705. }
  13706. };
  13707. Engine.prototype._drawMode = function (fillMode) {
  13708. switch (fillMode) {
  13709. // Triangle views
  13710. case BABYLON.Material.TriangleFillMode:
  13711. return this._gl.TRIANGLES;
  13712. case BABYLON.Material.PointFillMode:
  13713. return this._gl.POINTS;
  13714. case BABYLON.Material.WireFrameFillMode:
  13715. return this._gl.LINES;
  13716. // Draw modes
  13717. case BABYLON.Material.PointListDrawMode:
  13718. return this._gl.POINTS;
  13719. case BABYLON.Material.LineListDrawMode:
  13720. return this._gl.LINES;
  13721. case BABYLON.Material.LineLoopDrawMode:
  13722. return this._gl.LINE_LOOP;
  13723. case BABYLON.Material.LineStripDrawMode:
  13724. return this._gl.LINE_STRIP;
  13725. case BABYLON.Material.TriangleStripDrawMode:
  13726. return this._gl.TRIANGLE_STRIP;
  13727. case BABYLON.Material.TriangleFanDrawMode:
  13728. return this._gl.TRIANGLE_FAN;
  13729. default:
  13730. return this._gl.TRIANGLES;
  13731. }
  13732. };
  13733. // Shaders
  13734. /** @hidden */
  13735. Engine.prototype._releaseEffect = function (effect) {
  13736. if (this._compiledEffects[effect._key]) {
  13737. delete this._compiledEffects[effect._key];
  13738. this._deleteProgram(effect.getProgram());
  13739. }
  13740. };
  13741. /** @hidden */
  13742. Engine.prototype._deleteProgram = function (program) {
  13743. if (program) {
  13744. program.__SPECTOR_rebuildProgram = null;
  13745. if (program.transformFeedback) {
  13746. this.deleteTransformFeedback(program.transformFeedback);
  13747. program.transformFeedback = null;
  13748. }
  13749. this._gl.deleteProgram(program);
  13750. }
  13751. };
  13752. /**
  13753. * Create a new effect (used to store vertex/fragment shaders)
  13754. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13755. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13756. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13757. * @param samplers defines an array of string used to represent textures
  13758. * @param defines defines the string containing the defines to use to compile the shaders
  13759. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13760. * @param onCompiled defines a function to call when the effect creation is successful
  13761. * @param onError defines a function to call when the effect creation has failed
  13762. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13763. * @returns the new Effect
  13764. */
  13765. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13766. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13767. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13768. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13769. if (this._compiledEffects[name]) {
  13770. var compiledEffect = this._compiledEffects[name];
  13771. if (onCompiled && compiledEffect.isReady()) {
  13772. onCompiled(compiledEffect);
  13773. }
  13774. return compiledEffect;
  13775. }
  13776. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13777. effect._key = name;
  13778. this._compiledEffects[name] = effect;
  13779. return effect;
  13780. };
  13781. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13782. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13783. };
  13784. ;
  13785. Engine.prototype._compileRawShader = function (source, type) {
  13786. var gl = this._gl;
  13787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13788. gl.shaderSource(shader, source);
  13789. gl.compileShader(shader);
  13790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13791. var log = gl.getShaderInfoLog(shader);
  13792. if (log) {
  13793. throw new Error(log);
  13794. }
  13795. }
  13796. if (!shader) {
  13797. throw new Error("Something went wrong while compile the shader.");
  13798. }
  13799. return shader;
  13800. };
  13801. ;
  13802. /**
  13803. * Directly creates a webGL program
  13804. * @param vertexCode defines the vertex shader code to use
  13805. * @param fragmentCode defines the fragment shader code to use
  13806. * @param context defines the webGL context to use (if not set, the current one will be used)
  13807. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13808. * @returns the new webGL program
  13809. */
  13810. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13811. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13812. context = context || this._gl;
  13813. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13814. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13815. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13816. };
  13817. /**
  13818. * Creates a webGL program
  13819. * @param vertexCode defines the vertex shader code to use
  13820. * @param fragmentCode defines the fragment shader code to use
  13821. * @param defines defines the string containing the defines to use to compile the shaders
  13822. * @param context defines the webGL context to use (if not set, the current one will be used)
  13823. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13824. * @returns the new webGL program
  13825. */
  13826. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13827. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13828. context = context || this._gl;
  13829. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13830. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13831. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13832. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13833. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13834. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13835. return program;
  13836. };
  13837. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13838. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13839. var shaderProgram = context.createProgram();
  13840. if (!shaderProgram) {
  13841. throw new Error("Unable to create program");
  13842. }
  13843. context.attachShader(shaderProgram, vertexShader);
  13844. context.attachShader(shaderProgram, fragmentShader);
  13845. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13846. var transformFeedback = this.createTransformFeedback();
  13847. this.bindTransformFeedback(transformFeedback);
  13848. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13849. shaderProgram.transformFeedback = transformFeedback;
  13850. }
  13851. context.linkProgram(shaderProgram);
  13852. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13853. this.bindTransformFeedback(null);
  13854. }
  13855. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13856. if (!linked) {
  13857. var error = context.getProgramInfoLog(shaderProgram);
  13858. if (error) {
  13859. throw new Error(error);
  13860. }
  13861. }
  13862. if (this.validateShaderPrograms) {
  13863. context.validateProgram(shaderProgram);
  13864. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13865. if (!validated) {
  13866. var error = context.getProgramInfoLog(shaderProgram);
  13867. if (error) {
  13868. throw new Error(error);
  13869. }
  13870. }
  13871. }
  13872. context.deleteShader(vertexShader);
  13873. context.deleteShader(fragmentShader);
  13874. return shaderProgram;
  13875. };
  13876. /**
  13877. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13878. * @param shaderProgram defines the webGL program to use
  13879. * @param uniformsNames defines the list of uniform names
  13880. * @returns an array of webGL uniform locations
  13881. */
  13882. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13883. var results = new Array();
  13884. for (var index = 0; index < uniformsNames.length; index++) {
  13885. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13886. }
  13887. return results;
  13888. };
  13889. /**
  13890. * Gets the lsit of active attributes for a given webGL program
  13891. * @param shaderProgram defines the webGL program to use
  13892. * @param attributesNames defines the list of attribute names to get
  13893. * @returns an array of indices indicating the offset of each attribute
  13894. */
  13895. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13896. var results = [];
  13897. for (var index = 0; index < attributesNames.length; index++) {
  13898. try {
  13899. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13900. }
  13901. catch (e) {
  13902. results.push(-1);
  13903. }
  13904. }
  13905. return results;
  13906. };
  13907. /**
  13908. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13909. * @param effect defines the effect to activate
  13910. */
  13911. Engine.prototype.enableEffect = function (effect) {
  13912. if (!effect || effect === this._currentEffect) {
  13913. return;
  13914. }
  13915. // Use program
  13916. this.bindSamplers(effect);
  13917. this._currentEffect = effect;
  13918. if (effect.onBind) {
  13919. effect.onBind(effect);
  13920. }
  13921. if (effect._onBindObservable) {
  13922. effect._onBindObservable.notifyObservers(effect);
  13923. }
  13924. };
  13925. /**
  13926. * Set the value of an uniform to an array of int32
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param array defines the array of int32 to store
  13929. */
  13930. Engine.prototype.setIntArray = function (uniform, array) {
  13931. if (!uniform)
  13932. return;
  13933. this._gl.uniform1iv(uniform, array);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to an array of int32 (stored as vec2)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param array defines the array of int32 to store
  13939. */
  13940. Engine.prototype.setIntArray2 = function (uniform, array) {
  13941. if (!uniform || array.length % 2 !== 0)
  13942. return;
  13943. this._gl.uniform2iv(uniform, array);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to an array of int32 (stored as vec3)
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param array defines the array of int32 to store
  13949. */
  13950. Engine.prototype.setIntArray3 = function (uniform, array) {
  13951. if (!uniform || array.length % 3 !== 0)
  13952. return;
  13953. this._gl.uniform3iv(uniform, array);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to an array of int32 (stored as vec4)
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param array defines the array of int32 to store
  13959. */
  13960. Engine.prototype.setIntArray4 = function (uniform, array) {
  13961. if (!uniform || array.length % 4 !== 0)
  13962. return;
  13963. this._gl.uniform4iv(uniform, array);
  13964. };
  13965. /**
  13966. * Set the value of an uniform to an array of float32
  13967. * @param uniform defines the webGL uniform location where to store the value
  13968. * @param array defines the array of float32 to store
  13969. */
  13970. Engine.prototype.setFloatArray = function (uniform, array) {
  13971. if (!uniform)
  13972. return;
  13973. this._gl.uniform1fv(uniform, array);
  13974. };
  13975. /**
  13976. * Set the value of an uniform to an array of float32 (stored as vec2)
  13977. * @param uniform defines the webGL uniform location where to store the value
  13978. * @param array defines the array of float32 to store
  13979. */
  13980. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13981. if (!uniform || array.length % 2 !== 0)
  13982. return;
  13983. this._gl.uniform2fv(uniform, array);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to an array of float32 (stored as vec3)
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param array defines the array of float32 to store
  13989. */
  13990. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13991. if (!uniform || array.length % 3 !== 0)
  13992. return;
  13993. this._gl.uniform3fv(uniform, array);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to an array of float32 (stored as vec4)
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param array defines the array of float32 to store
  13999. */
  14000. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14001. if (!uniform || array.length % 4 !== 0)
  14002. return;
  14003. this._gl.uniform4fv(uniform, array);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to an array of number
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param array defines the array of number to store
  14009. */
  14010. Engine.prototype.setArray = function (uniform, array) {
  14011. if (!uniform)
  14012. return;
  14013. this._gl.uniform1fv(uniform, array);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to an array of number (stored as vec2)
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param array defines the array of number to store
  14019. */
  14020. Engine.prototype.setArray2 = function (uniform, array) {
  14021. if (!uniform || array.length % 2 !== 0)
  14022. return;
  14023. this._gl.uniform2fv(uniform, array);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to an array of number (stored as vec3)
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param array defines the array of number to store
  14029. */
  14030. Engine.prototype.setArray3 = function (uniform, array) {
  14031. if (!uniform || array.length % 3 !== 0)
  14032. return;
  14033. this._gl.uniform3fv(uniform, array);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to an array of number (stored as vec4)
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param array defines the array of number to store
  14039. */
  14040. Engine.prototype.setArray4 = function (uniform, array) {
  14041. if (!uniform || array.length % 4 !== 0)
  14042. return;
  14043. this._gl.uniform4fv(uniform, array);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to an array of float32 (stored as matrices)
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param matrices defines the array of float32 to store
  14049. */
  14050. Engine.prototype.setMatrices = function (uniform, matrices) {
  14051. if (!uniform)
  14052. return;
  14053. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to a matrix
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param matrix defines the matrix to store
  14059. */
  14060. Engine.prototype.setMatrix = function (uniform, matrix) {
  14061. if (!uniform)
  14062. return;
  14063. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14064. };
  14065. /**
  14066. * Set the value of an uniform to a matrix (3x3)
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14069. */
  14070. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14071. if (!uniform)
  14072. return;
  14073. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to a matrix (2x2)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14079. */
  14080. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14081. if (!uniform)
  14082. return;
  14083. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to a number (int)
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param value defines the int number to store
  14089. */
  14090. Engine.prototype.setInt = function (uniform, value) {
  14091. if (!uniform)
  14092. return;
  14093. this._gl.uniform1i(uniform, value);
  14094. };
  14095. /**
  14096. * Set the value of an uniform to a number (float)
  14097. * @param uniform defines the webGL uniform location where to store the value
  14098. * @param value defines the float number to store
  14099. */
  14100. Engine.prototype.setFloat = function (uniform, value) {
  14101. if (!uniform)
  14102. return;
  14103. this._gl.uniform1f(uniform, value);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to a vec2
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param x defines the 1st component of the value
  14109. * @param y defines the 2nd component of the value
  14110. */
  14111. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14112. if (!uniform)
  14113. return;
  14114. this._gl.uniform2f(uniform, x, y);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to a vec3
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param x defines the 1st component of the value
  14120. * @param y defines the 2nd component of the value
  14121. * @param z defines the 3rd component of the value
  14122. */
  14123. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform3f(uniform, x, y, z);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a boolean
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param bool defines the boolean to store
  14132. */
  14133. Engine.prototype.setBool = function (uniform, bool) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniform1i(uniform, bool);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a vec4
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param x defines the 1st component of the value
  14142. * @param y defines the 2nd component of the value
  14143. * @param z defines the 3rd component of the value
  14144. * @param w defines the 4th component of the value
  14145. */
  14146. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14147. if (!uniform)
  14148. return;
  14149. this._gl.uniform4f(uniform, x, y, z, w);
  14150. };
  14151. /**
  14152. * Set the value of an uniform to a Color3
  14153. * @param uniform defines the webGL uniform location where to store the value
  14154. * @param color3 defines the color to store
  14155. */
  14156. Engine.prototype.setColor3 = function (uniform, color3) {
  14157. if (!uniform)
  14158. return;
  14159. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14160. };
  14161. /**
  14162. * Set the value of an uniform to a Color3 and an alpha value
  14163. * @param uniform defines the webGL uniform location where to store the value
  14164. * @param color3 defines the color to store
  14165. * @param alpha defines the alpha component to store
  14166. */
  14167. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14168. if (!uniform)
  14169. return;
  14170. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14171. };
  14172. /**
  14173. * Sets a Color4 on a uniform variable
  14174. * @param uniform defines the uniform location
  14175. * @param color4 defines the value to be set
  14176. */
  14177. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14178. if (!uniform)
  14179. return;
  14180. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14181. };
  14182. // States
  14183. /**
  14184. * Set various states to the webGL context
  14185. * @param culling defines backface culling state
  14186. * @param zOffset defines the value to apply to zOffset (0 by default)
  14187. * @param force defines if states must be applied even if cache is up to date
  14188. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14189. */
  14190. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14191. if (zOffset === void 0) { zOffset = 0; }
  14192. if (reverseSide === void 0) { reverseSide = false; }
  14193. // Culling
  14194. if (this._depthCullingState.cull !== culling || force) {
  14195. this._depthCullingState.cull = culling;
  14196. }
  14197. // Cull face
  14198. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14199. if (this._depthCullingState.cullFace !== cullFace || force) {
  14200. this._depthCullingState.cullFace = cullFace;
  14201. }
  14202. // Z offset
  14203. this.setZOffset(zOffset);
  14204. // Front face
  14205. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14206. if (this._depthCullingState.frontFace !== frontFace || force) {
  14207. this._depthCullingState.frontFace = frontFace;
  14208. }
  14209. };
  14210. /**
  14211. * Set the z offset to apply to current rendering
  14212. * @param value defines the offset to apply
  14213. */
  14214. Engine.prototype.setZOffset = function (value) {
  14215. this._depthCullingState.zOffset = value;
  14216. };
  14217. /**
  14218. * Gets the current value of the zOffset
  14219. * @returns the current zOffset state
  14220. */
  14221. Engine.prototype.getZOffset = function () {
  14222. return this._depthCullingState.zOffset;
  14223. };
  14224. /**
  14225. * Enable or disable depth buffering
  14226. * @param enable defines the state to set
  14227. */
  14228. Engine.prototype.setDepthBuffer = function (enable) {
  14229. this._depthCullingState.depthTest = enable;
  14230. };
  14231. /**
  14232. * Gets a boolean indicating if depth writing is enabled
  14233. * @returns the current depth writing state
  14234. */
  14235. Engine.prototype.getDepthWrite = function () {
  14236. return this._depthCullingState.depthMask;
  14237. };
  14238. /**
  14239. * Enable or disable depth writing
  14240. * @param enable defines the state to set
  14241. */
  14242. Engine.prototype.setDepthWrite = function (enable) {
  14243. this._depthCullingState.depthMask = enable;
  14244. };
  14245. /**
  14246. * Enable or disable color writing
  14247. * @param enable defines the state to set
  14248. */
  14249. Engine.prototype.setColorWrite = function (enable) {
  14250. this._gl.colorMask(enable, enable, enable, enable);
  14251. this._colorWrite = enable;
  14252. };
  14253. /**
  14254. * Gets a boolean indicating if color writing is enabled
  14255. * @returns the current color writing state
  14256. */
  14257. Engine.prototype.getColorWrite = function () {
  14258. return this._colorWrite;
  14259. };
  14260. /**
  14261. * Sets alpha constants used by some alpha blending modes
  14262. * @param r defines the red component
  14263. * @param g defines the green component
  14264. * @param b defines the blue component
  14265. * @param a defines the alpha component
  14266. */
  14267. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14268. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14269. };
  14270. /**
  14271. * Sets the current alpha mode
  14272. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14273. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14274. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14275. */
  14276. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14277. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14278. if (this._alphaMode === mode) {
  14279. return;
  14280. }
  14281. switch (mode) {
  14282. case Engine.ALPHA_DISABLE:
  14283. this._alphaState.alphaBlend = false;
  14284. break;
  14285. case Engine.ALPHA_PREMULTIPLIED:
  14286. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14287. this._alphaState.alphaBlend = true;
  14288. break;
  14289. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14290. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14291. this._alphaState.alphaBlend = true;
  14292. break;
  14293. case Engine.ALPHA_COMBINE:
  14294. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14295. this._alphaState.alphaBlend = true;
  14296. break;
  14297. case Engine.ALPHA_ONEONE:
  14298. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14299. this._alphaState.alphaBlend = true;
  14300. break;
  14301. case Engine.ALPHA_ADD:
  14302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14303. this._alphaState.alphaBlend = true;
  14304. break;
  14305. case Engine.ALPHA_SUBTRACT:
  14306. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14307. this._alphaState.alphaBlend = true;
  14308. break;
  14309. case Engine.ALPHA_MULTIPLY:
  14310. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14311. this._alphaState.alphaBlend = true;
  14312. break;
  14313. case Engine.ALPHA_MAXIMIZED:
  14314. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14315. this._alphaState.alphaBlend = true;
  14316. break;
  14317. case Engine.ALPHA_INTERPOLATE:
  14318. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14319. this._alphaState.alphaBlend = true;
  14320. break;
  14321. case Engine.ALPHA_SCREENMODE:
  14322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14323. this._alphaState.alphaBlend = true;
  14324. break;
  14325. }
  14326. if (!noDepthWriteChange) {
  14327. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14328. }
  14329. this._alphaMode = mode;
  14330. };
  14331. /**
  14332. * Gets the current alpha mode
  14333. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14334. * @returns the current alpha mode
  14335. */
  14336. Engine.prototype.getAlphaMode = function () {
  14337. return this._alphaMode;
  14338. };
  14339. // Textures
  14340. /**
  14341. * Clears the list of texture accessible through engine.
  14342. * This can help preventing texture load conflict due to name collision.
  14343. */
  14344. Engine.prototype.clearInternalTexturesCache = function () {
  14345. this._internalTexturesCache = [];
  14346. };
  14347. /**
  14348. * Force the entire cache to be cleared
  14349. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14350. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14351. */
  14352. Engine.prototype.wipeCaches = function (bruteForce) {
  14353. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14354. return;
  14355. }
  14356. this._currentEffect = null;
  14357. this._viewportCached.x = 0;
  14358. this._viewportCached.y = 0;
  14359. this._viewportCached.z = 0;
  14360. this._viewportCached.w = 0;
  14361. if (bruteForce) {
  14362. this.resetTextureCache();
  14363. this._currentProgram = null;
  14364. this._stencilState.reset();
  14365. this._depthCullingState.reset();
  14366. this.setDepthFunctionToLessOrEqual();
  14367. this._alphaState.reset();
  14368. this._unpackFlipYCached = null;
  14369. }
  14370. this._resetVertexBufferBinding();
  14371. this._cachedIndexBuffer = null;
  14372. this._cachedEffectForVertexBuffers = null;
  14373. this._unbindVertexArrayObject();
  14374. this.bindIndexBuffer(null);
  14375. };
  14376. /**
  14377. * Set the compressed texture format to use, based on the formats you have, and the formats
  14378. * supported by the hardware / browser.
  14379. *
  14380. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14381. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14382. * to API arguments needed to compressed textures. This puts the burden on the container
  14383. * generator to house the arcane code for determining these for current & future formats.
  14384. *
  14385. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14386. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14387. *
  14388. * Note: The result of this call is not taken into account when a texture is base64.
  14389. *
  14390. * @param formatsAvailable defines the list of those format families you have created
  14391. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14392. *
  14393. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14394. * @returns The extension selected.
  14395. */
  14396. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14397. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14398. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14399. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14400. return this._textureFormatInUse = this._texturesSupported[i];
  14401. }
  14402. }
  14403. }
  14404. // actively set format to nothing, to allow this to be called more than once
  14405. // and possibly fail the 2nd time
  14406. this._textureFormatInUse = null;
  14407. return null;
  14408. };
  14409. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14410. var gl = this._gl;
  14411. var magFilter = gl.NEAREST;
  14412. var minFilter = gl.NEAREST;
  14413. switch (samplingMode) {
  14414. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14415. magFilter = gl.LINEAR;
  14416. if (generateMipMaps) {
  14417. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14418. }
  14419. else {
  14420. minFilter = gl.LINEAR;
  14421. }
  14422. break;
  14423. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14424. magFilter = gl.LINEAR;
  14425. if (generateMipMaps) {
  14426. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14427. }
  14428. else {
  14429. minFilter = gl.LINEAR;
  14430. }
  14431. break;
  14432. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14433. magFilter = gl.NEAREST;
  14434. if (generateMipMaps) {
  14435. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14436. }
  14437. else {
  14438. minFilter = gl.NEAREST;
  14439. }
  14440. break;
  14441. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14442. magFilter = gl.NEAREST;
  14443. if (generateMipMaps) {
  14444. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14445. }
  14446. else {
  14447. minFilter = gl.NEAREST;
  14448. }
  14449. break;
  14450. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14451. magFilter = gl.NEAREST;
  14452. if (generateMipMaps) {
  14453. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14454. }
  14455. else {
  14456. minFilter = gl.LINEAR;
  14457. }
  14458. break;
  14459. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14460. magFilter = gl.NEAREST;
  14461. if (generateMipMaps) {
  14462. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14463. }
  14464. else {
  14465. minFilter = gl.LINEAR;
  14466. }
  14467. break;
  14468. case Engine.TEXTURE_NEAREST_LINEAR:
  14469. magFilter = gl.NEAREST;
  14470. minFilter = gl.LINEAR;
  14471. break;
  14472. case Engine.TEXTURE_NEAREST_NEAREST:
  14473. magFilter = gl.NEAREST;
  14474. minFilter = gl.NEAREST;
  14475. break;
  14476. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14477. magFilter = gl.LINEAR;
  14478. if (generateMipMaps) {
  14479. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14480. }
  14481. else {
  14482. minFilter = gl.NEAREST;
  14483. }
  14484. break;
  14485. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14486. magFilter = gl.LINEAR;
  14487. if (generateMipMaps) {
  14488. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14489. }
  14490. else {
  14491. minFilter = gl.NEAREST;
  14492. }
  14493. break;
  14494. case Engine.TEXTURE_LINEAR_LINEAR:
  14495. magFilter = gl.LINEAR;
  14496. minFilter = gl.LINEAR;
  14497. break;
  14498. case Engine.TEXTURE_LINEAR_NEAREST:
  14499. magFilter = gl.LINEAR;
  14500. minFilter = gl.NEAREST;
  14501. break;
  14502. }
  14503. return {
  14504. min: minFilter,
  14505. mag: magFilter
  14506. };
  14507. };
  14508. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14509. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14510. var img;
  14511. var onload = function () {
  14512. loadedImages[index] = img;
  14513. loadedImages._internalCount++;
  14514. if (scene) {
  14515. scene._removePendingData(img);
  14516. }
  14517. if (loadedImages._internalCount === 6) {
  14518. onfinish(loadedImages);
  14519. }
  14520. };
  14521. var onerror = function (message, exception) {
  14522. if (scene) {
  14523. scene._removePendingData(img);
  14524. }
  14525. if (onErrorCallBack) {
  14526. onErrorCallBack(message, exception);
  14527. }
  14528. };
  14529. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14530. if (scene) {
  14531. scene._addPendingData(img);
  14532. }
  14533. };
  14534. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14535. if (onError === void 0) { onError = null; }
  14536. var loadedImages = [];
  14537. loadedImages._internalCount = 0;
  14538. for (var index = 0; index < 6; index++) {
  14539. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14540. }
  14541. };
  14542. ;
  14543. /** @hidden */
  14544. Engine.prototype._createTexture = function () {
  14545. var texture = this._gl.createTexture();
  14546. if (!texture) {
  14547. throw new Error("Unable to create texture");
  14548. }
  14549. return texture;
  14550. };
  14551. /**
  14552. * Usually called from BABYLON.Texture.ts.
  14553. * Passed information to create a WebGLTexture
  14554. * @param urlArg defines a value which contains one of the following:
  14555. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14556. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14557. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14558. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14559. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14560. * @param scene needed for loading to the correct scene
  14561. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14562. * @param onLoad optional callback to be called upon successful completion
  14563. * @param onError optional callback to be called upon failure
  14564. * @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
  14565. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14566. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14567. * @param forcedExtension defines the extension to use to pick the right loader
  14568. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14569. */
  14570. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14571. var _this = this;
  14572. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14573. if (onLoad === void 0) { onLoad = null; }
  14574. if (onError === void 0) { onError = null; }
  14575. if (buffer === void 0) { buffer = null; }
  14576. if (fallback === void 0) { fallback = null; }
  14577. if (format === void 0) { format = null; }
  14578. if (forcedExtension === void 0) { forcedExtension = null; }
  14579. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14580. var fromData = url.substr(0, 5) === "data:";
  14581. var fromBlob = url.substr(0, 5) === "blob:";
  14582. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14583. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14584. // establish the file extension, if possible
  14585. var lastDot = url.lastIndexOf('.');
  14586. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14587. var loader = null;
  14588. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14589. var availableLoader = _a[_i];
  14590. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14591. loader = availableLoader;
  14592. break;
  14593. }
  14594. }
  14595. if (loader) {
  14596. url = loader.transformUrl(url, this._textureFormatInUse);
  14597. }
  14598. if (scene) {
  14599. scene._addPendingData(texture);
  14600. }
  14601. texture.url = url;
  14602. texture.generateMipMaps = !noMipmap;
  14603. texture.samplingMode = samplingMode;
  14604. texture.invertY = invertY;
  14605. if (!this._doNotHandleContextLost) {
  14606. // Keep a link to the buffer only if we plan to handle context lost
  14607. texture._buffer = buffer;
  14608. }
  14609. var onLoadObserver = null;
  14610. if (onLoad && !fallback) {
  14611. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14612. }
  14613. if (!fallback)
  14614. this._internalTexturesCache.push(texture);
  14615. var onInternalError = function (message, exception) {
  14616. if (scene) {
  14617. scene._removePendingData(texture);
  14618. }
  14619. var customFallback = false;
  14620. if (loader) {
  14621. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14622. if (fallbackUrl) {
  14623. // Add Back
  14624. customFallback = true;
  14625. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14626. }
  14627. }
  14628. if (!customFallback) {
  14629. if (onLoadObserver) {
  14630. texture.onLoadedObservable.remove(onLoadObserver);
  14631. }
  14632. if (BABYLON.Tools.UseFallbackTexture) {
  14633. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14634. }
  14635. }
  14636. if (onError) {
  14637. onError(message || "Unknown error", exception);
  14638. }
  14639. };
  14640. // processing for non-image formats
  14641. if (loader) {
  14642. var callback = function (data) {
  14643. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14644. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14645. done();
  14646. return false;
  14647. }, samplingMode);
  14648. });
  14649. };
  14650. if (!buffer) {
  14651. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14652. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14653. });
  14654. }
  14655. else {
  14656. callback(buffer);
  14657. }
  14658. }
  14659. else {
  14660. var onload = function (img) {
  14661. if (fromBlob && !_this._doNotHandleContextLost) {
  14662. // We need to store the image if we need to rebuild the texture
  14663. // in case of a webgl context lost
  14664. texture._buffer = img;
  14665. }
  14666. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14667. var gl = _this._gl;
  14668. var isPot = (img.width === potWidth && img.height === potHeight);
  14669. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14670. if (isPot) {
  14671. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14672. return false;
  14673. }
  14674. var maxTextureSize = _this._caps.maxTextureSize;
  14675. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14676. _this._prepareWorkingCanvas();
  14677. if (!_this._workingCanvas || !_this._workingContext) {
  14678. return false;
  14679. }
  14680. _this._workingCanvas.width = potWidth;
  14681. _this._workingCanvas.height = potHeight;
  14682. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14683. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14684. texture.width = potWidth;
  14685. texture.height = potHeight;
  14686. return false;
  14687. }
  14688. else {
  14689. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14690. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14691. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14692. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14697. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14698. _this._releaseTexture(source_1);
  14699. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14700. continuationCallback();
  14701. });
  14702. }
  14703. return true;
  14704. }, samplingMode);
  14705. };
  14706. if (!fromData || isBase64) {
  14707. if (buffer instanceof HTMLImageElement) {
  14708. onload(buffer);
  14709. }
  14710. else {
  14711. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14712. }
  14713. }
  14714. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14715. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14716. }
  14717. else {
  14718. onload(buffer);
  14719. }
  14720. }
  14721. return texture;
  14722. };
  14723. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14724. var _this = this;
  14725. var rtt = this.createRenderTargetTexture({
  14726. width: destination.width,
  14727. height: destination.height,
  14728. }, {
  14729. generateMipMaps: false,
  14730. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14731. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14732. generateDepthBuffer: false,
  14733. generateStencilBuffer: false
  14734. });
  14735. if (!this._rescalePostProcess) {
  14736. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14737. }
  14738. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14739. _this._rescalePostProcess.onApply = function (effect) {
  14740. effect._bindTexture("textureSampler", source);
  14741. };
  14742. var hostingScene = scene;
  14743. if (!hostingScene) {
  14744. hostingScene = _this.scenes[_this.scenes.length - 1];
  14745. }
  14746. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14747. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14748. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14749. _this.unBindFramebuffer(rtt);
  14750. _this._releaseTexture(rtt);
  14751. if (onComplete) {
  14752. onComplete();
  14753. }
  14754. });
  14755. };
  14756. /**
  14757. * Update a raw texture
  14758. * @param texture defines the texture to update
  14759. * @param data defines the data to store in the texture
  14760. * @param format defines the format of the data
  14761. * @param invertY defines if data must be stored with Y axis inverted
  14762. * @param compression defines the compression used (null by default)
  14763. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14764. */
  14765. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14766. if (compression === void 0) { compression = null; }
  14767. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14768. if (!texture) {
  14769. return;
  14770. }
  14771. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14772. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14773. // babylon's internalFormat but gl's texImage2D format
  14774. var internalFormat = this._getInternalFormat(format);
  14775. var textureType = this._getWebGLTextureType(type);
  14776. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14777. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14778. if (!this._doNotHandleContextLost) {
  14779. texture._bufferView = data;
  14780. texture.format = format;
  14781. texture.type = type;
  14782. texture.invertY = invertY;
  14783. texture._compression = compression;
  14784. }
  14785. if (texture.width % 4 !== 0) {
  14786. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14787. }
  14788. if (compression && data) {
  14789. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14790. }
  14791. else {
  14792. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14793. }
  14794. if (texture.generateMipMaps) {
  14795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14796. }
  14797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14798. // this.resetTextureCache();
  14799. texture.isReady = true;
  14800. };
  14801. /**
  14802. * Creates a raw texture
  14803. * @param data defines the data to store in the texture
  14804. * @param width defines the width of the texture
  14805. * @param height defines the height of the texture
  14806. * @param format defines the format of the data
  14807. * @param generateMipMaps defines if the engine should generate the mip levels
  14808. * @param invertY defines if data must be stored with Y axis inverted
  14809. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14810. * @param compression defines the compression used (null by default)
  14811. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14812. * @returns the raw texture inside an InternalTexture
  14813. */
  14814. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14815. if (compression === void 0) { compression = null; }
  14816. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14817. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14818. texture.baseWidth = width;
  14819. texture.baseHeight = height;
  14820. texture.width = width;
  14821. texture.height = height;
  14822. texture.format = format;
  14823. texture.generateMipMaps = generateMipMaps;
  14824. texture.samplingMode = samplingMode;
  14825. texture.invertY = invertY;
  14826. texture._compression = compression;
  14827. texture.type = type;
  14828. if (!this._doNotHandleContextLost) {
  14829. texture._bufferView = data;
  14830. }
  14831. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14832. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14833. // Filters
  14834. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14835. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14837. if (generateMipMaps) {
  14838. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14839. }
  14840. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14841. this._internalTexturesCache.push(texture);
  14842. return texture;
  14843. };
  14844. /** @hidden */
  14845. Engine.prototype._unpackFlipY = function (value) {
  14846. if (this._unpackFlipYCached !== value) {
  14847. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14848. if (this.enableUnpackFlipYCached) {
  14849. this._unpackFlipYCached = value;
  14850. }
  14851. }
  14852. };
  14853. /** @hidden */
  14854. Engine.prototype._getUnpackAlignement = function () {
  14855. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14856. };
  14857. /**
  14858. * Creates a dynamic texture
  14859. * @param width defines the width of the texture
  14860. * @param height defines the height of the texture
  14861. * @param generateMipMaps defines if the engine should generate the mip levels
  14862. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14863. * @returns the dynamic texture inside an InternalTexture
  14864. */
  14865. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14866. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14867. texture.baseWidth = width;
  14868. texture.baseHeight = height;
  14869. if (generateMipMaps) {
  14870. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14871. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14872. }
  14873. // this.resetTextureCache();
  14874. texture.width = width;
  14875. texture.height = height;
  14876. texture.isReady = false;
  14877. texture.generateMipMaps = generateMipMaps;
  14878. texture.samplingMode = samplingMode;
  14879. this.updateTextureSamplingMode(samplingMode, texture);
  14880. this._internalTexturesCache.push(texture);
  14881. return texture;
  14882. };
  14883. /**
  14884. * Update the sampling mode of a given texture
  14885. * @param samplingMode defines the required sampling mode
  14886. * @param texture defines the texture to update
  14887. */
  14888. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14889. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14890. if (texture.isCube) {
  14891. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14892. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14893. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14894. }
  14895. else if (texture.is3D) {
  14896. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14897. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14898. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14899. }
  14900. else {
  14901. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14902. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14904. }
  14905. texture.samplingMode = samplingMode;
  14906. };
  14907. /**
  14908. * Update the content of a dynamic texture
  14909. * @param texture defines the texture to update
  14910. * @param canvas defines the canvas containing the source
  14911. * @param invertY defines if data must be stored with Y axis inverted
  14912. * @param premulAlpha defines if alpha is stored as premultiplied
  14913. * @param format defines the format of the data
  14914. */
  14915. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14916. if (premulAlpha === void 0) { premulAlpha = false; }
  14917. if (!texture) {
  14918. return;
  14919. }
  14920. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14921. this._unpackFlipY(invertY);
  14922. if (premulAlpha) {
  14923. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14924. }
  14925. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14926. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14927. if (texture.generateMipMaps) {
  14928. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14929. }
  14930. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14931. if (premulAlpha) {
  14932. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14933. }
  14934. texture.isReady = true;
  14935. };
  14936. /**
  14937. * Update a video texture
  14938. * @param texture defines the texture to update
  14939. * @param video defines the video element to use
  14940. * @param invertY defines if data must be stored with Y axis inverted
  14941. */
  14942. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14943. if (!texture || texture._isDisabled) {
  14944. return;
  14945. }
  14946. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14947. this._unpackFlipY(!invertY); // Video are upside down by default
  14948. try {
  14949. // Testing video texture support
  14950. if (this._videoTextureSupported === undefined) {
  14951. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14952. if (this._gl.getError() !== 0) {
  14953. this._videoTextureSupported = false;
  14954. }
  14955. else {
  14956. this._videoTextureSupported = true;
  14957. }
  14958. }
  14959. // Copy video through the current working canvas if video texture is not supported
  14960. if (!this._videoTextureSupported) {
  14961. if (!texture._workingCanvas) {
  14962. texture._workingCanvas = document.createElement("canvas");
  14963. var context = texture._workingCanvas.getContext("2d");
  14964. if (!context) {
  14965. throw new Error("Unable to get 2d context");
  14966. }
  14967. texture._workingContext = context;
  14968. texture._workingCanvas.width = texture.width;
  14969. texture._workingCanvas.height = texture.height;
  14970. }
  14971. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14972. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14973. }
  14974. else {
  14975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14976. }
  14977. if (texture.generateMipMaps) {
  14978. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14979. }
  14980. if (!wasPreviouslyBound) {
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14982. }
  14983. // this.resetTextureCache();
  14984. texture.isReady = true;
  14985. }
  14986. catch (ex) {
  14987. // Something unexpected
  14988. // Let's disable the texture
  14989. texture._isDisabled = true;
  14990. }
  14991. };
  14992. /**
  14993. * Updates a depth texture Comparison Mode and Function.
  14994. * If the comparison Function is equal to 0, the mode will be set to none.
  14995. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14996. * @param texture The texture to set the comparison function for
  14997. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14998. */
  14999. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15000. if (this.webGLVersion === 1) {
  15001. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15002. return;
  15003. }
  15004. var gl = this._gl;
  15005. if (texture.isCube) {
  15006. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15007. if (comparisonFunction === 0) {
  15008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15009. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15010. }
  15011. else {
  15012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15014. }
  15015. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15016. }
  15017. else {
  15018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15019. if (comparisonFunction === 0) {
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15022. }
  15023. else {
  15024. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15025. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15026. }
  15027. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15028. }
  15029. texture._comparisonFunction = comparisonFunction;
  15030. };
  15031. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15032. var width = size.width || size;
  15033. var height = size.height || size;
  15034. internalTexture.baseWidth = width;
  15035. internalTexture.baseHeight = height;
  15036. internalTexture.width = width;
  15037. internalTexture.height = height;
  15038. internalTexture.isReady = true;
  15039. internalTexture.samples = 1;
  15040. internalTexture.generateMipMaps = false;
  15041. internalTexture._generateDepthBuffer = true;
  15042. internalTexture._generateStencilBuffer = generateStencil;
  15043. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15044. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15045. internalTexture._comparisonFunction = comparisonFunction;
  15046. var gl = this._gl;
  15047. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15048. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15049. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15050. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15051. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15052. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15053. if (comparisonFunction === 0) {
  15054. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15055. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15056. }
  15057. else {
  15058. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15059. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15060. }
  15061. };
  15062. /**
  15063. * Creates a depth stencil texture.
  15064. * This is only available in WebGL 2 or with the depth texture extension available.
  15065. * @param size The size of face edge in the texture.
  15066. * @param options The options defining the texture.
  15067. * @returns The texture
  15068. */
  15069. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15070. if (options.isCube) {
  15071. var width = size.width || size;
  15072. return this._createDepthStencilCubeTexture(width, options);
  15073. }
  15074. else {
  15075. return this._createDepthStencilTexture(size, options);
  15076. }
  15077. };
  15078. /**
  15079. * Creates a depth stencil texture.
  15080. * This is only available in WebGL 2 or with the depth texture extension available.
  15081. * @param size The size of face edge in the texture.
  15082. * @param options The options defining the texture.
  15083. * @returns The texture
  15084. */
  15085. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15086. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15087. if (!this._caps.depthTextureExtension) {
  15088. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15089. return internalTexture;
  15090. }
  15091. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15092. var gl = this._gl;
  15093. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15094. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15095. if (this.webGLVersion > 1) {
  15096. if (internalOptions.generateStencil) {
  15097. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15098. }
  15099. else {
  15100. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15101. }
  15102. }
  15103. else {
  15104. if (internalOptions.generateStencil) {
  15105. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15106. }
  15107. else {
  15108. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15109. }
  15110. }
  15111. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15112. return internalTexture;
  15113. };
  15114. /**
  15115. * Creates a depth stencil cube texture.
  15116. * This is only available in WebGL 2.
  15117. * @param size The size of face edge in the cube texture.
  15118. * @param options The options defining the cube texture.
  15119. * @returns The cube texture
  15120. */
  15121. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15122. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15123. internalTexture.isCube = true;
  15124. if (this.webGLVersion === 1) {
  15125. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15126. return internalTexture;
  15127. }
  15128. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15129. var gl = this._gl;
  15130. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15131. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15132. // Create the depth/stencil buffer
  15133. for (var face = 0; face < 6; face++) {
  15134. if (internalOptions.generateStencil) {
  15135. 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);
  15136. }
  15137. else {
  15138. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15139. }
  15140. }
  15141. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15142. return internalTexture;
  15143. };
  15144. /**
  15145. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15146. * @param renderTarget The render target to set the frame buffer for
  15147. */
  15148. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15149. // Create the framebuffer
  15150. var internalTexture = renderTarget.getInternalTexture();
  15151. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15152. return;
  15153. }
  15154. var gl = this._gl;
  15155. var depthStencilTexture = renderTarget.depthStencilTexture;
  15156. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15157. if (depthStencilTexture.isCube) {
  15158. if (depthStencilTexture._generateStencilBuffer) {
  15159. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15160. }
  15161. else {
  15162. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15163. }
  15164. }
  15165. else {
  15166. if (depthStencilTexture._generateStencilBuffer) {
  15167. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15168. }
  15169. else {
  15170. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15171. }
  15172. }
  15173. this.bindUnboundFramebuffer(null);
  15174. };
  15175. /**
  15176. * Creates a new render target texture
  15177. * @param size defines the size of the texture
  15178. * @param options defines the options used to create the texture
  15179. * @returns a new render target texture stored in an InternalTexture
  15180. */
  15181. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15182. var fullOptions = new RenderTargetCreationOptions();
  15183. if (options !== undefined && typeof options === "object") {
  15184. fullOptions.generateMipMaps = options.generateMipMaps;
  15185. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15186. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15187. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15188. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15189. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15190. }
  15191. else {
  15192. fullOptions.generateMipMaps = options;
  15193. fullOptions.generateDepthBuffer = true;
  15194. fullOptions.generateStencilBuffer = false;
  15195. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15196. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15197. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15198. }
  15199. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15200. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15201. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15202. }
  15203. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15204. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15205. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15206. }
  15207. var gl = this._gl;
  15208. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15209. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15210. var width = size.width || size;
  15211. var height = size.height || size;
  15212. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15213. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15214. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15215. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15216. }
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15221. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15222. // Create the framebuffer
  15223. var currentFrameBuffer = this._currentFramebuffer;
  15224. var framebuffer = gl.createFramebuffer();
  15225. this.bindUnboundFramebuffer(framebuffer);
  15226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15227. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15228. if (fullOptions.generateMipMaps) {
  15229. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15230. }
  15231. // Unbind
  15232. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15234. this.bindUnboundFramebuffer(currentFrameBuffer);
  15235. texture._framebuffer = framebuffer;
  15236. texture.baseWidth = width;
  15237. texture.baseHeight = height;
  15238. texture.width = width;
  15239. texture.height = height;
  15240. texture.isReady = true;
  15241. texture.samples = 1;
  15242. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15243. texture.samplingMode = fullOptions.samplingMode;
  15244. texture.type = fullOptions.type;
  15245. texture.format = fullOptions.format;
  15246. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15247. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15248. // this.resetTextureCache();
  15249. this._internalTexturesCache.push(texture);
  15250. return texture;
  15251. };
  15252. /**
  15253. * Create a multi render target texture
  15254. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15255. * @param size defines the size of the texture
  15256. * @param options defines the creation options
  15257. * @returns the cube texture as an InternalTexture
  15258. */
  15259. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15260. var generateMipMaps = false;
  15261. var generateDepthBuffer = true;
  15262. var generateStencilBuffer = false;
  15263. var generateDepthTexture = false;
  15264. var textureCount = 1;
  15265. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15266. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15267. var types = new Array();
  15268. var samplingModes = new Array();
  15269. if (options !== undefined) {
  15270. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15271. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15272. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15273. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15274. textureCount = options.textureCount || 1;
  15275. if (options.types) {
  15276. types = options.types;
  15277. }
  15278. if (options.samplingModes) {
  15279. samplingModes = options.samplingModes;
  15280. }
  15281. }
  15282. var gl = this._gl;
  15283. // Create the framebuffer
  15284. var framebuffer = gl.createFramebuffer();
  15285. this.bindUnboundFramebuffer(framebuffer);
  15286. var width = size.width || size;
  15287. var height = size.height || size;
  15288. var textures = [];
  15289. var attachments = [];
  15290. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15291. for (var i = 0; i < textureCount; i++) {
  15292. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15293. var type = types[i] || defaultType;
  15294. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15295. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15296. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15297. }
  15298. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15299. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15300. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15301. }
  15302. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15303. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15304. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15305. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15306. }
  15307. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15308. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15309. textures.push(texture);
  15310. attachments.push(attachment);
  15311. gl.activeTexture(gl["TEXTURE" + i]);
  15312. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15314. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15317. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15318. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15319. if (generateMipMaps) {
  15320. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15321. }
  15322. // Unbind
  15323. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15324. texture._framebuffer = framebuffer;
  15325. texture._depthStencilBuffer = depthStencilBuffer;
  15326. texture.baseWidth = width;
  15327. texture.baseHeight = height;
  15328. texture.width = width;
  15329. texture.height = height;
  15330. texture.isReady = true;
  15331. texture.samples = 1;
  15332. texture.generateMipMaps = generateMipMaps;
  15333. texture.samplingMode = samplingMode;
  15334. texture.type = type;
  15335. texture._generateDepthBuffer = generateDepthBuffer;
  15336. texture._generateStencilBuffer = generateStencilBuffer;
  15337. texture._attachments = attachments;
  15338. this._internalTexturesCache.push(texture);
  15339. }
  15340. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15341. // Depth texture
  15342. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15343. gl.activeTexture(gl.TEXTURE0);
  15344. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15349. 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);
  15350. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15351. depthTexture._framebuffer = framebuffer;
  15352. depthTexture.baseWidth = width;
  15353. depthTexture.baseHeight = height;
  15354. depthTexture.width = width;
  15355. depthTexture.height = height;
  15356. depthTexture.isReady = true;
  15357. depthTexture.samples = 1;
  15358. depthTexture.generateMipMaps = generateMipMaps;
  15359. depthTexture.samplingMode = gl.NEAREST;
  15360. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15361. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15362. textures.push(depthTexture);
  15363. this._internalTexturesCache.push(depthTexture);
  15364. }
  15365. gl.drawBuffers(attachments);
  15366. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15367. this.bindUnboundFramebuffer(null);
  15368. this.resetTextureCache();
  15369. return textures;
  15370. };
  15371. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15372. if (samples === void 0) { samples = 1; }
  15373. var depthStencilBuffer = null;
  15374. var gl = this._gl;
  15375. // Create the depth/stencil buffer
  15376. if (generateStencilBuffer) {
  15377. depthStencilBuffer = gl.createRenderbuffer();
  15378. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15379. if (samples > 1) {
  15380. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15381. }
  15382. else {
  15383. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15384. }
  15385. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15386. }
  15387. else if (generateDepthBuffer) {
  15388. depthStencilBuffer = gl.createRenderbuffer();
  15389. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15390. if (samples > 1) {
  15391. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15392. }
  15393. else {
  15394. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15395. }
  15396. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15397. }
  15398. return depthStencilBuffer;
  15399. };
  15400. /**
  15401. * Updates the sample count of a render target texture
  15402. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15403. * @param texture defines the texture to update
  15404. * @param samples defines the sample count to set
  15405. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15406. */
  15407. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15408. if (this.webGLVersion < 2 || !texture) {
  15409. return 1;
  15410. }
  15411. if (texture.samples === samples) {
  15412. return samples;
  15413. }
  15414. var gl = this._gl;
  15415. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15416. // Dispose previous render buffers
  15417. if (texture._depthStencilBuffer) {
  15418. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15419. texture._depthStencilBuffer = null;
  15420. }
  15421. if (texture._MSAAFramebuffer) {
  15422. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15423. texture._MSAAFramebuffer = null;
  15424. }
  15425. if (texture._MSAARenderBuffer) {
  15426. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15427. texture._MSAARenderBuffer = null;
  15428. }
  15429. if (samples > 1) {
  15430. var framebuffer = gl.createFramebuffer();
  15431. if (!framebuffer) {
  15432. throw new Error("Unable to create multi sampled framebuffer");
  15433. }
  15434. texture._MSAAFramebuffer = framebuffer;
  15435. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15436. var colorRenderbuffer = gl.createRenderbuffer();
  15437. if (!colorRenderbuffer) {
  15438. throw new Error("Unable to create multi sampled framebuffer");
  15439. }
  15440. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15441. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15442. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15443. texture._MSAARenderBuffer = colorRenderbuffer;
  15444. }
  15445. else {
  15446. this.bindUnboundFramebuffer(texture._framebuffer);
  15447. }
  15448. texture.samples = samples;
  15449. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15451. this.bindUnboundFramebuffer(null);
  15452. return samples;
  15453. };
  15454. /**
  15455. * Update the sample count for a given multiple render target texture
  15456. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15457. * @param textures defines the textures to update
  15458. * @param samples defines the sample count to set
  15459. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15460. */
  15461. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15462. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15463. return 1;
  15464. }
  15465. if (textures[0].samples === samples) {
  15466. return samples;
  15467. }
  15468. var gl = this._gl;
  15469. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15470. // Dispose previous render buffers
  15471. if (textures[0]._depthStencilBuffer) {
  15472. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15473. textures[0]._depthStencilBuffer = null;
  15474. }
  15475. if (textures[0]._MSAAFramebuffer) {
  15476. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15477. textures[0]._MSAAFramebuffer = null;
  15478. }
  15479. for (var i = 0; i < textures.length; i++) {
  15480. if (textures[i]._MSAARenderBuffer) {
  15481. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15482. textures[i]._MSAARenderBuffer = null;
  15483. }
  15484. }
  15485. if (samples > 1) {
  15486. var framebuffer = gl.createFramebuffer();
  15487. if (!framebuffer) {
  15488. throw new Error("Unable to create multi sampled framebuffer");
  15489. }
  15490. this.bindUnboundFramebuffer(framebuffer);
  15491. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15492. var attachments = [];
  15493. for (var i = 0; i < textures.length; i++) {
  15494. var texture = textures[i];
  15495. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15496. var colorRenderbuffer = gl.createRenderbuffer();
  15497. if (!colorRenderbuffer) {
  15498. throw new Error("Unable to create multi sampled framebuffer");
  15499. }
  15500. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15501. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15502. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15503. texture._MSAAFramebuffer = framebuffer;
  15504. texture._MSAARenderBuffer = colorRenderbuffer;
  15505. texture.samples = samples;
  15506. texture._depthStencilBuffer = depthStencilBuffer;
  15507. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15508. attachments.push(attachment);
  15509. }
  15510. gl.drawBuffers(attachments);
  15511. }
  15512. else {
  15513. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15514. }
  15515. this.bindUnboundFramebuffer(null);
  15516. return samples;
  15517. };
  15518. /** @hidden */
  15519. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15520. if (faceIndex === void 0) { faceIndex = 0; }
  15521. if (lod === void 0) { lod = 0; }
  15522. var gl = this._gl;
  15523. var target = gl.TEXTURE_2D;
  15524. if (texture.isCube) {
  15525. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15526. }
  15527. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15528. };
  15529. /** @hidden */
  15530. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15531. if (faceIndex === void 0) { faceIndex = 0; }
  15532. if (lod === void 0) { lod = 0; }
  15533. var gl = this._gl;
  15534. var textureType = this._getWebGLTextureType(texture.type);
  15535. var format = this._getInternalFormat(texture.format);
  15536. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15537. this._unpackFlipY(texture.invertY);
  15538. var target = gl.TEXTURE_2D;
  15539. if (texture.isCube) {
  15540. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15541. }
  15542. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15543. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15544. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15545. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15546. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15547. };
  15548. /** @hidden */
  15549. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15550. if (faceIndex === void 0) { faceIndex = 0; }
  15551. if (lod === void 0) { lod = 0; }
  15552. var gl = this._gl;
  15553. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15554. this._bindTextureDirectly(bindTarget, texture, true);
  15555. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15556. this._bindTextureDirectly(bindTarget, null, true);
  15557. };
  15558. /** @hidden */
  15559. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15560. if (faceIndex === void 0) { faceIndex = 0; }
  15561. if (lod === void 0) { lod = 0; }
  15562. var gl = this._gl;
  15563. var textureType = this._getWebGLTextureType(texture.type);
  15564. var format = this._getInternalFormat(texture.format);
  15565. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15566. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15567. this._bindTextureDirectly(bindTarget, texture, true);
  15568. this._unpackFlipY(texture.invertY);
  15569. var target = gl.TEXTURE_2D;
  15570. if (texture.isCube) {
  15571. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15572. }
  15573. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15574. this._bindTextureDirectly(bindTarget, null, true);
  15575. };
  15576. /**
  15577. * Creates a new render target cube texture
  15578. * @param size defines the size of the texture
  15579. * @param options defines the options used to create the texture
  15580. * @returns a new render target cube texture stored in an InternalTexture
  15581. */
  15582. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15583. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15584. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15585. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15586. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15587. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15588. }
  15589. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15590. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15591. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15592. }
  15593. var gl = this._gl;
  15594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15595. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15596. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15597. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15598. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15599. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15600. }
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15605. for (var face = 0; face < 6; face++) {
  15606. 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);
  15607. }
  15608. // Create the framebuffer
  15609. var framebuffer = gl.createFramebuffer();
  15610. this.bindUnboundFramebuffer(framebuffer);
  15611. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15612. // MipMaps
  15613. if (fullOptions.generateMipMaps) {
  15614. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15615. }
  15616. // Unbind
  15617. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15618. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15619. this.bindUnboundFramebuffer(null);
  15620. texture._framebuffer = framebuffer;
  15621. texture.width = size;
  15622. texture.height = size;
  15623. texture.isReady = true;
  15624. texture.isCube = true;
  15625. texture.samples = 1;
  15626. texture.generateMipMaps = fullOptions.generateMipMaps;
  15627. texture.samplingMode = fullOptions.samplingMode;
  15628. texture.type = fullOptions.type;
  15629. texture.format = fullOptions.format;
  15630. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15631. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15632. this._internalTexturesCache.push(texture);
  15633. return texture;
  15634. };
  15635. /**
  15636. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15637. * @param rootUrl defines the url where the file to load is located
  15638. * @param scene defines the current scene
  15639. * @param lodScale defines scale to apply to the mip map selection
  15640. * @param lodOffset defines offset to apply to the mip map selection
  15641. * @param onLoad defines an optional callback raised when the texture is loaded
  15642. * @param onError defines an optional callback raised if there is an issue to load the texture
  15643. * @param format defines the format of the data
  15644. * @param forcedExtension defines the extension to use to pick the right loader
  15645. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15646. * @returns the cube texture as an InternalTexture
  15647. */
  15648. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15649. var _this = this;
  15650. if (onLoad === void 0) { onLoad = null; }
  15651. if (onError === void 0) { onError = null; }
  15652. if (forcedExtension === void 0) { forcedExtension = null; }
  15653. if (createPolynomials === void 0) { createPolynomials = true; }
  15654. var callback = function (loadData) {
  15655. if (!loadData) {
  15656. if (onLoad) {
  15657. onLoad(null);
  15658. }
  15659. return;
  15660. }
  15661. var texture = loadData.texture;
  15662. if (!createPolynomials) {
  15663. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15664. }
  15665. else if (loadData.info.sphericalPolynomial) {
  15666. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15667. }
  15668. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15669. if (_this._caps.textureLOD) {
  15670. // Do not add extra process if texture lod is supported.
  15671. if (onLoad) {
  15672. onLoad(texture);
  15673. }
  15674. return;
  15675. }
  15676. var mipSlices = 3;
  15677. var gl = _this._gl;
  15678. var width = loadData.width;
  15679. if (!width) {
  15680. return;
  15681. }
  15682. var textures = [];
  15683. for (var i = 0; i < mipSlices; i++) {
  15684. //compute LOD from even spacing in smoothness (matching shader calculation)
  15685. var smoothness = i / (mipSlices - 1);
  15686. var roughness = 1 - smoothness;
  15687. var minLODIndex = lodOffset; // roughness = 0
  15688. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15689. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15690. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15691. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15692. glTextureFromLod.type = texture.type;
  15693. glTextureFromLod.format = texture.format;
  15694. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15695. glTextureFromLod.height = glTextureFromLod.width;
  15696. glTextureFromLod.isCube = true;
  15697. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15702. if (loadData.isDDS) {
  15703. var info = loadData.info;
  15704. var data = loadData.data;
  15705. _this._unpackFlipY(info.isCompressed);
  15706. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15707. }
  15708. else {
  15709. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15710. }
  15711. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15712. // Wrap in a base texture for easy binding.
  15713. var lodTexture = new BABYLON.BaseTexture(scene);
  15714. lodTexture.isCube = true;
  15715. lodTexture._texture = glTextureFromLod;
  15716. glTextureFromLod.isReady = true;
  15717. textures.push(lodTexture);
  15718. }
  15719. texture._lodTextureHigh = textures[2];
  15720. texture._lodTextureMid = textures[1];
  15721. texture._lodTextureLow = textures[0];
  15722. if (onLoad) {
  15723. onLoad(texture);
  15724. }
  15725. };
  15726. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15727. };
  15728. /**
  15729. * Creates a cube texture
  15730. * @param rootUrl defines the url where the files to load is located
  15731. * @param scene defines the current scene
  15732. * @param files defines the list of files to load (1 per face)
  15733. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15734. * @param onLoad defines an optional callback raised when the texture is loaded
  15735. * @param onError defines an optional callback raised if there is an issue to load the texture
  15736. * @param format defines the format of the data
  15737. * @param forcedExtension defines the extension to use to pick the right loader
  15738. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15739. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15740. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15741. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15742. * @returns the cube texture as an InternalTexture
  15743. */
  15744. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15745. var _this = this;
  15746. if (onLoad === void 0) { onLoad = null; }
  15747. if (onError === void 0) { onError = null; }
  15748. if (forcedExtension === void 0) { forcedExtension = null; }
  15749. if (createPolynomials === void 0) { createPolynomials = false; }
  15750. if (lodScale === void 0) { lodScale = 0; }
  15751. if (lodOffset === void 0) { lodOffset = 0; }
  15752. if (fallback === void 0) { fallback = null; }
  15753. var gl = this._gl;
  15754. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15755. texture.isCube = true;
  15756. texture.url = rootUrl;
  15757. texture.generateMipMaps = !noMipmap;
  15758. texture._lodGenerationScale = lodScale;
  15759. texture._lodGenerationOffset = lodOffset;
  15760. if (!this._doNotHandleContextLost) {
  15761. texture._extension = forcedExtension;
  15762. texture._files = files;
  15763. }
  15764. var lastDot = rootUrl.lastIndexOf('.');
  15765. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15766. var loader = null;
  15767. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15768. var availableLoader = _a[_i];
  15769. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15770. loader = availableLoader;
  15771. break;
  15772. }
  15773. }
  15774. var onInternalError = function (request, exception) {
  15775. if (loader) {
  15776. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15777. if (fallbackUrl) {
  15778. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15779. }
  15780. }
  15781. if (onError && request) {
  15782. onError(request.status + " " + request.statusText, exception);
  15783. }
  15784. };
  15785. if (loader) {
  15786. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15787. var onloaddata = function (data) {
  15788. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15789. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15790. };
  15791. if (files && files.length === 6) {
  15792. if (loader.supportCascades) {
  15793. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15794. }
  15795. else if (onError) {
  15796. onError("Textures type does not support cascades.");
  15797. }
  15798. }
  15799. else {
  15800. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15801. }
  15802. }
  15803. else {
  15804. if (!files) {
  15805. throw new Error("Cannot load cubemap because files were not defined");
  15806. }
  15807. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15808. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15809. var height = width;
  15810. _this._prepareWorkingCanvas();
  15811. if (!_this._workingCanvas || !_this._workingContext) {
  15812. return;
  15813. }
  15814. _this._workingCanvas.width = width;
  15815. _this._workingCanvas.height = height;
  15816. var faces = [
  15817. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15818. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15819. ];
  15820. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15821. _this._unpackFlipY(false);
  15822. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15823. for (var index = 0; index < faces.length; index++) {
  15824. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15825. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15826. }
  15827. if (!noMipmap) {
  15828. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15829. }
  15830. _this._setCubeMapTextureParams(!noMipmap);
  15831. texture.width = width;
  15832. texture.height = height;
  15833. texture.isReady = true;
  15834. if (format) {
  15835. texture.format = format;
  15836. }
  15837. texture.onLoadedObservable.notifyObservers(texture);
  15838. texture.onLoadedObservable.clear();
  15839. if (onLoad) {
  15840. onLoad();
  15841. }
  15842. }, files, onError);
  15843. }
  15844. this._internalTexturesCache.push(texture);
  15845. return texture;
  15846. };
  15847. /**
  15848. * @hidden
  15849. */
  15850. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15851. var gl = this._gl;
  15852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15856. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15857. // this.resetTextureCache();
  15858. };
  15859. /**
  15860. * Update a raw cube texture
  15861. * @param texture defines the texture to udpdate
  15862. * @param data defines the data to store
  15863. * @param format defines the data format
  15864. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15865. * @param invertY defines if data must be stored with Y axis inverted
  15866. * @param compression defines the compression used (null by default)
  15867. * @param level defines which level of the texture to update
  15868. */
  15869. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15870. if (compression === void 0) { compression = null; }
  15871. if (level === void 0) { level = 0; }
  15872. texture._bufferViewArray = data;
  15873. texture.format = format;
  15874. texture.type = type;
  15875. texture.invertY = invertY;
  15876. texture._compression = compression;
  15877. var gl = this._gl;
  15878. var textureType = this._getWebGLTextureType(type);
  15879. var internalFormat = this._getInternalFormat(format);
  15880. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15881. var needConversion = false;
  15882. if (internalFormat === gl.RGB) {
  15883. internalFormat = gl.RGBA;
  15884. needConversion = true;
  15885. }
  15886. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15887. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15888. if (texture.width % 4 !== 0) {
  15889. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15890. }
  15891. // Data are known to be in +X +Y +Z -X -Y -Z
  15892. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15893. var faceData = data[faceIndex];
  15894. if (compression) {
  15895. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15896. }
  15897. else {
  15898. if (needConversion) {
  15899. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15900. }
  15901. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15902. }
  15903. }
  15904. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15905. if (isPot && texture.generateMipMaps && level === 0) {
  15906. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15907. }
  15908. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15909. // this.resetTextureCache();
  15910. texture.isReady = true;
  15911. };
  15912. /**
  15913. * Creates a new raw cube texture
  15914. * @param data defines the array of data to use to create each face
  15915. * @param size defines the size of the textures
  15916. * @param format defines the format of the data
  15917. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15918. * @param generateMipMaps defines if the engine should generate the mip levels
  15919. * @param invertY defines if data must be stored with Y axis inverted
  15920. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15921. * @param compression defines the compression used (null by default)
  15922. * @returns the cube texture as an InternalTexture
  15923. */
  15924. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15925. if (compression === void 0) { compression = null; }
  15926. var gl = this._gl;
  15927. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15928. texture.isCube = true;
  15929. texture.format = format;
  15930. texture.type = type;
  15931. if (!this._doNotHandleContextLost) {
  15932. texture._bufferViewArray = data;
  15933. }
  15934. var textureType = this._getWebGLTextureType(type);
  15935. var internalFormat = this._getInternalFormat(format);
  15936. if (internalFormat === gl.RGB) {
  15937. internalFormat = gl.RGBA;
  15938. }
  15939. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15940. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15941. generateMipMaps = false;
  15942. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15943. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15944. }
  15945. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15946. generateMipMaps = false;
  15947. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15948. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15949. }
  15950. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15951. generateMipMaps = false;
  15952. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15953. }
  15954. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15955. generateMipMaps = false;
  15956. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15957. }
  15958. var width = size;
  15959. var height = width;
  15960. texture.width = width;
  15961. texture.height = height;
  15962. // Double check on POT to generate Mips.
  15963. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15964. if (!isPot) {
  15965. generateMipMaps = false;
  15966. }
  15967. // Upload data if needed. The texture won't be ready until then.
  15968. if (data) {
  15969. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15970. }
  15971. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15972. // Filters
  15973. if (data && generateMipMaps) {
  15974. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15975. }
  15976. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15981. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15982. texture.generateMipMaps = generateMipMaps;
  15983. return texture;
  15984. };
  15985. /**
  15986. * Creates a new raw cube texture from a specified url
  15987. * @param url defines the url where the data is located
  15988. * @param scene defines the current scene
  15989. * @param size defines the size of the textures
  15990. * @param format defines the format of the data
  15991. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15992. * @param noMipmap defines if the engine should avoid generating the mip levels
  15993. * @param callback defines a callback used to extract texture data from loaded data
  15994. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15995. * @param onLoad defines a callback called when texture is loaded
  15996. * @param onError defines a callback called if there is an error
  15997. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15998. * @param invertY defines if data must be stored with Y axis inverted
  15999. * @returns the cube texture as an InternalTexture
  16000. */
  16001. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16002. var _this = this;
  16003. if (onLoad === void 0) { onLoad = null; }
  16004. if (onError === void 0) { onError = null; }
  16005. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16006. if (invertY === void 0) { invertY = false; }
  16007. var gl = this._gl;
  16008. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16009. scene._addPendingData(texture);
  16010. texture.url = url;
  16011. this._internalTexturesCache.push(texture);
  16012. var onerror = function (request, exception) {
  16013. scene._removePendingData(texture);
  16014. if (onError && request) {
  16015. onError(request.status + " " + request.statusText, exception);
  16016. }
  16017. };
  16018. var internalCallback = function (data) {
  16019. var width = texture.width;
  16020. var faceDataArrays = callback(data);
  16021. if (!faceDataArrays) {
  16022. return;
  16023. }
  16024. if (mipmapGenerator) {
  16025. var textureType = _this._getWebGLTextureType(type);
  16026. var internalFormat = _this._getInternalFormat(format);
  16027. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16028. var needConversion = false;
  16029. if (internalFormat === gl.RGB) {
  16030. internalFormat = gl.RGBA;
  16031. needConversion = true;
  16032. }
  16033. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16034. _this._unpackFlipY(false);
  16035. var mipData = mipmapGenerator(faceDataArrays);
  16036. for (var level = 0; level < mipData.length; level++) {
  16037. var mipSize = width >> level;
  16038. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16039. var mipFaceData = mipData[level][faceIndex];
  16040. if (needConversion) {
  16041. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16042. }
  16043. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16044. }
  16045. }
  16046. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16047. }
  16048. else {
  16049. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16050. }
  16051. texture.isReady = true;
  16052. // this.resetTextureCache();
  16053. scene._removePendingData(texture);
  16054. if (onLoad) {
  16055. onLoad();
  16056. }
  16057. };
  16058. this._loadFile(url, function (data) {
  16059. internalCallback(data);
  16060. }, undefined, scene.database, true, onerror);
  16061. return texture;
  16062. };
  16063. ;
  16064. /**
  16065. * Update a raw 3D texture
  16066. * @param texture defines the texture to update
  16067. * @param data defines the data to store
  16068. * @param format defines the data format
  16069. * @param invertY defines if data must be stored with Y axis inverted
  16070. * @param compression defines the used compression (can be null)
  16071. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16072. */
  16073. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16074. if (compression === void 0) { compression = null; }
  16075. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16076. var internalType = this._getWebGLTextureType(textureType);
  16077. var internalFormat = this._getInternalFormat(format);
  16078. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16079. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16080. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16081. if (!this._doNotHandleContextLost) {
  16082. texture._bufferView = data;
  16083. texture.format = format;
  16084. texture.invertY = invertY;
  16085. texture._compression = compression;
  16086. }
  16087. if (texture.width % 4 !== 0) {
  16088. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16089. }
  16090. if (compression && data) {
  16091. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16092. }
  16093. else {
  16094. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16095. }
  16096. if (texture.generateMipMaps) {
  16097. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16098. }
  16099. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16100. // this.resetTextureCache();
  16101. texture.isReady = true;
  16102. };
  16103. /**
  16104. * Creates a new raw 3D texture
  16105. * @param data defines the data used to create the texture
  16106. * @param width defines the width of the texture
  16107. * @param height defines the height of the texture
  16108. * @param depth defines the depth of the texture
  16109. * @param format defines the format of the texture
  16110. * @param generateMipMaps defines if the engine must generate mip levels
  16111. * @param invertY defines if data must be stored with Y axis inverted
  16112. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16113. * @param compression defines the compressed used (can be null)
  16114. * @param textureType defines the compressed used (can be null)
  16115. * @returns a new raw 3D texture (stored in an InternalTexture)
  16116. */
  16117. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16118. if (compression === void 0) { compression = null; }
  16119. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16120. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16121. texture.baseWidth = width;
  16122. texture.baseHeight = height;
  16123. texture.baseDepth = depth;
  16124. texture.width = width;
  16125. texture.height = height;
  16126. texture.depth = depth;
  16127. texture.format = format;
  16128. texture.type = textureType;
  16129. texture.generateMipMaps = generateMipMaps;
  16130. texture.samplingMode = samplingMode;
  16131. texture.is3D = true;
  16132. if (!this._doNotHandleContextLost) {
  16133. texture._bufferView = data;
  16134. }
  16135. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16136. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16137. // Filters
  16138. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16139. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16140. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16141. if (generateMipMaps) {
  16142. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16143. }
  16144. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16145. this._internalTexturesCache.push(texture);
  16146. return texture;
  16147. };
  16148. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16149. var gl = this._gl;
  16150. if (!gl) {
  16151. return;
  16152. }
  16153. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16156. if (!noMipmap && !isCompressed) {
  16157. gl.generateMipmap(gl.TEXTURE_2D);
  16158. }
  16159. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16160. // this.resetTextureCache();
  16161. if (scene) {
  16162. scene._removePendingData(texture);
  16163. }
  16164. texture.onLoadedObservable.notifyObservers(texture);
  16165. texture.onLoadedObservable.clear();
  16166. };
  16167. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16168. var _this = this;
  16169. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16170. var maxTextureSize = this.getCaps().maxTextureSize;
  16171. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16172. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16173. var gl = this._gl;
  16174. if (!gl) {
  16175. return;
  16176. }
  16177. if (!texture._webGLTexture) {
  16178. // this.resetTextureCache();
  16179. if (scene) {
  16180. scene._removePendingData(texture);
  16181. }
  16182. return;
  16183. }
  16184. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16185. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16186. texture.baseWidth = width;
  16187. texture.baseHeight = height;
  16188. texture.width = potWidth;
  16189. texture.height = potHeight;
  16190. texture.isReady = true;
  16191. if (processFunction(potWidth, potHeight, function () {
  16192. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16193. })) {
  16194. // Returning as texture needs extra async steps
  16195. return;
  16196. }
  16197. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16198. };
  16199. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16200. // Create new RGBA data container.
  16201. var rgbaData;
  16202. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16203. rgbaData = new Float32Array(width * height * 4);
  16204. }
  16205. else {
  16206. rgbaData = new Uint32Array(width * height * 4);
  16207. }
  16208. // Convert each pixel.
  16209. for (var x = 0; x < width; x++) {
  16210. for (var y = 0; y < height; y++) {
  16211. var index = (y * width + x) * 3;
  16212. var newIndex = (y * width + x) * 4;
  16213. // Map Old Value to new value.
  16214. rgbaData[newIndex + 0] = rgbData[index + 0];
  16215. rgbaData[newIndex + 1] = rgbData[index + 1];
  16216. rgbaData[newIndex + 2] = rgbData[index + 2];
  16217. // Add fully opaque alpha channel.
  16218. rgbaData[newIndex + 3] = 1;
  16219. }
  16220. }
  16221. return rgbaData;
  16222. };
  16223. /** @hidden */
  16224. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16225. var gl = this._gl;
  16226. if (texture._framebuffer) {
  16227. gl.deleteFramebuffer(texture._framebuffer);
  16228. texture._framebuffer = null;
  16229. }
  16230. if (texture._depthStencilBuffer) {
  16231. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16232. texture._depthStencilBuffer = null;
  16233. }
  16234. if (texture._MSAAFramebuffer) {
  16235. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16236. texture._MSAAFramebuffer = null;
  16237. }
  16238. if (texture._MSAARenderBuffer) {
  16239. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16240. texture._MSAARenderBuffer = null;
  16241. }
  16242. };
  16243. /** @hidden */
  16244. Engine.prototype._releaseTexture = function (texture) {
  16245. var gl = this._gl;
  16246. this._releaseFramebufferObjects(texture);
  16247. gl.deleteTexture(texture._webGLTexture);
  16248. // Unbind channels
  16249. this.unbindAllTextures();
  16250. var index = this._internalTexturesCache.indexOf(texture);
  16251. if (index !== -1) {
  16252. this._internalTexturesCache.splice(index, 1);
  16253. }
  16254. // Integrated fixed lod samplers.
  16255. if (texture._lodTextureHigh) {
  16256. texture._lodTextureHigh.dispose();
  16257. }
  16258. if (texture._lodTextureMid) {
  16259. texture._lodTextureMid.dispose();
  16260. }
  16261. if (texture._lodTextureLow) {
  16262. texture._lodTextureLow.dispose();
  16263. }
  16264. // Set output texture of post process to null if the texture has been released/disposed
  16265. this.scenes.forEach(function (scene) {
  16266. scene.postProcesses.forEach(function (postProcess) {
  16267. if (postProcess._outputTexture == texture) {
  16268. postProcess._outputTexture = null;
  16269. }
  16270. });
  16271. scene.cameras.forEach(function (camera) {
  16272. camera._postProcesses.forEach(function (postProcess) {
  16273. if (postProcess) {
  16274. if (postProcess._outputTexture == texture) {
  16275. postProcess._outputTexture = null;
  16276. }
  16277. }
  16278. });
  16279. });
  16280. });
  16281. };
  16282. Engine.prototype.setProgram = function (program) {
  16283. if (this._currentProgram !== program) {
  16284. this._gl.useProgram(program);
  16285. this._currentProgram = program;
  16286. }
  16287. };
  16288. /**
  16289. * Binds an effect to the webGL context
  16290. * @param effect defines the effect to bind
  16291. */
  16292. Engine.prototype.bindSamplers = function (effect) {
  16293. this.setProgram(effect.getProgram());
  16294. var samplers = effect.getSamplers();
  16295. for (var index = 0; index < samplers.length; index++) {
  16296. var uniform = effect.getUniform(samplers[index]);
  16297. if (uniform) {
  16298. this._boundUniforms[index] = uniform;
  16299. }
  16300. }
  16301. this._currentEffect = null;
  16302. };
  16303. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16304. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16305. return;
  16306. }
  16307. // Remove
  16308. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16309. // Bind last to it
  16310. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16311. // Bind to dummy
  16312. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16313. };
  16314. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16315. if (!internalTexture) {
  16316. return -1;
  16317. }
  16318. internalTexture._initialSlot = channel;
  16319. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16320. if (channel !== internalTexture._designatedSlot) {
  16321. this._textureCollisions.addCount(1, false);
  16322. }
  16323. }
  16324. else {
  16325. if (channel !== internalTexture._designatedSlot) {
  16326. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16327. return internalTexture._designatedSlot;
  16328. }
  16329. else {
  16330. // No slot for this texture, let's pick a new one (if we find a free slot)
  16331. if (this._nextFreeTextureSlots.length) {
  16332. return this._nextFreeTextureSlots[0];
  16333. }
  16334. // We need to recycle the oldest bound texture, sorry.
  16335. this._textureCollisions.addCount(1, false);
  16336. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16337. }
  16338. }
  16339. }
  16340. return channel;
  16341. };
  16342. Engine.prototype._linkTrackers = function (previous, next) {
  16343. previous.next = next;
  16344. next.previous = previous;
  16345. };
  16346. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16347. var currentSlot = internalTexture._designatedSlot;
  16348. if (currentSlot === -1) {
  16349. return -1;
  16350. }
  16351. internalTexture._designatedSlot = -1;
  16352. if (this.disableTextureBindingOptimization) {
  16353. return -1;
  16354. }
  16355. // Remove from bound list
  16356. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16357. // Free the slot
  16358. this._boundTexturesCache[currentSlot] = null;
  16359. this._nextFreeTextureSlots.push(currentSlot);
  16360. return currentSlot;
  16361. };
  16362. Engine.prototype._activateCurrentTexture = function () {
  16363. if (this._currentTextureChannel !== this._activeChannel) {
  16364. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16365. this._currentTextureChannel = this._activeChannel;
  16366. }
  16367. };
  16368. /** @hidden */
  16369. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16370. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16371. if (force === void 0) { force = false; }
  16372. var wasPreviouslyBound = false;
  16373. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16374. this._activeChannel = texture._designatedSlot;
  16375. }
  16376. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16377. var isTextureForRendering = texture && texture._initialSlot > -1;
  16378. if (currentTextureBound !== texture || force) {
  16379. if (currentTextureBound) {
  16380. this._removeDesignatedSlot(currentTextureBound);
  16381. }
  16382. this._activateCurrentTexture();
  16383. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16384. this._boundTexturesCache[this._activeChannel] = texture;
  16385. if (texture) {
  16386. if (!this.disableTextureBindingOptimization) {
  16387. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16388. if (slotIndex > -1) {
  16389. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16390. }
  16391. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16392. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16393. }
  16394. texture._designatedSlot = this._activeChannel;
  16395. }
  16396. }
  16397. else if (forTextureDataUpdate) {
  16398. wasPreviouslyBound = true;
  16399. this._activateCurrentTexture();
  16400. }
  16401. if (isTextureForRendering && !forTextureDataUpdate) {
  16402. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16403. }
  16404. return wasPreviouslyBound;
  16405. };
  16406. /** @hidden */
  16407. Engine.prototype._bindTexture = function (channel, texture) {
  16408. if (channel < 0) {
  16409. return;
  16410. }
  16411. if (texture) {
  16412. channel = this._getCorrectTextureChannel(channel, texture);
  16413. }
  16414. this._activeChannel = channel;
  16415. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16416. };
  16417. /**
  16418. * Sets a texture to the webGL context from a postprocess
  16419. * @param channel defines the channel to use
  16420. * @param postProcess defines the source postprocess
  16421. */
  16422. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16423. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16424. };
  16425. /**
  16426. * Binds the output of the passed in post process to the texture channel specified
  16427. * @param channel The channel the texture should be bound to
  16428. * @param postProcess The post process which's output should be bound
  16429. */
  16430. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16431. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16432. };
  16433. /**
  16434. * Unbind all textures from the webGL context
  16435. */
  16436. Engine.prototype.unbindAllTextures = function () {
  16437. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16438. this._activeChannel = channel;
  16439. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16440. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16441. if (this.webGLVersion > 1) {
  16442. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16443. }
  16444. }
  16445. };
  16446. /**
  16447. * Sets a texture to the according uniform.
  16448. * @param channel The texture channel
  16449. * @param uniform The uniform to set
  16450. * @param texture The texture to apply
  16451. */
  16452. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16453. if (channel < 0) {
  16454. return;
  16455. }
  16456. if (uniform) {
  16457. this._boundUniforms[channel] = uniform;
  16458. }
  16459. this._setTexture(channel, texture);
  16460. };
  16461. /**
  16462. * Sets a depth stencil texture from a render target to the according uniform.
  16463. * @param channel The texture channel
  16464. * @param uniform The uniform to set
  16465. * @param texture The render target texture containing the depth stencil texture to apply
  16466. */
  16467. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16468. if (channel < 0) {
  16469. return;
  16470. }
  16471. if (uniform) {
  16472. this._boundUniforms[channel] = uniform;
  16473. }
  16474. if (!texture || !texture.depthStencilTexture) {
  16475. this._setTexture(channel, null);
  16476. }
  16477. else {
  16478. this._setTexture(channel, texture, false, true);
  16479. }
  16480. };
  16481. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16482. var uniform = this._boundUniforms[sourceSlot];
  16483. if (uniform._currentState === destination) {
  16484. return;
  16485. }
  16486. this._gl.uniform1i(uniform, destination);
  16487. uniform._currentState = destination;
  16488. };
  16489. Engine.prototype._getTextureWrapMode = function (mode) {
  16490. switch (mode) {
  16491. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16492. return this._gl.REPEAT;
  16493. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16494. return this._gl.CLAMP_TO_EDGE;
  16495. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16496. return this._gl.MIRRORED_REPEAT;
  16497. }
  16498. return this._gl.REPEAT;
  16499. };
  16500. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16501. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16502. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16503. // Not ready?
  16504. if (!texture) {
  16505. if (this._boundTexturesCache[channel] != null) {
  16506. this._activeChannel = channel;
  16507. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16508. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16509. if (this.webGLVersion > 1) {
  16510. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16511. }
  16512. }
  16513. return false;
  16514. }
  16515. // Video
  16516. if (texture.video) {
  16517. this._activeChannel = channel;
  16518. texture.update();
  16519. }
  16520. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16521. texture.delayLoad();
  16522. return false;
  16523. }
  16524. var internalTexture;
  16525. if (depthStencilTexture) {
  16526. internalTexture = texture.depthStencilTexture;
  16527. }
  16528. else if (texture.isReady()) {
  16529. internalTexture = texture.getInternalTexture();
  16530. }
  16531. else if (texture.isCube) {
  16532. internalTexture = this.emptyCubeTexture;
  16533. }
  16534. else if (texture.is3D) {
  16535. internalTexture = this.emptyTexture3D;
  16536. }
  16537. else {
  16538. internalTexture = this.emptyTexture;
  16539. }
  16540. if (!isPartOfTextureArray) {
  16541. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16542. }
  16543. var needToBind = true;
  16544. if (this._boundTexturesCache[channel] === internalTexture) {
  16545. this._moveBoundTextureOnTop(internalTexture);
  16546. if (!isPartOfTextureArray) {
  16547. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16548. }
  16549. needToBind = false;
  16550. }
  16551. this._activeChannel = channel;
  16552. if (internalTexture && internalTexture.is3D) {
  16553. if (needToBind) {
  16554. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16555. }
  16556. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16557. internalTexture._cachedWrapU = texture.wrapU;
  16558. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16559. }
  16560. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16561. internalTexture._cachedWrapV = texture.wrapV;
  16562. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16563. }
  16564. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16565. internalTexture._cachedWrapR = texture.wrapR;
  16566. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16567. }
  16568. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16569. }
  16570. else if (internalTexture && internalTexture.isCube) {
  16571. if (needToBind) {
  16572. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16573. }
  16574. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16575. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16576. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16577. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16578. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16579. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16580. }
  16581. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16582. }
  16583. else {
  16584. if (needToBind) {
  16585. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16586. }
  16587. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16588. internalTexture._cachedWrapU = texture.wrapU;
  16589. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16590. }
  16591. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16592. internalTexture._cachedWrapV = texture.wrapV;
  16593. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16594. }
  16595. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16596. }
  16597. return true;
  16598. };
  16599. /**
  16600. * Sets an array of texture to the webGL context
  16601. * @param channel defines the channel where the texture array must be set
  16602. * @param uniform defines the associated uniform location
  16603. * @param textures defines the array of textures to bind
  16604. */
  16605. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16606. if (channel < 0 || !uniform) {
  16607. return;
  16608. }
  16609. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16610. this._textureUnits = new Int32Array(textures.length);
  16611. }
  16612. for (var i = 0; i < textures.length; i++) {
  16613. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16614. }
  16615. this._gl.uniform1iv(uniform, this._textureUnits);
  16616. for (var index = 0; index < textures.length; index++) {
  16617. this._setTexture(this._textureUnits[index], textures[index], true);
  16618. }
  16619. };
  16620. /** @hidden */
  16621. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16622. var internalTexture = texture.getInternalTexture();
  16623. if (!internalTexture) {
  16624. return;
  16625. }
  16626. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16627. var value = texture.anisotropicFilteringLevel;
  16628. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16629. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16630. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16631. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16632. }
  16633. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16634. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16635. internalTexture._cachedAnisotropicFilteringLevel = value;
  16636. }
  16637. };
  16638. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16639. this._bindTextureDirectly(target, texture, true, true);
  16640. this._gl.texParameterf(target, parameter, value);
  16641. };
  16642. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16643. if (texture) {
  16644. this._bindTextureDirectly(target, texture, true, true);
  16645. }
  16646. this._gl.texParameteri(target, parameter, value);
  16647. };
  16648. /**
  16649. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16650. * @param x defines the x coordinate of the rectangle where pixels must be read
  16651. * @param y defines the y coordinate of the rectangle where pixels must be read
  16652. * @param width defines the width of the rectangle where pixels must be read
  16653. * @param height defines the height of the rectangle where pixels must be read
  16654. * @returns a Uint8Array containing RGBA colors
  16655. */
  16656. Engine.prototype.readPixels = function (x, y, width, height) {
  16657. var data = new Uint8Array(height * width * 4);
  16658. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16659. return data;
  16660. };
  16661. /**
  16662. * Add an externaly attached data from its key.
  16663. * This method call will fail and return false, if such key already exists.
  16664. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16665. * @param key the unique key that identifies the data
  16666. * @param data the data object to associate to the key for this Engine instance
  16667. * @return true if no such key were already present and the data was added successfully, false otherwise
  16668. */
  16669. Engine.prototype.addExternalData = function (key, data) {
  16670. if (!this._externalData) {
  16671. this._externalData = new BABYLON.StringDictionary();
  16672. }
  16673. return this._externalData.add(key, data);
  16674. };
  16675. /**
  16676. * Get an externaly attached data from its key
  16677. * @param key the unique key that identifies the data
  16678. * @return the associated data, if present (can be null), or undefined if not present
  16679. */
  16680. Engine.prototype.getExternalData = function (key) {
  16681. if (!this._externalData) {
  16682. this._externalData = new BABYLON.StringDictionary();
  16683. }
  16684. return this._externalData.get(key);
  16685. };
  16686. /**
  16687. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16688. * @param key the unique key that identifies the data
  16689. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16690. * @return the associated data, can be null if the factory returned null.
  16691. */
  16692. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16693. if (!this._externalData) {
  16694. this._externalData = new BABYLON.StringDictionary();
  16695. }
  16696. return this._externalData.getOrAddWithFactory(key, factory);
  16697. };
  16698. /**
  16699. * Remove an externaly attached data from the Engine instance
  16700. * @param key the unique key that identifies the data
  16701. * @return true if the data was successfully removed, false if it doesn't exist
  16702. */
  16703. Engine.prototype.removeExternalData = function (key) {
  16704. if (!this._externalData) {
  16705. this._externalData = new BABYLON.StringDictionary();
  16706. }
  16707. return this._externalData.remove(key);
  16708. };
  16709. /**
  16710. * Unbind all vertex attributes from the webGL context
  16711. */
  16712. Engine.prototype.unbindAllAttributes = function () {
  16713. if (this._mustWipeVertexAttributes) {
  16714. this._mustWipeVertexAttributes = false;
  16715. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16716. this._gl.disableVertexAttribArray(i);
  16717. this._vertexAttribArraysEnabled[i] = false;
  16718. this._currentBufferPointers[i].active = false;
  16719. }
  16720. return;
  16721. }
  16722. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16723. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16724. continue;
  16725. }
  16726. this._gl.disableVertexAttribArray(i);
  16727. this._vertexAttribArraysEnabled[i] = false;
  16728. this._currentBufferPointers[i].active = false;
  16729. }
  16730. };
  16731. /**
  16732. * 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
  16733. */
  16734. Engine.prototype.releaseEffects = function () {
  16735. for (var name in this._compiledEffects) {
  16736. this._deleteProgram(this._compiledEffects[name]._program);
  16737. }
  16738. this._compiledEffects = {};
  16739. };
  16740. /**
  16741. * Dispose and release all associated resources
  16742. */
  16743. Engine.prototype.dispose = function () {
  16744. this.hideLoadingUI();
  16745. this.stopRenderLoop();
  16746. // Release postProcesses
  16747. while (this.postProcesses.length) {
  16748. this.postProcesses[0].dispose();
  16749. }
  16750. // Empty texture
  16751. if (this._emptyTexture) {
  16752. this._releaseTexture(this._emptyTexture);
  16753. this._emptyTexture = null;
  16754. }
  16755. if (this._emptyCubeTexture) {
  16756. this._releaseTexture(this._emptyCubeTexture);
  16757. this._emptyCubeTexture = null;
  16758. }
  16759. // Rescale PP
  16760. if (this._rescalePostProcess) {
  16761. this._rescalePostProcess.dispose();
  16762. }
  16763. // Release scenes
  16764. while (this.scenes.length) {
  16765. this.scenes[0].dispose();
  16766. }
  16767. // Release audio engine
  16768. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16769. Engine.audioEngine.dispose();
  16770. }
  16771. // Release effects
  16772. this.releaseEffects();
  16773. // Unbind
  16774. this.unbindAllAttributes();
  16775. this._boundUniforms = [];
  16776. if (this._dummyFramebuffer) {
  16777. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16778. }
  16779. //WebVR
  16780. this.disableVR();
  16781. // Events
  16782. if (BABYLON.Tools.IsWindowObjectExist()) {
  16783. window.removeEventListener("blur", this._onBlur);
  16784. window.removeEventListener("focus", this._onFocus);
  16785. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16786. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16787. if (this._renderingCanvas) {
  16788. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16789. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16790. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16791. if (!this._doNotHandleContextLost) {
  16792. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16793. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16794. }
  16795. }
  16796. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16797. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16798. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16799. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16800. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16801. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16802. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16803. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16804. if (this._onVrDisplayConnect) {
  16805. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16806. if (this._onVrDisplayDisconnect) {
  16807. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16808. }
  16809. if (this._onVrDisplayPresentChange) {
  16810. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16811. }
  16812. this._onVrDisplayConnect = null;
  16813. this._onVrDisplayDisconnect = null;
  16814. }
  16815. }
  16816. // Remove from Instances
  16817. var index = Engine.Instances.indexOf(this);
  16818. if (index >= 0) {
  16819. Engine.Instances.splice(index, 1);
  16820. }
  16821. this._workingCanvas = null;
  16822. this._workingContext = null;
  16823. this._currentBufferPointers = [];
  16824. this._renderingCanvas = null;
  16825. this._currentProgram = null;
  16826. this._bindedRenderFunction = null;
  16827. this.onResizeObservable.clear();
  16828. this.onCanvasBlurObservable.clear();
  16829. this.onCanvasFocusObservable.clear();
  16830. this.onCanvasPointerOutObservable.clear();
  16831. this.onBeginFrameObservable.clear();
  16832. this.onEndFrameObservable.clear();
  16833. BABYLON.Effect.ResetCache();
  16834. // Abort active requests
  16835. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16836. var request = _a[_i];
  16837. request.abort();
  16838. }
  16839. };
  16840. // Loading screen
  16841. /**
  16842. * Display the loading screen
  16843. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16844. */
  16845. Engine.prototype.displayLoadingUI = function () {
  16846. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16847. return;
  16848. }
  16849. var loadingScreen = this.loadingScreen;
  16850. if (loadingScreen) {
  16851. loadingScreen.displayLoadingUI();
  16852. }
  16853. };
  16854. /**
  16855. * Hide the loading screen
  16856. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16857. */
  16858. Engine.prototype.hideLoadingUI = function () {
  16859. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16860. return;
  16861. }
  16862. var loadingScreen = this.loadingScreen;
  16863. if (loadingScreen) {
  16864. loadingScreen.hideLoadingUI();
  16865. }
  16866. };
  16867. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16868. /**
  16869. * Gets the current loading screen object
  16870. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16871. */
  16872. get: function () {
  16873. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16874. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16875. return this._loadingScreen;
  16876. },
  16877. /**
  16878. * Sets the current loading screen object
  16879. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16880. */
  16881. set: function (loadingScreen) {
  16882. this._loadingScreen = loadingScreen;
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16888. /**
  16889. * Sets the current loading screen text
  16890. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16891. */
  16892. set: function (text) {
  16893. this.loadingScreen.loadingUIText = text;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16899. /**
  16900. * Sets the current loading screen background color
  16901. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16902. */
  16903. set: function (color) {
  16904. this.loadingScreen.loadingUIBackgroundColor = color;
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. /**
  16910. * Attach a new callback raised when context lost event is fired
  16911. * @param callback defines the callback to call
  16912. */
  16913. Engine.prototype.attachContextLostEvent = function (callback) {
  16914. if (this._renderingCanvas) {
  16915. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16916. }
  16917. };
  16918. /**
  16919. * Attach a new callback raised when context restored event is fired
  16920. * @param callback defines the callback to call
  16921. */
  16922. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16923. if (this._renderingCanvas) {
  16924. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16925. }
  16926. };
  16927. /**
  16928. * Gets the source code of the vertex shader associated with a specific webGL program
  16929. * @param program defines the program to use
  16930. * @returns a string containing the source code of the vertex shader associated with the program
  16931. */
  16932. Engine.prototype.getVertexShaderSource = function (program) {
  16933. var shaders = this._gl.getAttachedShaders(program);
  16934. if (!shaders) {
  16935. return null;
  16936. }
  16937. return this._gl.getShaderSource(shaders[0]);
  16938. };
  16939. /**
  16940. * Gets the source code of the fragment shader associated with a specific webGL program
  16941. * @param program defines the program to use
  16942. * @returns a string containing the source code of the fragment shader associated with the program
  16943. */
  16944. Engine.prototype.getFragmentShaderSource = function (program) {
  16945. var shaders = this._gl.getAttachedShaders(program);
  16946. if (!shaders) {
  16947. return null;
  16948. }
  16949. return this._gl.getShaderSource(shaders[1]);
  16950. };
  16951. /**
  16952. * Get the current error code of the webGL context
  16953. * @returns the error code
  16954. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16955. */
  16956. Engine.prototype.getError = function () {
  16957. return this._gl.getError();
  16958. };
  16959. // FPS
  16960. /**
  16961. * Gets the current framerate
  16962. * @returns a number representing the framerate
  16963. */
  16964. Engine.prototype.getFps = function () {
  16965. return this._fps;
  16966. };
  16967. /**
  16968. * Gets the time spent between current and previous frame
  16969. * @returns a number representing the delta time in ms
  16970. */
  16971. Engine.prototype.getDeltaTime = function () {
  16972. return this._deltaTime;
  16973. };
  16974. Engine.prototype._measureFps = function () {
  16975. this._performanceMonitor.sampleFrame();
  16976. this._fps = this._performanceMonitor.averageFPS;
  16977. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16978. };
  16979. /** @hidden */
  16980. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16981. if (faceIndex === void 0) { faceIndex = -1; }
  16982. if (level === void 0) { level = 0; }
  16983. if (buffer === void 0) { buffer = null; }
  16984. var gl = this._gl;
  16985. if (!this._dummyFramebuffer) {
  16986. var dummy = gl.createFramebuffer();
  16987. if (!dummy) {
  16988. throw new Error("Unable to create dummy framebuffer");
  16989. }
  16990. this._dummyFramebuffer = dummy;
  16991. }
  16992. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16993. if (faceIndex > -1) {
  16994. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16995. }
  16996. else {
  16997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16998. }
  16999. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17000. switch (readType) {
  17001. case gl.UNSIGNED_BYTE:
  17002. if (!buffer) {
  17003. buffer = new Uint8Array(4 * width * height);
  17004. }
  17005. readType = gl.UNSIGNED_BYTE;
  17006. break;
  17007. default:
  17008. if (!buffer) {
  17009. buffer = new Float32Array(4 * width * height);
  17010. }
  17011. readType = gl.FLOAT;
  17012. break;
  17013. }
  17014. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17015. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17016. return buffer;
  17017. };
  17018. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17019. if (this._webGLVersion > 1) {
  17020. return this._caps.colorBufferFloat;
  17021. }
  17022. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17023. };
  17024. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17025. if (this._webGLVersion > 1) {
  17026. return this._caps.colorBufferFloat;
  17027. }
  17028. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17029. };
  17030. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17031. Engine.prototype._canRenderToFramebuffer = function (type) {
  17032. var gl = this._gl;
  17033. //clear existing errors
  17034. while (gl.getError() !== gl.NO_ERROR) { }
  17035. var successful = true;
  17036. var texture = gl.createTexture();
  17037. gl.bindTexture(gl.TEXTURE_2D, texture);
  17038. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17039. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17041. var fb = gl.createFramebuffer();
  17042. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17044. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17045. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17046. successful = successful && (gl.getError() === gl.NO_ERROR);
  17047. //try render by clearing frame buffer's color buffer
  17048. if (successful) {
  17049. gl.clear(gl.COLOR_BUFFER_BIT);
  17050. successful = successful && (gl.getError() === gl.NO_ERROR);
  17051. }
  17052. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17053. if (successful) {
  17054. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17055. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17056. var readFormat = gl.RGBA;
  17057. var readType = gl.UNSIGNED_BYTE;
  17058. var buffer = new Uint8Array(4);
  17059. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17060. successful = successful && (gl.getError() === gl.NO_ERROR);
  17061. }
  17062. //clean up
  17063. gl.deleteTexture(texture);
  17064. gl.deleteFramebuffer(fb);
  17065. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17066. //clear accumulated errors
  17067. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17068. return successful;
  17069. };
  17070. /** @hidden */
  17071. Engine.prototype._getWebGLTextureType = function (type) {
  17072. if (this._webGLVersion === 1) {
  17073. switch (type) {
  17074. case Engine.TEXTURETYPE_FLOAT:
  17075. return this._gl.FLOAT;
  17076. case Engine.TEXTURETYPE_HALF_FLOAT:
  17077. return this._gl.HALF_FLOAT_OES;
  17078. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17079. return this._gl.UNSIGNED_BYTE;
  17080. }
  17081. return this._gl.UNSIGNED_BYTE;
  17082. }
  17083. switch (type) {
  17084. case Engine.TEXTURETYPE_BYTE:
  17085. return this._gl.BYTE;
  17086. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17087. return this._gl.UNSIGNED_BYTE;
  17088. case Engine.TEXTURETYPE_SHORT:
  17089. return this._gl.SHORT;
  17090. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17091. return this._gl.UNSIGNED_SHORT;
  17092. case Engine.TEXTURETYPE_INT:
  17093. return this._gl.INT;
  17094. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17095. return this._gl.UNSIGNED_INT;
  17096. case Engine.TEXTURETYPE_FLOAT:
  17097. return this._gl.FLOAT;
  17098. case Engine.TEXTURETYPE_HALF_FLOAT:
  17099. return this._gl.HALF_FLOAT;
  17100. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17101. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17102. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17103. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17104. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17105. return this._gl.UNSIGNED_SHORT_5_6_5;
  17106. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17107. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17108. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17109. return this._gl.UNSIGNED_INT_24_8;
  17110. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17111. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17112. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17113. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17114. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17115. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17116. }
  17117. return this._gl.UNSIGNED_BYTE;
  17118. };
  17119. ;
  17120. Engine.prototype._getInternalFormat = function (format) {
  17121. var internalFormat = this._gl.RGBA;
  17122. switch (format) {
  17123. case Engine.TEXTUREFORMAT_ALPHA:
  17124. internalFormat = this._gl.ALPHA;
  17125. break;
  17126. case Engine.TEXTUREFORMAT_LUMINANCE:
  17127. internalFormat = this._gl.LUMINANCE;
  17128. break;
  17129. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17130. internalFormat = this._gl.LUMINANCE_ALPHA;
  17131. break;
  17132. case Engine.TEXTUREFORMAT_RED:
  17133. internalFormat = this._gl.RED;
  17134. break;
  17135. case Engine.TEXTUREFORMAT_RG:
  17136. internalFormat = this._gl.RG;
  17137. break;
  17138. case Engine.TEXTUREFORMAT_RGB:
  17139. internalFormat = this._gl.RGB;
  17140. break;
  17141. case Engine.TEXTUREFORMAT_RGBA:
  17142. internalFormat = this._gl.RGBA;
  17143. break;
  17144. }
  17145. if (this._webGLVersion > 1) {
  17146. switch (format) {
  17147. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17148. internalFormat = this._gl.RED_INTEGER;
  17149. break;
  17150. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17151. internalFormat = this._gl.RG_INTEGER;
  17152. break;
  17153. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17154. internalFormat = this._gl.RGB_INTEGER;
  17155. break;
  17156. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17157. internalFormat = this._gl.RGBA_INTEGER;
  17158. break;
  17159. }
  17160. }
  17161. return internalFormat;
  17162. };
  17163. /** @hidden */
  17164. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17165. if (this._webGLVersion === 1) {
  17166. if (format !== undefined) {
  17167. switch (format) {
  17168. case Engine.TEXTUREFORMAT_ALPHA:
  17169. return this._gl.ALPHA;
  17170. case Engine.TEXTUREFORMAT_LUMINANCE:
  17171. return this._gl.LUMINANCE;
  17172. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17173. return this._gl.LUMINANCE_ALPHA;
  17174. }
  17175. }
  17176. return this._gl.RGBA;
  17177. }
  17178. switch (type) {
  17179. case Engine.TEXTURETYPE_BYTE:
  17180. switch (format) {
  17181. case Engine.TEXTUREFORMAT_RED:
  17182. return this._gl.R8_SNORM;
  17183. case Engine.TEXTUREFORMAT_RG:
  17184. return this._gl.RG8_SNORM;
  17185. case Engine.TEXTUREFORMAT_RGB:
  17186. return this._gl.RGB8_SNORM;
  17187. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17188. return this._gl.R8I;
  17189. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17190. return this._gl.RG8I;
  17191. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17192. return this._gl.RGB8I;
  17193. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17194. return this._gl.RGBA8I;
  17195. default:
  17196. return this._gl.RGBA8_SNORM;
  17197. }
  17198. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17199. switch (format) {
  17200. case Engine.TEXTUREFORMAT_RED:
  17201. return this._gl.R8;
  17202. case Engine.TEXTUREFORMAT_RG:
  17203. return this._gl.RG8;
  17204. case Engine.TEXTUREFORMAT_RGB:
  17205. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17206. case Engine.TEXTUREFORMAT_RGBA:
  17207. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17208. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17209. return this._gl.R8UI;
  17210. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17211. return this._gl.RG8UI;
  17212. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17213. return this._gl.RGB8UI;
  17214. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17215. return this._gl.RGBA8UI;
  17216. default:
  17217. return this._gl.RGBA8;
  17218. }
  17219. case Engine.TEXTURETYPE_SHORT:
  17220. switch (format) {
  17221. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17222. return this._gl.R16I;
  17223. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17224. return this._gl.RG16I;
  17225. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17226. return this._gl.RGB16I;
  17227. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17228. return this._gl.RGBA16I;
  17229. default:
  17230. return this._gl.RGBA16I;
  17231. }
  17232. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17233. switch (format) {
  17234. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17235. return this._gl.R16UI;
  17236. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17237. return this._gl.RG16UI;
  17238. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17239. return this._gl.RGB16UI;
  17240. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17241. return this._gl.RGBA16UI;
  17242. default:
  17243. return this._gl.RGBA16UI;
  17244. }
  17245. case Engine.TEXTURETYPE_INT:
  17246. switch (format) {
  17247. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17248. return this._gl.R32I;
  17249. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17250. return this._gl.RG32I;
  17251. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17252. return this._gl.RGB32I;
  17253. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17254. return this._gl.RGBA32I;
  17255. default:
  17256. return this._gl.RGBA32I;
  17257. }
  17258. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17259. switch (format) {
  17260. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17261. return this._gl.R32UI;
  17262. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17263. return this._gl.RG32UI;
  17264. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17265. return this._gl.RGB32UI;
  17266. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17267. return this._gl.RGBA32UI;
  17268. default:
  17269. return this._gl.RGBA32UI;
  17270. }
  17271. case Engine.TEXTURETYPE_FLOAT:
  17272. switch (format) {
  17273. case Engine.TEXTUREFORMAT_RED:
  17274. return this._gl.R32F; // By default. Other possibility is R16F.
  17275. case Engine.TEXTUREFORMAT_RG:
  17276. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17277. case Engine.TEXTUREFORMAT_RGB:
  17278. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17279. case Engine.TEXTUREFORMAT_RGBA:
  17280. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17281. default:
  17282. return this._gl.RGBA32F;
  17283. }
  17284. case Engine.TEXTURETYPE_HALF_FLOAT:
  17285. switch (format) {
  17286. case Engine.TEXTUREFORMAT_RED:
  17287. return this._gl.R16F;
  17288. case Engine.TEXTUREFORMAT_RG:
  17289. return this._gl.RG16F;
  17290. case Engine.TEXTUREFORMAT_RGB:
  17291. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17292. case Engine.TEXTUREFORMAT_RGBA:
  17293. return this._gl.RGBA16F;
  17294. default:
  17295. return this._gl.RGBA16F;
  17296. }
  17297. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17298. return this._gl.RGB565;
  17299. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17300. return this._gl.R11F_G11F_B10F;
  17301. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17302. return this._gl.RGB9_E5;
  17303. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17304. return this._gl.RGBA4;
  17305. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17306. return this._gl.RGB5_A1;
  17307. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17308. switch (format) {
  17309. case Engine.TEXTUREFORMAT_RGBA:
  17310. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17311. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17312. return this._gl.RGB10_A2UI;
  17313. default:
  17314. return this._gl.RGB10_A2;
  17315. }
  17316. }
  17317. return this._gl.RGBA8;
  17318. };
  17319. ;
  17320. /** @hidden */
  17321. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17322. if (type === Engine.TEXTURETYPE_FLOAT) {
  17323. return this._gl.RGBA32F;
  17324. }
  17325. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17326. return this._gl.RGBA16F;
  17327. }
  17328. return this._gl.RGBA8;
  17329. };
  17330. ;
  17331. /** @hidden */
  17332. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17333. var _this = this;
  17334. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17335. this._activeRequests.push(request);
  17336. request.onCompleteObservable.add(function (request) {
  17337. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17338. });
  17339. return request;
  17340. };
  17341. /** @hidden */
  17342. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17343. var _this = this;
  17344. return new Promise(function (resolve, reject) {
  17345. _this._loadFile(url, function (data) {
  17346. resolve(data);
  17347. }, undefined, database, useArrayBuffer, function (request, exception) {
  17348. reject(exception);
  17349. });
  17350. });
  17351. };
  17352. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17353. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17354. var onload = function (data) {
  17355. loadedFiles[index] = data;
  17356. loadedFiles._internalCount++;
  17357. if (loadedFiles._internalCount === 6) {
  17358. onfinish(loadedFiles);
  17359. }
  17360. };
  17361. var onerror = function (request, exception) {
  17362. if (onErrorCallBack && request) {
  17363. onErrorCallBack(request.status + " " + request.statusText, exception);
  17364. }
  17365. };
  17366. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17367. };
  17368. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17369. if (onError === void 0) { onError = null; }
  17370. var loadedFiles = [];
  17371. loadedFiles._internalCount = 0;
  17372. for (var index = 0; index < 6; index++) {
  17373. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17374. }
  17375. };
  17376. // Statics
  17377. /**
  17378. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17379. * @returns true if the engine can be created
  17380. * @ignorenaming
  17381. */
  17382. Engine.isSupported = function () {
  17383. try {
  17384. var tempcanvas = document.createElement("canvas");
  17385. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17386. return gl != null && !!window.WebGLRenderingContext;
  17387. }
  17388. catch (e) {
  17389. return false;
  17390. }
  17391. };
  17392. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17393. Engine.ExceptionList = [
  17394. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17395. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17396. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17397. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17398. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17399. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17400. ];
  17401. /** Gets the list of created engines */
  17402. Engine.Instances = new Array();
  17403. /**
  17404. * Hidden
  17405. */
  17406. Engine._TextureLoaders = [];
  17407. // Const statics
  17408. /** Defines that alpha blending is disabled */
  17409. Engine.ALPHA_DISABLE = 0;
  17410. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17411. Engine.ALPHA_ADD = 1;
  17412. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17413. Engine.ALPHA_COMBINE = 2;
  17414. /** Defines that alpha blending to DEST - SRC * DEST */
  17415. Engine.ALPHA_SUBTRACT = 3;
  17416. /** Defines that alpha blending to SRC * DEST */
  17417. Engine.ALPHA_MULTIPLY = 4;
  17418. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17419. Engine.ALPHA_MAXIMIZED = 5;
  17420. /** Defines that alpha blending to SRC + DEST */
  17421. Engine.ALPHA_ONEONE = 6;
  17422. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17423. Engine.ALPHA_PREMULTIPLIED = 7;
  17424. /**
  17425. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17426. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17427. */
  17428. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17429. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17430. Engine.ALPHA_INTERPOLATE = 9;
  17431. /**
  17432. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17433. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17434. */
  17435. Engine.ALPHA_SCREENMODE = 10;
  17436. /** Defines that the ressource is not delayed*/
  17437. Engine.DELAYLOADSTATE_NONE = 0;
  17438. /** Defines that the ressource was successfully delay loaded */
  17439. Engine.DELAYLOADSTATE_LOADED = 1;
  17440. /** Defines that the ressource is currently delay loading */
  17441. Engine.DELAYLOADSTATE_LOADING = 2;
  17442. /** Defines that the ressource is delayed and has not started loading */
  17443. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17444. // Depht or Stencil test Constants.
  17445. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17446. Engine.NEVER = 0x0200;
  17447. /** 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 */
  17448. Engine.ALWAYS = 0x0207;
  17449. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17450. Engine.LESS = 0x0201;
  17451. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17452. Engine.EQUAL = 0x0202;
  17453. /** 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 */
  17454. Engine.LEQUAL = 0x0203;
  17455. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17456. Engine.GREATER = 0x0204;
  17457. /** 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 */
  17458. Engine.GEQUAL = 0x0206;
  17459. /** 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 */
  17460. Engine.NOTEQUAL = 0x0205;
  17461. // Stencil Actions Constants.
  17462. /** Passed to stencilOperation to specify that stencil value must be kept */
  17463. Engine.KEEP = 0x1E00;
  17464. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17465. Engine.REPLACE = 0x1E01;
  17466. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17467. Engine.INCR = 0x1E02;
  17468. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17469. Engine.DECR = 0x1E03;
  17470. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17471. Engine.INVERT = 0x150A;
  17472. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17473. Engine.INCR_WRAP = 0x8507;
  17474. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17475. Engine.DECR_WRAP = 0x8508;
  17476. /** Texture is not repeating outside of 0..1 UVs */
  17477. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17478. /** Texture is repeating outside of 0..1 UVs */
  17479. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17480. /** Texture is repeating and mirrored */
  17481. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17482. /** ALPHA */
  17483. Engine.TEXTUREFORMAT_ALPHA = 0;
  17484. /** LUMINANCE */
  17485. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17486. /** LUMINANCE_ALPHA */
  17487. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17488. /** RGB */
  17489. Engine.TEXTUREFORMAT_RGB = 4;
  17490. /** RGBA */
  17491. Engine.TEXTUREFORMAT_RGBA = 5;
  17492. /** RED */
  17493. Engine.TEXTUREFORMAT_RED = 6;
  17494. /** RED (2nd reference) */
  17495. Engine.TEXTUREFORMAT_R = 6;
  17496. /** RG */
  17497. Engine.TEXTUREFORMAT_RG = 7;
  17498. /** RED_INTEGER */
  17499. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17500. /** RED_INTEGER (2nd reference) */
  17501. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17502. /** RG_INTEGER */
  17503. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17504. /** RGB_INTEGER */
  17505. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17506. /** RGBA_INTEGER */
  17507. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17508. /** UNSIGNED_BYTE */
  17509. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17510. /** UNSIGNED_BYTE (2nd reference) */
  17511. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17512. /** FLOAT */
  17513. Engine.TEXTURETYPE_FLOAT = 1;
  17514. /** HALF_FLOAT */
  17515. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17516. /** BYTE */
  17517. Engine.TEXTURETYPE_BYTE = 3;
  17518. /** SHORT */
  17519. Engine.TEXTURETYPE_SHORT = 4;
  17520. /** UNSIGNED_SHORT */
  17521. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17522. /** INT */
  17523. Engine.TEXTURETYPE_INT = 6;
  17524. /** UNSIGNED_INT */
  17525. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17526. /** UNSIGNED_SHORT_4_4_4_4 */
  17527. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17528. /** UNSIGNED_SHORT_5_5_5_1 */
  17529. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17530. /** UNSIGNED_SHORT_5_6_5 */
  17531. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17532. /** UNSIGNED_INT_2_10_10_10_REV */
  17533. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17534. /** UNSIGNED_INT_24_8 */
  17535. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17536. /** UNSIGNED_INT_10F_11F_11F_REV */
  17537. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17538. /** UNSIGNED_INT_5_9_9_9_REV */
  17539. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17540. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17541. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17542. /** nearest is mag = nearest and min = nearest and mip = linear */
  17543. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17544. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17545. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17546. /** Trilinear is mag = linear and min = linear and mip = linear */
  17547. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17548. /** nearest is mag = nearest and min = nearest and mip = linear */
  17549. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17550. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17551. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17552. /** Trilinear is mag = linear and min = linear and mip = linear */
  17553. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17554. /** mag = nearest and min = nearest and mip = nearest */
  17555. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17556. /** mag = nearest and min = linear and mip = nearest */
  17557. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17558. /** mag = nearest and min = linear and mip = linear */
  17559. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17560. /** mag = nearest and min = linear and mip = none */
  17561. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17562. /** mag = nearest and min = nearest and mip = none */
  17563. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17564. /** mag = linear and min = nearest and mip = nearest */
  17565. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17566. /** mag = linear and min = nearest and mip = linear */
  17567. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17568. /** mag = linear and min = linear and mip = none */
  17569. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17570. /** mag = linear and min = nearest and mip = none */
  17571. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17572. /** Explicit coordinates mode */
  17573. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17574. /** Spherical coordinates mode */
  17575. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17576. /** Planar coordinates mode */
  17577. Engine.TEXTURE_PLANAR_MODE = 2;
  17578. /** Cubic coordinates mode */
  17579. Engine.TEXTURE_CUBIC_MODE = 3;
  17580. /** Projection coordinates mode */
  17581. Engine.TEXTURE_PROJECTION_MODE = 4;
  17582. /** Skybox coordinates mode */
  17583. Engine.TEXTURE_SKYBOX_MODE = 5;
  17584. /** Inverse Cubic coordinates mode */
  17585. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17586. /** Equirectangular coordinates mode */
  17587. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17588. /** Equirectangular Fixed coordinates mode */
  17589. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17590. /** Equirectangular Fixed Mirrored coordinates mode */
  17591. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17592. // Texture rescaling mode
  17593. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17594. Engine.SCALEMODE_FLOOR = 1;
  17595. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17596. Engine.SCALEMODE_NEAREST = 2;
  17597. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17598. Engine.SCALEMODE_CEILING = 3;
  17599. // Updatable statics so stick with vars here
  17600. /**
  17601. * Gets or sets the epsilon value used by collision engine
  17602. */
  17603. Engine.CollisionsEpsilon = 0.001;
  17604. /**
  17605. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17606. */
  17607. Engine.CodeRepository = "src/";
  17608. /**
  17609. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17610. */
  17611. Engine.ShadersRepository = "src/Shaders/";
  17612. return Engine;
  17613. }());
  17614. BABYLON.Engine = Engine;
  17615. })(BABYLON || (BABYLON = {}));
  17616. //# sourceMappingURL=babylon.engine.js.map
  17617. var BABYLON;
  17618. (function (BABYLON) {
  17619. /**
  17620. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17621. */
  17622. var Node = /** @class */ (function () {
  17623. /**
  17624. * Creates a new Node
  17625. * @param {string} name - the name and id to be given to this node
  17626. * @param {BABYLON.Scene} the scene this node will be added to
  17627. */
  17628. function Node(name, scene) {
  17629. if (scene === void 0) { scene = null; }
  17630. /**
  17631. * Gets or sets a string used to store user defined state for the node
  17632. */
  17633. this.state = "";
  17634. /**
  17635. * Gets or sets an object used to store user defined information for the node
  17636. */
  17637. this.metadata = null;
  17638. /**
  17639. * Gets or sets a boolean used to define if the node must be serialized
  17640. */
  17641. this.doNotSerialize = false;
  17642. /** @hidden */
  17643. this._isDisposed = false;
  17644. /**
  17645. * Gets a list of Animations associated with the node
  17646. */
  17647. this.animations = new Array();
  17648. this._ranges = {};
  17649. this._isEnabled = true;
  17650. this._isParentEnabled = true;
  17651. this._isReady = true;
  17652. /** @hidden */
  17653. this._currentRenderId = -1;
  17654. this._parentRenderId = -1;
  17655. this._childRenderId = -1;
  17656. /** @hidden */
  17657. this._worldMatrix = BABYLON.Matrix.Identity();
  17658. /** @hidden */
  17659. this._worldMatrixDeterminant = 0;
  17660. this._animationPropertiesOverride = null;
  17661. /**
  17662. * An event triggered when the mesh is disposed
  17663. */
  17664. this.onDisposeObservable = new BABYLON.Observable();
  17665. // Behaviors
  17666. this._behaviors = new Array();
  17667. this.name = name;
  17668. this.id = name;
  17669. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17670. this.uniqueId = this._scene.getUniqueId();
  17671. this._initCache();
  17672. this._scene.rootNodes.push(this);
  17673. }
  17674. /**
  17675. * Add a new node constructor
  17676. * @param type defines the type name of the node to construct
  17677. * @param constructorFunc defines the constructor function
  17678. */
  17679. Node.AddNodeConstructor = function (type, constructorFunc) {
  17680. this._NodeConstructors[type] = constructorFunc;
  17681. };
  17682. /**
  17683. * Returns a node constructor based on type name
  17684. * @param type defines the type name
  17685. * @param name defines the new node name
  17686. * @param scene defines the hosting scene
  17687. * @param options defines optional options to transmit to constructors
  17688. * @returns the new constructor or null
  17689. */
  17690. Node.Construct = function (type, name, scene, options) {
  17691. var constructorFunc = this._NodeConstructors[type];
  17692. if (!constructorFunc) {
  17693. return null;
  17694. }
  17695. return constructorFunc(name, scene, options);
  17696. };
  17697. /**
  17698. * Gets a boolean indicating if the node has been disposed
  17699. * @returns true if the node was disposed
  17700. */
  17701. Node.prototype.isDisposed = function () {
  17702. return this._isDisposed;
  17703. };
  17704. Object.defineProperty(Node.prototype, "parent", {
  17705. get: function () {
  17706. return this._parentNode;
  17707. },
  17708. /**
  17709. * Gets or sets the parent of the node
  17710. */
  17711. set: function (parent) {
  17712. if (this._parentNode === parent) {
  17713. return;
  17714. }
  17715. var previousParentNode = this._parentNode;
  17716. // Remove self from list of children of parent
  17717. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17718. var index = this._parentNode._children.indexOf(this);
  17719. if (index !== -1) {
  17720. this._parentNode._children.splice(index, 1);
  17721. }
  17722. if (!parent) {
  17723. // Need to add this node to the rootNodes
  17724. this._scene.rootNodes.push(this);
  17725. }
  17726. }
  17727. // Store new parent
  17728. this._parentNode = parent;
  17729. // Add as child to new parent
  17730. if (this._parentNode) {
  17731. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17732. this._parentNode._children = new Array();
  17733. }
  17734. this._parentNode._children.push(this);
  17735. if (!previousParentNode) {
  17736. // Need to remove from rootNodes
  17737. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17738. if (rootNodeIndex > -1) {
  17739. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17740. }
  17741. }
  17742. }
  17743. // Enabled state
  17744. this._syncParentEnabledState();
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17750. /**
  17751. * Gets or sets the animation properties override
  17752. */
  17753. get: function () {
  17754. if (!this._animationPropertiesOverride) {
  17755. return this._scene.animationPropertiesOverride;
  17756. }
  17757. return this._animationPropertiesOverride;
  17758. },
  17759. set: function (value) {
  17760. this._animationPropertiesOverride = value;
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. /**
  17766. * Gets a string idenfifying the name of the class
  17767. * @returns "Node" string
  17768. */
  17769. Node.prototype.getClassName = function () {
  17770. return "Node";
  17771. };
  17772. Object.defineProperty(Node.prototype, "onDispose", {
  17773. /**
  17774. * Sets a callback that will be raised when the node will be disposed
  17775. */
  17776. set: function (callback) {
  17777. if (this._onDisposeObserver) {
  17778. this.onDisposeObservable.remove(this._onDisposeObserver);
  17779. }
  17780. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17781. },
  17782. enumerable: true,
  17783. configurable: true
  17784. });
  17785. /**
  17786. * Gets the scene of the node
  17787. * @returns a {BABYLON.Scene}
  17788. */
  17789. Node.prototype.getScene = function () {
  17790. return this._scene;
  17791. };
  17792. /**
  17793. * Gets the engine of the node
  17794. * @returns a {BABYLON.Engine}
  17795. */
  17796. Node.prototype.getEngine = function () {
  17797. return this._scene.getEngine();
  17798. };
  17799. /**
  17800. * Attach a behavior to the node
  17801. * @see http://doc.babylonjs.com/features/behaviour
  17802. * @param behavior defines the behavior to attach
  17803. * @returns the current Node
  17804. */
  17805. Node.prototype.addBehavior = function (behavior) {
  17806. var _this = this;
  17807. var index = this._behaviors.indexOf(behavior);
  17808. if (index !== -1) {
  17809. return this;
  17810. }
  17811. behavior.init();
  17812. if (this._scene.isLoading) {
  17813. // We defer the attach when the scene will be loaded
  17814. this._scene.onDataLoadedObservable.addOnce(function () {
  17815. behavior.attach(_this);
  17816. });
  17817. }
  17818. else {
  17819. behavior.attach(this);
  17820. }
  17821. this._behaviors.push(behavior);
  17822. return this;
  17823. };
  17824. /**
  17825. * Remove an attached behavior
  17826. * @see http://doc.babylonjs.com/features/behaviour
  17827. * @param behavior defines the behavior to attach
  17828. * @returns the current Node
  17829. */
  17830. Node.prototype.removeBehavior = function (behavior) {
  17831. var index = this._behaviors.indexOf(behavior);
  17832. if (index === -1) {
  17833. return this;
  17834. }
  17835. this._behaviors[index].detach();
  17836. this._behaviors.splice(index, 1);
  17837. return this;
  17838. };
  17839. Object.defineProperty(Node.prototype, "behaviors", {
  17840. /**
  17841. * Gets the list of attached behaviors
  17842. * @see http://doc.babylonjs.com/features/behaviour
  17843. */
  17844. get: function () {
  17845. return this._behaviors;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. /**
  17851. * Gets an attached behavior by name
  17852. * @param name defines the name of the behavior to look for
  17853. * @see http://doc.babylonjs.com/features/behaviour
  17854. * @returns null if behavior was not found else the requested behavior
  17855. */
  17856. Node.prototype.getBehaviorByName = function (name) {
  17857. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17858. var behavior = _a[_i];
  17859. if (behavior.name === name) {
  17860. return behavior;
  17861. }
  17862. }
  17863. return null;
  17864. };
  17865. /**
  17866. * Returns the latest update of the World matrix
  17867. * @returns a Matrix
  17868. */
  17869. Node.prototype.getWorldMatrix = function () {
  17870. if (this._currentRenderId !== this._scene.getRenderId()) {
  17871. this.computeWorldMatrix();
  17872. }
  17873. return this._worldMatrix;
  17874. };
  17875. /** @hidden */
  17876. Node.prototype._getWorldMatrixDeterminant = function () {
  17877. return this._worldMatrixDeterminant;
  17878. };
  17879. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17880. /**
  17881. * Returns directly the latest state of the mesh World matrix.
  17882. * A Matrix is returned.
  17883. */
  17884. get: function () {
  17885. return this._worldMatrix;
  17886. },
  17887. enumerable: true,
  17888. configurable: true
  17889. });
  17890. // override it in derived class if you add new variables to the cache
  17891. // and call the parent class method
  17892. /** @hidden */
  17893. Node.prototype._initCache = function () {
  17894. this._cache = {};
  17895. this._cache.parent = undefined;
  17896. };
  17897. /** @hidden */
  17898. Node.prototype.updateCache = function (force) {
  17899. if (!force && this.isSynchronized())
  17900. return;
  17901. this._cache.parent = this.parent;
  17902. this._updateCache();
  17903. };
  17904. // override it in derived class if you add new variables to the cache
  17905. // and call the parent class method if !ignoreParentClass
  17906. /** @hidden */
  17907. Node.prototype._updateCache = function (ignoreParentClass) {
  17908. };
  17909. // override it in derived class if you add new variables to the cache
  17910. /** @hidden */
  17911. Node.prototype._isSynchronized = function () {
  17912. return true;
  17913. };
  17914. /** @hidden */
  17915. Node.prototype._markSyncedWithParent = function () {
  17916. if (this._parentNode) {
  17917. this._parentRenderId = this._parentNode._childRenderId;
  17918. }
  17919. };
  17920. /** @hidden */
  17921. Node.prototype.isSynchronizedWithParent = function () {
  17922. if (!this._parentNode) {
  17923. return true;
  17924. }
  17925. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17926. return false;
  17927. }
  17928. return this._parentNode.isSynchronized();
  17929. };
  17930. /** @hidden */
  17931. Node.prototype.isSynchronized = function () {
  17932. if (this._cache.parent != this._parentNode) {
  17933. this._cache.parent = this._parentNode;
  17934. return false;
  17935. }
  17936. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17937. return false;
  17938. }
  17939. return this._isSynchronized();
  17940. };
  17941. /**
  17942. * Is this node ready to be used/rendered
  17943. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17944. * @return true if the node is ready
  17945. */
  17946. Node.prototype.isReady = function (completeCheck) {
  17947. if (completeCheck === void 0) { completeCheck = false; }
  17948. return this._isReady;
  17949. };
  17950. /**
  17951. * Is this node enabled?
  17952. * 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
  17953. * @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
  17954. * @return whether this node (and its parent) is enabled
  17955. */
  17956. Node.prototype.isEnabled = function (checkAncestors) {
  17957. if (checkAncestors === void 0) { checkAncestors = true; }
  17958. if (checkAncestors === false) {
  17959. return this._isEnabled;
  17960. }
  17961. if (!this._isEnabled) {
  17962. return false;
  17963. }
  17964. return this._isParentEnabled;
  17965. };
  17966. /** @hidden */
  17967. Node.prototype._syncParentEnabledState = function () {
  17968. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17969. if (this._children) {
  17970. this._children.forEach(function (c) {
  17971. c._syncParentEnabledState(); // Force children to update accordingly
  17972. });
  17973. }
  17974. };
  17975. /**
  17976. * Set the enabled state of this node
  17977. * @param value defines the new enabled state
  17978. */
  17979. Node.prototype.setEnabled = function (value) {
  17980. this._isEnabled = value;
  17981. this._syncParentEnabledState();
  17982. };
  17983. /**
  17984. * Is this node a descendant of the given node?
  17985. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17986. * @param ancestor defines the parent node to inspect
  17987. * @returns a boolean indicating if this node is a descendant of the given node
  17988. */
  17989. Node.prototype.isDescendantOf = function (ancestor) {
  17990. if (this.parent) {
  17991. if (this.parent === ancestor) {
  17992. return true;
  17993. }
  17994. return this.parent.isDescendantOf(ancestor);
  17995. }
  17996. return false;
  17997. };
  17998. /** @hidden */
  17999. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18000. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18001. if (!this._children) {
  18002. return;
  18003. }
  18004. for (var index = 0; index < this._children.length; index++) {
  18005. var item = this._children[index];
  18006. if (!predicate || predicate(item)) {
  18007. results.push(item);
  18008. }
  18009. if (!directDescendantsOnly) {
  18010. item._getDescendants(results, false, predicate);
  18011. }
  18012. }
  18013. };
  18014. /**
  18015. * Will return all nodes that have this node as ascendant
  18016. * @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
  18017. * @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
  18018. * @return all children nodes of all types
  18019. */
  18020. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18021. var results = new Array();
  18022. this._getDescendants(results, directDescendantsOnly, predicate);
  18023. return results;
  18024. };
  18025. /**
  18026. * Get all child-meshes of this node
  18027. * @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
  18028. * @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
  18029. * @returns an array of {BABYLON.AbstractMesh}
  18030. */
  18031. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18032. var results = [];
  18033. this._getDescendants(results, directDescendantsOnly, function (node) {
  18034. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18035. });
  18036. return results;
  18037. };
  18038. /**
  18039. * Get all child-transformNodes of this node
  18040. * @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
  18041. * @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
  18042. * @returns an array of {BABYLON.TransformNode}
  18043. */
  18044. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18045. var results = [];
  18046. this._getDescendants(results, directDescendantsOnly, function (node) {
  18047. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18048. });
  18049. return results;
  18050. };
  18051. /**
  18052. * Get all direct children of this node
  18053. * @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
  18054. * @returns an array of {BABYLON.Node}
  18055. */
  18056. Node.prototype.getChildren = function (predicate) {
  18057. if (!predicate) {
  18058. return this._children;
  18059. }
  18060. return this.getDescendants(true, predicate);
  18061. };
  18062. /** @hidden */
  18063. Node.prototype._setReady = function (state) {
  18064. if (state === this._isReady) {
  18065. return;
  18066. }
  18067. if (!state) {
  18068. this._isReady = false;
  18069. return;
  18070. }
  18071. if (this.onReady) {
  18072. this.onReady(this);
  18073. }
  18074. this._isReady = true;
  18075. };
  18076. /**
  18077. * Get an animation by name
  18078. * @param name defines the name of the animation to look for
  18079. * @returns null if not found else the requested animation
  18080. */
  18081. Node.prototype.getAnimationByName = function (name) {
  18082. for (var i = 0; i < this.animations.length; i++) {
  18083. var animation = this.animations[i];
  18084. if (animation.name === name) {
  18085. return animation;
  18086. }
  18087. }
  18088. return null;
  18089. };
  18090. /**
  18091. * Creates an animation range for this node
  18092. * @param name defines the name of the range
  18093. * @param from defines the starting key
  18094. * @param to defines the end key
  18095. */
  18096. Node.prototype.createAnimationRange = function (name, from, to) {
  18097. // check name not already in use
  18098. if (!this._ranges[name]) {
  18099. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18100. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18101. if (this.animations[i]) {
  18102. this.animations[i].createRange(name, from, to);
  18103. }
  18104. }
  18105. }
  18106. };
  18107. /**
  18108. * Delete a specific animation range
  18109. * @param name defines the name of the range to delete
  18110. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18111. */
  18112. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18113. if (deleteFrames === void 0) { deleteFrames = true; }
  18114. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18115. if (this.animations[i]) {
  18116. this.animations[i].deleteRange(name, deleteFrames);
  18117. }
  18118. }
  18119. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18120. };
  18121. /**
  18122. * Get an animation range by name
  18123. * @param name defines the name of the animation range to look for
  18124. * @returns null if not found else the requested animation range
  18125. */
  18126. Node.prototype.getAnimationRange = function (name) {
  18127. return this._ranges[name];
  18128. };
  18129. /**
  18130. * Will start the animation sequence
  18131. * @param name defines the range frames for animation sequence
  18132. * @param loop defines if the animation should loop (false by default)
  18133. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18134. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18135. * @returns the object created for this animation. If range does not exist, it will return null
  18136. */
  18137. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18138. var range = this.getAnimationRange(name);
  18139. if (!range) {
  18140. return null;
  18141. }
  18142. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18143. };
  18144. /**
  18145. * Serialize animation ranges into a JSON compatible object
  18146. * @returns serialization object
  18147. */
  18148. Node.prototype.serializeAnimationRanges = function () {
  18149. var serializationRanges = [];
  18150. for (var name in this._ranges) {
  18151. var localRange = this._ranges[name];
  18152. if (!localRange) {
  18153. continue;
  18154. }
  18155. var range = {};
  18156. range.name = name;
  18157. range.from = localRange.from;
  18158. range.to = localRange.to;
  18159. serializationRanges.push(range);
  18160. }
  18161. return serializationRanges;
  18162. };
  18163. /**
  18164. * Computes the world matrix of the node
  18165. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18166. * @returns the world matrix
  18167. */
  18168. Node.prototype.computeWorldMatrix = function (force) {
  18169. if (!this._worldMatrix) {
  18170. this._worldMatrix = BABYLON.Matrix.Identity();
  18171. }
  18172. return this._worldMatrix;
  18173. };
  18174. /**
  18175. * Releases resources associated with this node.
  18176. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18177. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18178. */
  18179. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18180. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18181. if (!doNotRecurse) {
  18182. var nodes = this.getDescendants(true);
  18183. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18184. var node = nodes_1[_i];
  18185. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18186. }
  18187. }
  18188. else {
  18189. var transformNodes = this.getChildTransformNodes(true);
  18190. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18191. var transformNode = transformNodes_1[_a];
  18192. transformNode.parent = null;
  18193. transformNode.computeWorldMatrix(true);
  18194. }
  18195. }
  18196. if (!this.parent) {
  18197. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18198. if (rootNodeIndex > -1) {
  18199. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18200. }
  18201. }
  18202. else {
  18203. this.parent = null;
  18204. }
  18205. // Callback
  18206. this.onDisposeObservable.notifyObservers(this);
  18207. this.onDisposeObservable.clear();
  18208. // Behaviors
  18209. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18210. var behavior = _c[_b];
  18211. behavior.detach();
  18212. }
  18213. this._behaviors = [];
  18214. this._isDisposed = true;
  18215. };
  18216. /**
  18217. * Parse animation range data from a serialization object and store them into a given node
  18218. * @param node defines where to store the animation ranges
  18219. * @param parsedNode defines the serialization object to read data from
  18220. * @param scene defines the hosting scene
  18221. */
  18222. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18223. if (parsedNode.ranges) {
  18224. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18225. var data = parsedNode.ranges[index];
  18226. node.createAnimationRange(data.name, data.from, data.to);
  18227. }
  18228. }
  18229. };
  18230. Node._NodeConstructors = {};
  18231. __decorate([
  18232. BABYLON.serialize()
  18233. ], Node.prototype, "name", void 0);
  18234. __decorate([
  18235. BABYLON.serialize()
  18236. ], Node.prototype, "id", void 0);
  18237. __decorate([
  18238. BABYLON.serialize()
  18239. ], Node.prototype, "uniqueId", void 0);
  18240. __decorate([
  18241. BABYLON.serialize()
  18242. ], Node.prototype, "state", void 0);
  18243. __decorate([
  18244. BABYLON.serialize()
  18245. ], Node.prototype, "metadata", void 0);
  18246. return Node;
  18247. }());
  18248. BABYLON.Node = Node;
  18249. })(BABYLON || (BABYLON = {}));
  18250. //# sourceMappingURL=babylon.node.js.map
  18251. var BABYLON;
  18252. (function (BABYLON) {
  18253. // This matrix is used as a value to reset the bounding box.
  18254. var _identityMatrix = BABYLON.Matrix.Identity();
  18255. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18256. var BoundingSphere = /** @class */ (function () {
  18257. /**
  18258. * Creates a new bounding sphere
  18259. * @param min defines the minimum vector (in local space)
  18260. * @param max defines the maximum vector (in local space)
  18261. */
  18262. function BoundingSphere(min, max) {
  18263. this.center = BABYLON.Vector3.Zero();
  18264. this.centerWorld = BABYLON.Vector3.Zero();
  18265. this.reConstruct(min, max);
  18266. }
  18267. /**
  18268. * Recreates the entire bounding sphere from scratch
  18269. * @param min defines the new minimum vector (in local space)
  18270. * @param max defines the new maximum vector (in local space)
  18271. */
  18272. BoundingSphere.prototype.reConstruct = function (min, max) {
  18273. this.minimum = min.clone();
  18274. this.maximum = max.clone();
  18275. var distance = BABYLON.Vector3.Distance(min, max);
  18276. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18277. this.radius = distance * 0.5;
  18278. this.centerWorld.set(0, 0, 0);
  18279. this._update(_identityMatrix);
  18280. };
  18281. /**
  18282. * Scale the current bounding sphere by applying a scale factor
  18283. * @param factor defines the scale factor to apply
  18284. * @returns the current bounding box
  18285. */
  18286. BoundingSphere.prototype.scale = function (factor) {
  18287. var newRadius = this.radius * factor;
  18288. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18289. var min = this.center.subtract(_tempRadiusVector);
  18290. var max = this.center.add(_tempRadiusVector);
  18291. this.reConstruct(min, max);
  18292. return this;
  18293. };
  18294. // Methods
  18295. /** @hidden */
  18296. BoundingSphere.prototype._update = function (world) {
  18297. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18298. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18299. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18300. };
  18301. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18302. for (var i = 0; i < 6; i++) {
  18303. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18304. return false;
  18305. }
  18306. return true;
  18307. };
  18308. BoundingSphere.prototype.intersectsPoint = function (point) {
  18309. var x = this.centerWorld.x - point.x;
  18310. var y = this.centerWorld.y - point.y;
  18311. var z = this.centerWorld.z - point.z;
  18312. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18313. if (this.radiusWorld < distance)
  18314. return false;
  18315. return true;
  18316. };
  18317. // Statics
  18318. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18319. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18320. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18321. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18322. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18323. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18324. return false;
  18325. return true;
  18326. };
  18327. return BoundingSphere;
  18328. }());
  18329. BABYLON.BoundingSphere = BoundingSphere;
  18330. })(BABYLON || (BABYLON = {}));
  18331. //# sourceMappingURL=babylon.boundingSphere.js.map
  18332. var BABYLON;
  18333. (function (BABYLON) {
  18334. var BoundingBox = /** @class */ (function () {
  18335. /**
  18336. * Creates a new bounding box
  18337. * @param min defines the minimum vector (in local space)
  18338. * @param max defines the maximum vector (in local space)
  18339. */
  18340. function BoundingBox(min, max) {
  18341. this.vectorsWorld = new Array();
  18342. this.reConstruct(min, max);
  18343. }
  18344. // Methods
  18345. /**
  18346. * Recreates the entire bounding box from scratch
  18347. * @param min defines the new minimum vector (in local space)
  18348. * @param max defines the new maximum vector (in local space)
  18349. */
  18350. BoundingBox.prototype.reConstruct = function (min, max) {
  18351. this.minimum = min.clone();
  18352. this.maximum = max.clone();
  18353. // Bounding vectors
  18354. this.vectors = [
  18355. this.minimum.clone(),
  18356. this.maximum.clone(),
  18357. this.minimum.clone(),
  18358. this.minimum.clone(),
  18359. this.minimum.clone(),
  18360. this.maximum.clone(),
  18361. this.maximum.clone(),
  18362. this.maximum.clone()
  18363. ];
  18364. this.vectors[2].x = this.maximum.x;
  18365. this.vectors[3].y = this.maximum.y;
  18366. this.vectors[4].z = this.maximum.z;
  18367. this.vectors[5].z = this.minimum.z;
  18368. this.vectors[6].x = this.minimum.x;
  18369. this.vectors[7].y = this.minimum.y;
  18370. // OBB
  18371. this.center = this.maximum.add(this.minimum).scale(0.5);
  18372. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18373. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18374. // World
  18375. for (var index = 0; index < this.vectors.length; index++) {
  18376. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18377. }
  18378. this.minimumWorld = BABYLON.Vector3.Zero();
  18379. this.maximumWorld = BABYLON.Vector3.Zero();
  18380. this.centerWorld = BABYLON.Vector3.Zero();
  18381. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18382. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18383. };
  18384. /**
  18385. * Scale the current bounding box by applying a scale factor
  18386. * @param factor defines the scale factor to apply
  18387. * @returns the current bounding box
  18388. */
  18389. BoundingBox.prototype.scale = function (factor) {
  18390. var diff = this.maximum.subtract(this.minimum);
  18391. var distance = diff.length() * factor;
  18392. diff.normalize();
  18393. var newRadius = diff.scale(distance / 2);
  18394. var min = this.center.subtract(newRadius);
  18395. var max = this.center.add(newRadius);
  18396. this.reConstruct(min, max);
  18397. return this;
  18398. };
  18399. BoundingBox.prototype.getWorldMatrix = function () {
  18400. return this._worldMatrix;
  18401. };
  18402. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18403. this._worldMatrix.copyFrom(matrix);
  18404. return this;
  18405. };
  18406. /** @hidden */
  18407. BoundingBox.prototype._update = function (world) {
  18408. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18409. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18410. for (var index = 0; index < this.vectors.length; index++) {
  18411. var v = this.vectorsWorld[index];
  18412. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18413. if (v.x < this.minimumWorld.x)
  18414. this.minimumWorld.x = v.x;
  18415. if (v.y < this.minimumWorld.y)
  18416. this.minimumWorld.y = v.y;
  18417. if (v.z < this.minimumWorld.z)
  18418. this.minimumWorld.z = v.z;
  18419. if (v.x > this.maximumWorld.x)
  18420. this.maximumWorld.x = v.x;
  18421. if (v.y > this.maximumWorld.y)
  18422. this.maximumWorld.y = v.y;
  18423. if (v.z > this.maximumWorld.z)
  18424. this.maximumWorld.z = v.z;
  18425. }
  18426. // Extend
  18427. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18428. this.extendSizeWorld.scaleInPlace(0.5);
  18429. // OBB
  18430. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18431. this.centerWorld.scaleInPlace(0.5);
  18432. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18433. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18434. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18435. this._worldMatrix = world;
  18436. };
  18437. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18438. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18439. };
  18440. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18441. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18442. };
  18443. BoundingBox.prototype.intersectsPoint = function (point) {
  18444. var delta = -BABYLON.Epsilon;
  18445. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18446. return false;
  18447. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18448. return false;
  18449. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18450. return false;
  18451. return true;
  18452. };
  18453. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18454. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18455. };
  18456. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18457. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18458. return false;
  18459. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18460. return false;
  18461. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18462. return false;
  18463. return true;
  18464. };
  18465. // Statics
  18466. BoundingBox.Intersects = function (box0, box1) {
  18467. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18468. return false;
  18469. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18470. return false;
  18471. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18472. return false;
  18473. return true;
  18474. };
  18475. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18476. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18477. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18478. return (num <= (sphereRadius * sphereRadius));
  18479. };
  18480. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18481. for (var p = 0; p < 6; p++) {
  18482. for (var i = 0; i < 8; i++) {
  18483. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18484. return false;
  18485. }
  18486. }
  18487. }
  18488. return true;
  18489. };
  18490. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18491. for (var p = 0; p < 6; p++) {
  18492. var inCount = 8;
  18493. for (var i = 0; i < 8; i++) {
  18494. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18495. --inCount;
  18496. }
  18497. else {
  18498. break;
  18499. }
  18500. }
  18501. if (inCount === 0)
  18502. return false;
  18503. }
  18504. return true;
  18505. };
  18506. return BoundingBox;
  18507. }());
  18508. BABYLON.BoundingBox = BoundingBox;
  18509. })(BABYLON || (BABYLON = {}));
  18510. //# sourceMappingURL=babylon.boundingBox.js.map
  18511. var BABYLON;
  18512. (function (BABYLON) {
  18513. var computeBoxExtents = function (axis, box) {
  18514. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18515. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18516. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18517. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18518. var r = r0 + r1 + r2;
  18519. return {
  18520. min: p - r,
  18521. max: p + r
  18522. };
  18523. };
  18524. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18525. var axisOverlap = function (axis, box0, box1) {
  18526. var result0 = computeBoxExtents(axis, box0);
  18527. var result1 = computeBoxExtents(axis, box1);
  18528. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18529. };
  18530. var BoundingInfo = /** @class */ (function () {
  18531. function BoundingInfo(minimum, maximum) {
  18532. this.minimum = minimum;
  18533. this.maximum = maximum;
  18534. this._isLocked = false;
  18535. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18536. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18537. }
  18538. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18539. get: function () {
  18540. return this._isLocked;
  18541. },
  18542. set: function (value) {
  18543. this._isLocked = value;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. // Methods
  18549. BoundingInfo.prototype.update = function (world) {
  18550. if (this._isLocked) {
  18551. return;
  18552. }
  18553. this.boundingBox._update(world);
  18554. this.boundingSphere._update(world);
  18555. };
  18556. /**
  18557. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18558. * @param center New center of the bounding info
  18559. * @param extend New extend of the bounding info
  18560. */
  18561. BoundingInfo.prototype.centerOn = function (center, extend) {
  18562. this.minimum = center.subtract(extend);
  18563. this.maximum = center.add(extend);
  18564. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18565. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18566. return this;
  18567. };
  18568. /**
  18569. * Scale the current bounding info by applying a scale factor
  18570. * @param factor defines the scale factor to apply
  18571. * @returns the current bounding info
  18572. */
  18573. BoundingInfo.prototype.scale = function (factor) {
  18574. this.boundingBox.scale(factor);
  18575. this.boundingSphere.scale(factor);
  18576. return this;
  18577. };
  18578. /**
  18579. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18580. * @param frustumPlanes defines the frustum to test
  18581. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18582. * @returns true if the bounding info is in the frustum planes
  18583. */
  18584. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18585. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18586. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18587. return false;
  18588. }
  18589. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18590. return true;
  18591. }
  18592. return this.boundingBox.isInFrustum(frustumPlanes);
  18593. };
  18594. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18595. /**
  18596. * Gets the world distance between the min and max points of the bounding box
  18597. */
  18598. get: function () {
  18599. var boundingBox = this.boundingBox;
  18600. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18601. return size.length();
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18607. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18608. };
  18609. /** @hidden */
  18610. BoundingInfo.prototype._checkCollision = function (collider) {
  18611. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18612. };
  18613. BoundingInfo.prototype.intersectsPoint = function (point) {
  18614. if (!this.boundingSphere.centerWorld) {
  18615. return false;
  18616. }
  18617. if (!this.boundingSphere.intersectsPoint(point)) {
  18618. return false;
  18619. }
  18620. if (!this.boundingBox.intersectsPoint(point)) {
  18621. return false;
  18622. }
  18623. return true;
  18624. };
  18625. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18626. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18627. return false;
  18628. }
  18629. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18630. return false;
  18631. }
  18632. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18633. return false;
  18634. }
  18635. if (!precise) {
  18636. return true;
  18637. }
  18638. var box0 = this.boundingBox;
  18639. var box1 = boundingInfo.boundingBox;
  18640. if (!axisOverlap(box0.directions[0], box0, box1))
  18641. return false;
  18642. if (!axisOverlap(box0.directions[1], box0, box1))
  18643. return false;
  18644. if (!axisOverlap(box0.directions[2], box0, box1))
  18645. return false;
  18646. if (!axisOverlap(box1.directions[0], box0, box1))
  18647. return false;
  18648. if (!axisOverlap(box1.directions[1], box0, box1))
  18649. return false;
  18650. if (!axisOverlap(box1.directions[2], box0, box1))
  18651. return false;
  18652. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18653. return false;
  18654. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18655. return false;
  18656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18657. return false;
  18658. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18659. return false;
  18660. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18661. return false;
  18662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18663. return false;
  18664. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18665. return false;
  18666. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18667. return false;
  18668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18669. return false;
  18670. return true;
  18671. };
  18672. return BoundingInfo;
  18673. }());
  18674. BABYLON.BoundingInfo = BoundingInfo;
  18675. })(BABYLON || (BABYLON = {}));
  18676. //# sourceMappingURL=babylon.boundingInfo.js.map
  18677. var BABYLON;
  18678. (function (BABYLON) {
  18679. var TransformNode = /** @class */ (function (_super) {
  18680. __extends(TransformNode, _super);
  18681. function TransformNode(name, scene, isPure) {
  18682. if (scene === void 0) { scene = null; }
  18683. if (isPure === void 0) { isPure = true; }
  18684. var _this = _super.call(this, name, scene) || this;
  18685. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18686. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18687. _this._up = new BABYLON.Vector3(0, 1, 0);
  18688. _this._right = new BABYLON.Vector3(1, 0, 0);
  18689. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18690. // Properties
  18691. _this._position = BABYLON.Vector3.Zero();
  18692. _this._rotation = BABYLON.Vector3.Zero();
  18693. _this._scaling = BABYLON.Vector3.One();
  18694. _this._isDirty = false;
  18695. /**
  18696. * Set the billboard mode. Default is 0.
  18697. *
  18698. * | Value | Type | Description |
  18699. * | --- | --- | --- |
  18700. * | 0 | BILLBOARDMODE_NONE | |
  18701. * | 1 | BILLBOARDMODE_X | |
  18702. * | 2 | BILLBOARDMODE_Y | |
  18703. * | 4 | BILLBOARDMODE_Z | |
  18704. * | 7 | BILLBOARDMODE_ALL | |
  18705. *
  18706. */
  18707. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18708. _this.scalingDeterminant = 1;
  18709. _this.infiniteDistance = false;
  18710. /**
  18711. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18712. * By default the system will update normals to compensate
  18713. */
  18714. _this.ignoreNonUniformScaling = false;
  18715. _this._localWorld = BABYLON.Matrix.Zero();
  18716. _this._absolutePosition = BABYLON.Vector3.Zero();
  18717. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18718. _this._postMultiplyPivotMatrix = false;
  18719. _this._isWorldMatrixFrozen = false;
  18720. /**
  18721. * An event triggered after the world matrix is updated
  18722. */
  18723. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18724. _this._nonUniformScaling = false;
  18725. if (isPure) {
  18726. _this.getScene().addTransformNode(_this);
  18727. }
  18728. return _this;
  18729. }
  18730. /**
  18731. * Gets a string identifying the name of the class
  18732. * @returns "TransformNode" string
  18733. */
  18734. TransformNode.prototype.getClassName = function () {
  18735. return "TransformNode";
  18736. };
  18737. Object.defineProperty(TransformNode.prototype, "position", {
  18738. /**
  18739. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18740. */
  18741. get: function () {
  18742. return this._position;
  18743. },
  18744. set: function (newPosition) {
  18745. this._position = newPosition;
  18746. this._isDirty = true;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(TransformNode.prototype, "rotation", {
  18752. /**
  18753. * 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)).
  18754. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18755. */
  18756. get: function () {
  18757. return this._rotation;
  18758. },
  18759. set: function (newRotation) {
  18760. this._rotation = newRotation;
  18761. this._isDirty = true;
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Object.defineProperty(TransformNode.prototype, "scaling", {
  18767. /**
  18768. * 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)).
  18769. */
  18770. get: function () {
  18771. return this._scaling;
  18772. },
  18773. set: function (newScaling) {
  18774. this._scaling = newScaling;
  18775. this._isDirty = true;
  18776. },
  18777. enumerable: true,
  18778. configurable: true
  18779. });
  18780. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18781. /**
  18782. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18783. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18784. */
  18785. get: function () {
  18786. return this._rotationQuaternion;
  18787. },
  18788. set: function (quaternion) {
  18789. this._rotationQuaternion = quaternion;
  18790. //reset the rotation vector.
  18791. if (quaternion && this.rotation.length()) {
  18792. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18793. }
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. Object.defineProperty(TransformNode.prototype, "forward", {
  18799. /**
  18800. * The forward direction of that transform in world space.
  18801. */
  18802. get: function () {
  18803. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18804. },
  18805. enumerable: true,
  18806. configurable: true
  18807. });
  18808. Object.defineProperty(TransformNode.prototype, "up", {
  18809. /**
  18810. * The up direction of that transform in world space.
  18811. */
  18812. get: function () {
  18813. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. Object.defineProperty(TransformNode.prototype, "right", {
  18819. /**
  18820. * The right direction of that transform in world space.
  18821. */
  18822. get: function () {
  18823. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. /**
  18829. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18830. * Returns the TransformNode.
  18831. */
  18832. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18833. this._poseMatrix.copyFrom(matrix);
  18834. return this;
  18835. };
  18836. /**
  18837. * Returns the mesh Pose matrix.
  18838. * Returned object : Matrix
  18839. */
  18840. TransformNode.prototype.getPoseMatrix = function () {
  18841. return this._poseMatrix;
  18842. };
  18843. /** @hidden */
  18844. TransformNode.prototype._isSynchronized = function () {
  18845. if (this._isDirty) {
  18846. return false;
  18847. }
  18848. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18849. return false;
  18850. if (this._cache.pivotMatrixUpdated) {
  18851. return false;
  18852. }
  18853. if (this.infiniteDistance) {
  18854. return false;
  18855. }
  18856. if (!this._cache.position.equals(this._position))
  18857. return false;
  18858. if (this._rotationQuaternion) {
  18859. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18860. return false;
  18861. }
  18862. else if (!this._cache.rotation.equals(this._rotation))
  18863. return false;
  18864. if (!this._cache.scaling.equals(this._scaling))
  18865. return false;
  18866. return true;
  18867. };
  18868. /** @hidden */
  18869. TransformNode.prototype._initCache = function () {
  18870. _super.prototype._initCache.call(this);
  18871. this._cache.localMatrixUpdated = false;
  18872. this._cache.position = BABYLON.Vector3.Zero();
  18873. this._cache.scaling = BABYLON.Vector3.Zero();
  18874. this._cache.rotation = BABYLON.Vector3.Zero();
  18875. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18876. this._cache.billboardMode = -1;
  18877. };
  18878. TransformNode.prototype.markAsDirty = function (property) {
  18879. if (property === "rotation") {
  18880. this.rotationQuaternion = null;
  18881. }
  18882. this._currentRenderId = Number.MAX_VALUE;
  18883. this._isDirty = true;
  18884. return this;
  18885. };
  18886. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18887. /**
  18888. * Returns the current mesh absolute position.
  18889. * Returns a Vector3.
  18890. */
  18891. get: function () {
  18892. return this._absolutePosition;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. /**
  18898. * Sets a new matrix to apply before all other transformation
  18899. * @param matrix defines the transform matrix
  18900. * @returns the current TransformNode
  18901. */
  18902. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18903. return this.setPivotMatrix(matrix, false);
  18904. };
  18905. /**
  18906. * Sets a new pivot matrix to the current node
  18907. * @param matrix defines the new pivot matrix to use
  18908. * @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
  18909. * @returns the current TransformNode
  18910. */
  18911. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18912. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18913. this._pivotMatrix = matrix.clone();
  18914. this._cache.pivotMatrixUpdated = true;
  18915. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18916. if (this._postMultiplyPivotMatrix) {
  18917. if (!this._pivotMatrixInverse) {
  18918. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18919. }
  18920. else {
  18921. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18922. }
  18923. }
  18924. return this;
  18925. };
  18926. /**
  18927. * Returns the mesh pivot matrix.
  18928. * Default : Identity.
  18929. * A Matrix is returned.
  18930. */
  18931. TransformNode.prototype.getPivotMatrix = function () {
  18932. return this._pivotMatrix;
  18933. };
  18934. /**
  18935. * Prevents the World matrix to be computed any longer.
  18936. * Returns the TransformNode.
  18937. */
  18938. TransformNode.prototype.freezeWorldMatrix = function () {
  18939. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18940. this.computeWorldMatrix(true);
  18941. this._isWorldMatrixFrozen = true;
  18942. return this;
  18943. };
  18944. /**
  18945. * Allows back the World matrix computation.
  18946. * Returns the TransformNode.
  18947. */
  18948. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18949. this._isWorldMatrixFrozen = false;
  18950. this.computeWorldMatrix(true);
  18951. return this;
  18952. };
  18953. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18954. /**
  18955. * True if the World matrix has been frozen.
  18956. * Returns a boolean.
  18957. */
  18958. get: function () {
  18959. return this._isWorldMatrixFrozen;
  18960. },
  18961. enumerable: true,
  18962. configurable: true
  18963. });
  18964. /**
  18965. * Retuns the mesh absolute position in the World.
  18966. * Returns a Vector3.
  18967. */
  18968. TransformNode.prototype.getAbsolutePosition = function () {
  18969. this.computeWorldMatrix();
  18970. return this._absolutePosition;
  18971. };
  18972. /**
  18973. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18974. * Returns the TransformNode.
  18975. */
  18976. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18977. if (!absolutePosition) {
  18978. return this;
  18979. }
  18980. var absolutePositionX;
  18981. var absolutePositionY;
  18982. var absolutePositionZ;
  18983. if (absolutePosition.x === undefined) {
  18984. if (arguments.length < 3) {
  18985. return this;
  18986. }
  18987. absolutePositionX = arguments[0];
  18988. absolutePositionY = arguments[1];
  18989. absolutePositionZ = arguments[2];
  18990. }
  18991. else {
  18992. absolutePositionX = absolutePosition.x;
  18993. absolutePositionY = absolutePosition.y;
  18994. absolutePositionZ = absolutePosition.z;
  18995. }
  18996. if (this.parent) {
  18997. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18998. invertParentWorldMatrix.invert();
  18999. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19000. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19001. }
  19002. else {
  19003. this.position.x = absolutePositionX;
  19004. this.position.y = absolutePositionY;
  19005. this.position.z = absolutePositionZ;
  19006. }
  19007. return this;
  19008. };
  19009. /**
  19010. * Sets the mesh position in its local space.
  19011. * Returns the TransformNode.
  19012. */
  19013. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19014. this.computeWorldMatrix();
  19015. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19016. return this;
  19017. };
  19018. /**
  19019. * Returns the mesh position in the local space from the current World matrix values.
  19020. * Returns a new Vector3.
  19021. */
  19022. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19023. this.computeWorldMatrix();
  19024. var invLocalWorldMatrix = this._localWorld.clone();
  19025. invLocalWorldMatrix.invert();
  19026. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19027. };
  19028. /**
  19029. * Translates the mesh along the passed Vector3 in its local space.
  19030. * Returns the TransformNode.
  19031. */
  19032. TransformNode.prototype.locallyTranslate = function (vector3) {
  19033. this.computeWorldMatrix(true);
  19034. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19035. return this;
  19036. };
  19037. /**
  19038. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19039. * @param targetPoint the position (must be in same space as current mesh) to look at
  19040. * @param yawCor optional yaw (y-axis) correction in radians
  19041. * @param pitchCor optional pitch (x-axis) correction in radians
  19042. * @param rollCor optional roll (z-axis) correction in radians
  19043. * @param space the choosen space of the target
  19044. * @returns the TransformNode.
  19045. */
  19046. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19047. if (yawCor === void 0) { yawCor = 0; }
  19048. if (pitchCor === void 0) { pitchCor = 0; }
  19049. if (rollCor === void 0) { rollCor = 0; }
  19050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19051. var dv = TransformNode._lookAtVectorCache;
  19052. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19053. targetPoint.subtractToRef(pos, dv);
  19054. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19055. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19056. var pitch = Math.atan2(dv.y, len);
  19057. if (this.rotationQuaternion) {
  19058. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19059. }
  19060. else {
  19061. this.rotation.x = pitch + pitchCor;
  19062. this.rotation.y = yaw + yawCor;
  19063. this.rotation.z = rollCor;
  19064. }
  19065. return this;
  19066. };
  19067. /**
  19068. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19069. * This Vector3 is expressed in the World space.
  19070. */
  19071. TransformNode.prototype.getDirection = function (localAxis) {
  19072. var result = BABYLON.Vector3.Zero();
  19073. this.getDirectionToRef(localAxis, result);
  19074. return result;
  19075. };
  19076. /**
  19077. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19078. * localAxis is expressed in the mesh local space.
  19079. * result is computed in the Wordl space from the mesh World matrix.
  19080. * Returns the TransformNode.
  19081. */
  19082. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19083. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19084. return this;
  19085. };
  19086. /**
  19087. * Sets a new pivot point to the current node
  19088. * @param point defines the new pivot point to use
  19089. * @param space defines if the point is in world or local space (local by default)
  19090. * @returns the current TransformNode
  19091. */
  19092. TransformNode.prototype.setPivotPoint = function (point, space) {
  19093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19094. if (this.getScene().getRenderId() == 0) {
  19095. this.computeWorldMatrix(true);
  19096. }
  19097. var wm = this.getWorldMatrix();
  19098. if (space == BABYLON.Space.WORLD) {
  19099. var tmat = BABYLON.Tmp.Matrix[0];
  19100. wm.invertToRef(tmat);
  19101. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19102. }
  19103. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19104. };
  19105. /**
  19106. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19107. */
  19108. TransformNode.prototype.getPivotPoint = function () {
  19109. var point = BABYLON.Vector3.Zero();
  19110. this.getPivotPointToRef(point);
  19111. return point;
  19112. };
  19113. /**
  19114. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19115. * Returns the TransformNode.
  19116. */
  19117. TransformNode.prototype.getPivotPointToRef = function (result) {
  19118. result.x = -this._pivotMatrix.m[12];
  19119. result.y = -this._pivotMatrix.m[13];
  19120. result.z = -this._pivotMatrix.m[14];
  19121. return this;
  19122. };
  19123. /**
  19124. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19125. */
  19126. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19127. var point = BABYLON.Vector3.Zero();
  19128. this.getAbsolutePivotPointToRef(point);
  19129. return point;
  19130. };
  19131. /**
  19132. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19133. * Returns the TransformNode.
  19134. */
  19135. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19136. result.x = this._pivotMatrix.m[12];
  19137. result.y = this._pivotMatrix.m[13];
  19138. result.z = this._pivotMatrix.m[14];
  19139. this.getPivotPointToRef(result);
  19140. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19141. return this;
  19142. };
  19143. /**
  19144. * Defines the passed node as the parent of the current node.
  19145. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19146. * Returns the TransformNode.
  19147. */
  19148. TransformNode.prototype.setParent = function (node) {
  19149. if (!node && !this.parent) {
  19150. return this;
  19151. }
  19152. if (!node) {
  19153. var rotation = BABYLON.Tmp.Quaternion[0];
  19154. var position = BABYLON.Tmp.Vector3[0];
  19155. var scale = BABYLON.Tmp.Vector3[1];
  19156. if (this.parent && this.parent.computeWorldMatrix) {
  19157. this.parent.computeWorldMatrix(true);
  19158. }
  19159. this.computeWorldMatrix(true);
  19160. this.getWorldMatrix().decompose(scale, rotation, position);
  19161. if (this.rotationQuaternion) {
  19162. this.rotationQuaternion.copyFrom(rotation);
  19163. }
  19164. else {
  19165. rotation.toEulerAnglesToRef(this.rotation);
  19166. }
  19167. this.scaling.x = scale.x;
  19168. this.scaling.y = scale.y;
  19169. this.scaling.z = scale.z;
  19170. this.position.x = position.x;
  19171. this.position.y = position.y;
  19172. this.position.z = position.z;
  19173. }
  19174. else {
  19175. var rotation = BABYLON.Tmp.Quaternion[0];
  19176. var position = BABYLON.Tmp.Vector3[0];
  19177. var scale = BABYLON.Tmp.Vector3[1];
  19178. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19179. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19180. this.computeWorldMatrix(true);
  19181. node.computeWorldMatrix(true);
  19182. node.getWorldMatrix().invertToRef(invParentMatrix);
  19183. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19184. diffMatrix.decompose(scale, rotation, position);
  19185. if (this.rotationQuaternion) {
  19186. this.rotationQuaternion.copyFrom(rotation);
  19187. }
  19188. else {
  19189. rotation.toEulerAnglesToRef(this.rotation);
  19190. }
  19191. this.position.x = position.x;
  19192. this.position.y = position.y;
  19193. this.position.z = position.z;
  19194. this.scaling.x = scale.x;
  19195. this.scaling.y = scale.y;
  19196. this.scaling.z = scale.z;
  19197. }
  19198. this.parent = node;
  19199. return this;
  19200. };
  19201. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19202. get: function () {
  19203. return this._nonUniformScaling;
  19204. },
  19205. enumerable: true,
  19206. configurable: true
  19207. });
  19208. /** @hidden */
  19209. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19210. if (this._nonUniformScaling === value) {
  19211. return false;
  19212. }
  19213. this._nonUniformScaling = value;
  19214. return true;
  19215. };
  19216. /**
  19217. * Attach the current TransformNode to another TransformNode associated with a bone
  19218. * @param bone Bone affecting the TransformNode
  19219. * @param affectedTransformNode TransformNode associated with the bone
  19220. */
  19221. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19222. this._transformToBoneReferal = affectedTransformNode;
  19223. this.parent = bone;
  19224. if (bone.getWorldMatrix().determinant() < 0) {
  19225. this.scalingDeterminant *= -1;
  19226. }
  19227. return this;
  19228. };
  19229. TransformNode.prototype.detachFromBone = function () {
  19230. if (!this.parent) {
  19231. return this;
  19232. }
  19233. if (this.parent.getWorldMatrix().determinant() < 0) {
  19234. this.scalingDeterminant *= -1;
  19235. }
  19236. this._transformToBoneReferal = null;
  19237. this.parent = null;
  19238. return this;
  19239. };
  19240. /**
  19241. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19242. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19243. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19244. * The passed axis is also normalized.
  19245. * Returns the TransformNode.
  19246. */
  19247. TransformNode.prototype.rotate = function (axis, amount, space) {
  19248. axis.normalize();
  19249. if (!this.rotationQuaternion) {
  19250. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19251. this.rotation = BABYLON.Vector3.Zero();
  19252. }
  19253. var rotationQuaternion;
  19254. if (!space || space === BABYLON.Space.LOCAL) {
  19255. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19256. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19257. }
  19258. else {
  19259. if (this.parent) {
  19260. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19261. invertParentWorldMatrix.invert();
  19262. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19263. }
  19264. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19265. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19266. }
  19267. return this;
  19268. };
  19269. /**
  19270. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19271. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19272. * The passed axis is also normalized.
  19273. * Returns the TransformNode.
  19274. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19275. */
  19276. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19277. axis.normalize();
  19278. if (!this.rotationQuaternion) {
  19279. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19280. this.rotation.copyFromFloats(0, 0, 0);
  19281. }
  19282. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19283. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19284. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19285. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19286. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19287. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19288. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19289. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19290. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19291. return this;
  19292. };
  19293. /**
  19294. * Translates the mesh along the axis vector for the passed distance in the given space.
  19295. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19296. * Returns the TransformNode.
  19297. */
  19298. TransformNode.prototype.translate = function (axis, distance, space) {
  19299. var displacementVector = axis.scale(distance);
  19300. if (!space || space === BABYLON.Space.LOCAL) {
  19301. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19302. this.setPositionWithLocalVector(tempV3);
  19303. }
  19304. else {
  19305. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19306. }
  19307. return this;
  19308. };
  19309. /**
  19310. * Adds a rotation step to the mesh current rotation.
  19311. * x, y, z are Euler angles expressed in radians.
  19312. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19313. * This means this rotation is made in the mesh local space only.
  19314. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19315. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19316. * ```javascript
  19317. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19318. * ```
  19319. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19320. * 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.
  19321. * Returns the TransformNode.
  19322. */
  19323. TransformNode.prototype.addRotation = function (x, y, z) {
  19324. var rotationQuaternion;
  19325. if (this.rotationQuaternion) {
  19326. rotationQuaternion = this.rotationQuaternion;
  19327. }
  19328. else {
  19329. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19330. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19331. }
  19332. var accumulation = BABYLON.Tmp.Quaternion[0];
  19333. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19334. rotationQuaternion.multiplyInPlace(accumulation);
  19335. if (!this.rotationQuaternion) {
  19336. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19337. }
  19338. return this;
  19339. };
  19340. /**
  19341. * Computes the world matrix of the node
  19342. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19343. * @returns the world matrix
  19344. */
  19345. TransformNode.prototype.computeWorldMatrix = function (force) {
  19346. if (this._isWorldMatrixFrozen) {
  19347. return this._worldMatrix;
  19348. }
  19349. if (!force && this.isSynchronized()) {
  19350. this._currentRenderId = this.getScene().getRenderId();
  19351. return this._worldMatrix;
  19352. }
  19353. this._updateCache();
  19354. this._cache.position.copyFrom(this.position);
  19355. this._cache.scaling.copyFrom(this.scaling);
  19356. this._cache.pivotMatrixUpdated = false;
  19357. this._cache.billboardMode = this.billboardMode;
  19358. this._currentRenderId = this.getScene().getRenderId();
  19359. this._childRenderId = this.getScene().getRenderId();
  19360. this._isDirty = false;
  19361. // Scaling
  19362. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19363. // Rotation
  19364. //rotate, if quaternion is set and rotation was used
  19365. if (this.rotationQuaternion) {
  19366. var len = this.rotation.length();
  19367. if (len) {
  19368. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19369. this.rotation.copyFromFloats(0, 0, 0);
  19370. }
  19371. }
  19372. if (this.rotationQuaternion) {
  19373. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19374. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19375. }
  19376. else {
  19377. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19378. this._cache.rotation.copyFrom(this.rotation);
  19379. }
  19380. // Translation
  19381. var camera = this.getScene().activeCamera;
  19382. if (this.infiniteDistance && !this.parent && camera) {
  19383. var cameraWorldMatrix = camera.getWorldMatrix();
  19384. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19385. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19386. }
  19387. else {
  19388. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19389. }
  19390. // Composing transformations
  19391. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19392. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19393. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19394. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19395. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19396. // Need to decompose each rotation here
  19397. var currentPosition = BABYLON.Tmp.Vector3[3];
  19398. if (this.parent && this.parent.getWorldMatrix) {
  19399. if (this._transformToBoneReferal) {
  19400. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19401. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19402. }
  19403. else {
  19404. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19405. }
  19406. }
  19407. else {
  19408. currentPosition.copyFrom(this.position);
  19409. }
  19410. currentPosition.subtractInPlace(camera.globalPosition);
  19411. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19412. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19413. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19414. }
  19415. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19416. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19417. }
  19418. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19419. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19420. }
  19421. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19422. }
  19423. else {
  19424. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19425. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19426. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19427. }
  19428. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19429. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19430. }
  19431. // Post multiply inverse of pivotMatrix
  19432. if (this._postMultiplyPivotMatrix) {
  19433. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19434. }
  19435. // Local world
  19436. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19437. // Parent
  19438. if (this.parent && this.parent.getWorldMatrix) {
  19439. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19440. if (this._transformToBoneReferal) {
  19441. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19442. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19443. }
  19444. else {
  19445. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19446. }
  19447. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19448. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19449. this._worldMatrix.copyFrom(this._localWorld);
  19450. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19451. }
  19452. else {
  19453. if (this._transformToBoneReferal) {
  19454. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19455. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19456. }
  19457. else {
  19458. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19459. }
  19460. }
  19461. this._markSyncedWithParent();
  19462. }
  19463. else {
  19464. this._worldMatrix.copyFrom(this._localWorld);
  19465. }
  19466. // Normal matrix
  19467. if (!this.ignoreNonUniformScaling) {
  19468. if (this.scaling.isNonUniform) {
  19469. this._updateNonUniformScalingState(true);
  19470. }
  19471. else if (this.parent && this.parent._nonUniformScaling) {
  19472. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19473. }
  19474. else {
  19475. this._updateNonUniformScalingState(false);
  19476. }
  19477. }
  19478. else {
  19479. this._updateNonUniformScalingState(false);
  19480. }
  19481. this._afterComputeWorldMatrix();
  19482. // Absolute position
  19483. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19484. // Callbacks
  19485. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19486. if (!this._poseMatrix) {
  19487. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19488. }
  19489. // Cache the determinant
  19490. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19491. return this._worldMatrix;
  19492. };
  19493. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19494. };
  19495. /**
  19496. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19497. * @param func: callback function to add
  19498. *
  19499. * Returns the TransformNode.
  19500. */
  19501. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19502. this.onAfterWorldMatrixUpdateObservable.add(func);
  19503. return this;
  19504. };
  19505. /**
  19506. * Removes a registered callback function.
  19507. * Returns the TransformNode.
  19508. */
  19509. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19510. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19511. return this;
  19512. };
  19513. /**
  19514. * Clone the current transform node
  19515. * Returns the new transform node
  19516. * @param name Name of the new clone
  19517. * @param newParent New parent for the clone
  19518. * @param doNotCloneChildren Do not clone children hierarchy
  19519. */
  19520. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19521. var _this = this;
  19522. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19523. result.name = name;
  19524. result.id = name;
  19525. if (newParent) {
  19526. result.parent = newParent;
  19527. }
  19528. if (!doNotCloneChildren) {
  19529. // Children
  19530. var directDescendants = this.getDescendants(true);
  19531. for (var index = 0; index < directDescendants.length; index++) {
  19532. var child = directDescendants[index];
  19533. if (child.clone) {
  19534. child.clone(name + "." + child.name, result);
  19535. }
  19536. }
  19537. }
  19538. return result;
  19539. };
  19540. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19541. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19542. serializationObject.type = this.getClassName();
  19543. // Parent
  19544. if (this.parent) {
  19545. serializationObject.parentId = this.parent.id;
  19546. }
  19547. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19548. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19549. }
  19550. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19551. serializationObject.isEnabled = this.isEnabled();
  19552. // Parent
  19553. if (this.parent) {
  19554. serializationObject.parentId = this.parent.id;
  19555. }
  19556. return serializationObject;
  19557. };
  19558. // Statics
  19559. /**
  19560. * Returns a new TransformNode object parsed from the source provided.
  19561. * The parameter `parsedMesh` is the source.
  19562. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19563. */
  19564. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19565. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19566. if (BABYLON.Tags) {
  19567. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19568. }
  19569. if (parsedTransformNode.localMatrix) {
  19570. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19571. }
  19572. else if (parsedTransformNode.pivotMatrix) {
  19573. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19574. }
  19575. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19576. // Parent
  19577. if (parsedTransformNode.parentId) {
  19578. transformNode._waitingParentId = parsedTransformNode.parentId;
  19579. }
  19580. return transformNode;
  19581. };
  19582. /**
  19583. * Releases resources associated with this transform node.
  19584. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19585. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19586. */
  19587. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19588. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19589. // Animations
  19590. this.getScene().stopAnimation(this);
  19591. // Remove from scene
  19592. this.getScene().removeTransformNode(this);
  19593. this.onAfterWorldMatrixUpdateObservable.clear();
  19594. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19595. };
  19596. // Statics
  19597. TransformNode.BILLBOARDMODE_NONE = 0;
  19598. TransformNode.BILLBOARDMODE_X = 1;
  19599. TransformNode.BILLBOARDMODE_Y = 2;
  19600. TransformNode.BILLBOARDMODE_Z = 4;
  19601. TransformNode.BILLBOARDMODE_ALL = 7;
  19602. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19603. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19604. __decorate([
  19605. BABYLON.serializeAsVector3("position")
  19606. ], TransformNode.prototype, "_position", void 0);
  19607. __decorate([
  19608. BABYLON.serializeAsVector3("rotation")
  19609. ], TransformNode.prototype, "_rotation", void 0);
  19610. __decorate([
  19611. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19612. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19613. __decorate([
  19614. BABYLON.serializeAsVector3("scaling")
  19615. ], TransformNode.prototype, "_scaling", void 0);
  19616. __decorate([
  19617. BABYLON.serialize()
  19618. ], TransformNode.prototype, "billboardMode", void 0);
  19619. __decorate([
  19620. BABYLON.serialize()
  19621. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19622. __decorate([
  19623. BABYLON.serialize()
  19624. ], TransformNode.prototype, "infiniteDistance", void 0);
  19625. __decorate([
  19626. BABYLON.serialize()
  19627. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19628. return TransformNode;
  19629. }(BABYLON.Node));
  19630. BABYLON.TransformNode = TransformNode;
  19631. })(BABYLON || (BABYLON = {}));
  19632. //# sourceMappingURL=babylon.transformNode.js.map
  19633. var BABYLON;
  19634. (function (BABYLON) {
  19635. /**
  19636. * Class used to store all common mesh properties
  19637. */
  19638. var AbstractMesh = /** @class */ (function (_super) {
  19639. __extends(AbstractMesh, _super);
  19640. // Constructor
  19641. /**
  19642. * Creates a new AbstractMesh
  19643. * @param name defines the name of the mesh
  19644. * @param scene defines the hosting scene
  19645. */
  19646. function AbstractMesh(name, scene) {
  19647. if (scene === void 0) { scene = null; }
  19648. var _this = _super.call(this, name, scene, false) || this;
  19649. _this._facetNb = 0; // facet number
  19650. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19651. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19652. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19653. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19654. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19655. _this._subDiv = {
  19656. max: 1,
  19657. X: 1,
  19658. Y: 1,
  19659. Z: 1
  19660. };
  19661. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19662. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19663. /** Gets ot sets the culling strategy to use to find visible meshes */
  19664. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19665. // Events
  19666. /**
  19667. * An event triggered when this mesh collides with another one
  19668. */
  19669. _this.onCollideObservable = new BABYLON.Observable();
  19670. /**
  19671. * An event triggered when the collision's position changes
  19672. */
  19673. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19674. /**
  19675. * An event triggered when material is changed
  19676. */
  19677. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19678. // Properties
  19679. /**
  19680. * Gets or sets the orientation for POV movement & rotation
  19681. */
  19682. _this.definedFacingForward = true;
  19683. /**
  19684. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19685. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19686. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19687. * @see http://doc.babylonjs.com/features/occlusionquery
  19688. */
  19689. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19690. /**
  19691. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19692. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19693. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19694. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19695. * @see http://doc.babylonjs.com/features/occlusionquery
  19696. */
  19697. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19698. /**
  19699. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19700. * The default value is -1 which means don't break the query and wait till the result
  19701. * @see http://doc.babylonjs.com/features/occlusionquery
  19702. */
  19703. _this.occlusionRetryCount = -1;
  19704. /** @hidden */
  19705. _this._occlusionInternalRetryCounter = 0;
  19706. /** @hidden */
  19707. _this._isOccluded = false;
  19708. /** @hidden */
  19709. _this._isOcclusionQueryInProgress = false;
  19710. _this._visibility = 1.0;
  19711. /** Gets or sets the alpha index used to sort transparent meshes
  19712. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19713. */
  19714. _this.alphaIndex = Number.MAX_VALUE;
  19715. /**
  19716. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19717. */
  19718. _this.isVisible = true;
  19719. /**
  19720. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19721. */
  19722. _this.isPickable = true;
  19723. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19724. _this.showSubMeshesBoundingBox = false;
  19725. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19726. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19727. */
  19728. _this.isBlocker = false;
  19729. /**
  19730. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19731. */
  19732. _this.enablePointerMoveEvents = false;
  19733. /**
  19734. * Specifies the rendering group id for this mesh (0 by default)
  19735. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19736. */
  19737. _this.renderingGroupId = 0;
  19738. _this._receiveShadows = false;
  19739. /** Defines color to use when rendering outline */
  19740. _this.outlineColor = BABYLON.Color3.Red();
  19741. /** Define width to use when rendering outline */
  19742. _this.outlineWidth = 0.02;
  19743. /** Defines color to use when rendering overlay */
  19744. _this.overlayColor = BABYLON.Color3.Red();
  19745. /** Defines alpha to use when rendering overlay */
  19746. _this.overlayAlpha = 0.5;
  19747. _this._hasVertexAlpha = false;
  19748. _this._useVertexColors = true;
  19749. _this._computeBonesUsingShaders = true;
  19750. _this._numBoneInfluencers = 4;
  19751. _this._applyFog = true;
  19752. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19753. _this.useOctreeForRenderingSelection = true;
  19754. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19755. _this.useOctreeForPicking = true;
  19756. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19757. _this.useOctreeForCollisions = true;
  19758. _this._layerMask = 0x0FFFFFFF;
  19759. /**
  19760. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19761. */
  19762. _this.alwaysSelectAsActiveMesh = false;
  19763. /**
  19764. * Gets or sets the current action manager
  19765. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19766. */
  19767. _this.actionManager = null;
  19768. // Collisions
  19769. _this._checkCollisions = false;
  19770. _this._collisionMask = -1;
  19771. _this._collisionGroup = -1;
  19772. /**
  19773. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19774. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19775. */
  19776. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19777. /**
  19778. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19779. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19780. */
  19781. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19782. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19783. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19784. // Edges
  19785. /**
  19786. * Defines edge width used when edgesRenderer is enabled
  19787. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19788. */
  19789. _this.edgesWidth = 1;
  19790. /**
  19791. * Defines edge color used when edgesRenderer is enabled
  19792. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19793. */
  19794. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19795. // Cache
  19796. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19797. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19798. /** @hidden */
  19799. _this._renderId = 0;
  19800. /** @hidden */
  19801. _this._intersectionsInProgress = new Array();
  19802. /** @hidden */
  19803. _this._unIndexed = false;
  19804. /** @hidden */
  19805. _this._lightSources = new Array();
  19806. /**
  19807. * An event triggered when the mesh is rebuilt.
  19808. */
  19809. _this.onRebuildObservable = new BABYLON.Observable();
  19810. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19811. if (collidedMesh === void 0) { collidedMesh = null; }
  19812. //TODO move this to the collision coordinator!
  19813. if (_this.getScene().workerCollisions)
  19814. newPosition.multiplyInPlace(_this._collider._radius);
  19815. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19816. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19817. _this.position.addInPlace(_this._diffPositionForCollisions);
  19818. }
  19819. if (collidedMesh) {
  19820. _this.onCollideObservable.notifyObservers(collidedMesh);
  19821. }
  19822. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19823. };
  19824. _this.getScene().addMesh(_this);
  19825. _this._resyncLightSources();
  19826. return _this;
  19827. }
  19828. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19829. /**
  19830. * No billboard
  19831. */
  19832. get: function () {
  19833. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19839. /** Billboard on X axis */
  19840. get: function () {
  19841. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19847. /** Billboard on Y axis */
  19848. get: function () {
  19849. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19855. /** Billboard on Z axis */
  19856. get: function () {
  19857. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19858. },
  19859. enumerable: true,
  19860. configurable: true
  19861. });
  19862. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19863. /** Billboard on all axes */
  19864. get: function () {
  19865. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19871. /**
  19872. * Gets the number of facets in the mesh
  19873. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19874. */
  19875. get: function () {
  19876. return this._facetNb;
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19882. /**
  19883. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19884. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19885. */
  19886. get: function () {
  19887. return this._partitioningSubdivisions;
  19888. },
  19889. set: function (nb) {
  19890. this._partitioningSubdivisions = nb;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19896. /**
  19897. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19898. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19899. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19900. */
  19901. get: function () {
  19902. return this._partitioningBBoxRatio;
  19903. },
  19904. set: function (ratio) {
  19905. this._partitioningBBoxRatio = ratio;
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19911. /**
  19912. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19913. * Works only for updatable meshes.
  19914. * Doesn't work with multi-materials
  19915. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19916. */
  19917. get: function () {
  19918. return this._facetDepthSort;
  19919. },
  19920. set: function (sort) {
  19921. this._facetDepthSort = sort;
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19927. /**
  19928. * The location (Vector3) where the facet depth sort must be computed from.
  19929. * By default, the active camera position.
  19930. * Used only when facet depth sort is enabled
  19931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19932. */
  19933. get: function () {
  19934. return this._facetDepthSortFrom;
  19935. },
  19936. set: function (location) {
  19937. this._facetDepthSortFrom = location;
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19943. /**
  19944. * gets a boolean indicating if facetData is enabled
  19945. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19946. */
  19947. get: function () {
  19948. return this._facetDataEnabled;
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. /** @hidden */
  19954. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19955. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19956. return false;
  19957. }
  19958. this._markSubMeshesAsMiscDirty();
  19959. return true;
  19960. };
  19961. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19962. /** Set a function to call when this mesh collides with another one */
  19963. set: function (callback) {
  19964. if (this._onCollideObserver) {
  19965. this.onCollideObservable.remove(this._onCollideObserver);
  19966. }
  19967. this._onCollideObserver = this.onCollideObservable.add(callback);
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19973. /** Set a function to call when the collision's position changes */
  19974. set: function (callback) {
  19975. if (this._onCollisionPositionChangeObserver) {
  19976. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19977. }
  19978. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19984. /**
  19985. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19986. * @see http://doc.babylonjs.com/features/occlusionquery
  19987. */
  19988. get: function () {
  19989. return this._isOccluded;
  19990. },
  19991. set: function (value) {
  19992. this._isOccluded = value;
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19998. /**
  19999. * Flag to check the progress status of the query
  20000. * @see http://doc.babylonjs.com/features/occlusionquery
  20001. */
  20002. get: function () {
  20003. return this._isOcclusionQueryInProgress;
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20009. /**
  20010. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20011. */
  20012. get: function () {
  20013. return this._visibility;
  20014. },
  20015. /**
  20016. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20017. */
  20018. set: function (value) {
  20019. if (this._visibility === value) {
  20020. return;
  20021. }
  20022. this._visibility = value;
  20023. this._markSubMeshesAsMiscDirty();
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Object.defineProperty(AbstractMesh.prototype, "material", {
  20029. /** Gets or sets current material */
  20030. get: function () {
  20031. return this._material;
  20032. },
  20033. set: function (value) {
  20034. if (this._material === value) {
  20035. return;
  20036. }
  20037. this._material = value;
  20038. if (this.onMaterialChangedObservable.hasObservers) {
  20039. this.onMaterialChangedObservable.notifyObservers(this);
  20040. }
  20041. if (!this.subMeshes) {
  20042. return;
  20043. }
  20044. this._unBindEffect();
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20050. /**
  20051. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20052. * @see http://doc.babylonjs.com/babylon101/shadows
  20053. */
  20054. get: function () {
  20055. return this._receiveShadows;
  20056. },
  20057. set: function (value) {
  20058. if (this._receiveShadows === value) {
  20059. return;
  20060. }
  20061. this._receiveShadows = value;
  20062. this._markSubMeshesAsLightDirty();
  20063. },
  20064. enumerable: true,
  20065. configurable: true
  20066. });
  20067. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20068. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20069. get: function () {
  20070. return this._hasVertexAlpha;
  20071. },
  20072. set: function (value) {
  20073. if (this._hasVertexAlpha === value) {
  20074. return;
  20075. }
  20076. this._hasVertexAlpha = value;
  20077. this._markSubMeshesAsAttributesDirty();
  20078. this._markSubMeshesAsMiscDirty();
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20084. /** 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) */
  20085. get: function () {
  20086. return this._useVertexColors;
  20087. },
  20088. set: function (value) {
  20089. if (this._useVertexColors === value) {
  20090. return;
  20091. }
  20092. this._useVertexColors = value;
  20093. this._markSubMeshesAsAttributesDirty();
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20099. /**
  20100. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20101. */
  20102. get: function () {
  20103. return this._computeBonesUsingShaders;
  20104. },
  20105. set: function (value) {
  20106. if (this._computeBonesUsingShaders === value) {
  20107. return;
  20108. }
  20109. this._computeBonesUsingShaders = value;
  20110. this._markSubMeshesAsAttributesDirty();
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20116. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20117. get: function () {
  20118. return this._numBoneInfluencers;
  20119. },
  20120. set: function (value) {
  20121. if (this._numBoneInfluencers === value) {
  20122. return;
  20123. }
  20124. this._numBoneInfluencers = value;
  20125. this._markSubMeshesAsAttributesDirty();
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20131. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20132. get: function () {
  20133. return this._applyFog;
  20134. },
  20135. set: function (value) {
  20136. if (this._applyFog === value) {
  20137. return;
  20138. }
  20139. this._applyFog = value;
  20140. this._markSubMeshesAsMiscDirty();
  20141. },
  20142. enumerable: true,
  20143. configurable: true
  20144. });
  20145. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20146. /**
  20147. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20148. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20149. */
  20150. get: function () {
  20151. return this._layerMask;
  20152. },
  20153. set: function (value) {
  20154. if (value === this._layerMask) {
  20155. return;
  20156. }
  20157. this._layerMask = value;
  20158. this._resyncLightSources();
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20164. /**
  20165. * Gets or sets a collision mask used to mask collisions (default is -1).
  20166. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20167. */
  20168. get: function () {
  20169. return this._collisionMask;
  20170. },
  20171. set: function (mask) {
  20172. this._collisionMask = !isNaN(mask) ? mask : -1;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20178. /**
  20179. * Gets or sets the current collision group mask (-1 by default).
  20180. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20181. */
  20182. get: function () {
  20183. return this._collisionGroup;
  20184. },
  20185. set: function (mask) {
  20186. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20192. /** @hidden */
  20193. get: function () {
  20194. return null;
  20195. },
  20196. enumerable: true,
  20197. configurable: true
  20198. });
  20199. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20200. get: function () {
  20201. return this._skeleton;
  20202. },
  20203. /**
  20204. * Gets or sets a skeleton to apply skining transformations
  20205. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20206. */
  20207. set: function (value) {
  20208. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20209. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20210. }
  20211. if (value && value.needInitialSkinMatrix) {
  20212. value._registerMeshWithPoseMatrix(this);
  20213. }
  20214. this._skeleton = value;
  20215. if (!this._skeleton) {
  20216. this._bonesTransformMatrices = null;
  20217. }
  20218. this._markSubMeshesAsAttributesDirty();
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. /**
  20224. * Returns the string "AbstractMesh"
  20225. * @returns "AbstractMesh"
  20226. */
  20227. AbstractMesh.prototype.getClassName = function () {
  20228. return "AbstractMesh";
  20229. };
  20230. /**
  20231. * Gets a string representation of the current mesh
  20232. * @param fullDetails defines a boolean indicating if full details must be included
  20233. * @returns a string representation of the current mesh
  20234. */
  20235. AbstractMesh.prototype.toString = function (fullDetails) {
  20236. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20237. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20238. if (this._skeleton) {
  20239. ret += ", skeleton: " + this._skeleton.name;
  20240. }
  20241. if (fullDetails) {
  20242. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20243. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20244. }
  20245. return ret;
  20246. };
  20247. /** @hidden */
  20248. AbstractMesh.prototype._rebuild = function () {
  20249. this.onRebuildObservable.notifyObservers(this);
  20250. if (this._occlusionQuery) {
  20251. this._occlusionQuery = null;
  20252. }
  20253. if (!this.subMeshes) {
  20254. return;
  20255. }
  20256. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20257. var subMesh = _a[_i];
  20258. subMesh._rebuild();
  20259. }
  20260. };
  20261. /** @hidden */
  20262. AbstractMesh.prototype._resyncLightSources = function () {
  20263. this._lightSources.length = 0;
  20264. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20265. var light = _a[_i];
  20266. if (!light.isEnabled()) {
  20267. continue;
  20268. }
  20269. if (light.canAffectMesh(this)) {
  20270. this._lightSources.push(light);
  20271. }
  20272. }
  20273. this._markSubMeshesAsLightDirty();
  20274. };
  20275. /** @hidden */
  20276. AbstractMesh.prototype._resyncLighSource = function (light) {
  20277. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20278. var index = this._lightSources.indexOf(light);
  20279. if (index === -1) {
  20280. if (!isIn) {
  20281. return;
  20282. }
  20283. this._lightSources.push(light);
  20284. }
  20285. else {
  20286. if (isIn) {
  20287. return;
  20288. }
  20289. this._lightSources.splice(index, 1);
  20290. }
  20291. this._markSubMeshesAsLightDirty();
  20292. };
  20293. /** @hidden */
  20294. AbstractMesh.prototype._unBindEffect = function () {
  20295. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20296. var subMesh = _a[_i];
  20297. subMesh.setEffect(null);
  20298. }
  20299. };
  20300. /** @hidden */
  20301. AbstractMesh.prototype._removeLightSource = function (light) {
  20302. var index = this._lightSources.indexOf(light);
  20303. if (index === -1) {
  20304. return;
  20305. }
  20306. this._lightSources.splice(index, 1);
  20307. this._markSubMeshesAsLightDirty();
  20308. };
  20309. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20310. if (!this.subMeshes) {
  20311. return;
  20312. }
  20313. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20314. var subMesh = _a[_i];
  20315. if (subMesh._materialDefines) {
  20316. func(subMesh._materialDefines);
  20317. }
  20318. }
  20319. };
  20320. /** @hidden */
  20321. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20322. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20323. };
  20324. /** @hidden */
  20325. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20326. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20327. };
  20328. /** @hidden */
  20329. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20330. if (!this.subMeshes) {
  20331. return;
  20332. }
  20333. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20334. var subMesh = _a[_i];
  20335. var material = subMesh.getMaterial();
  20336. if (material) {
  20337. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20338. }
  20339. }
  20340. };
  20341. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20342. /**
  20343. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20344. */
  20345. get: function () {
  20346. return this._scaling;
  20347. },
  20348. set: function (newScaling) {
  20349. this._scaling = newScaling;
  20350. if (this.physicsImpostor) {
  20351. this.physicsImpostor.forceUpdate();
  20352. }
  20353. },
  20354. enumerable: true,
  20355. configurable: true
  20356. });
  20357. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20358. // Methods
  20359. /**
  20360. * Returns true if the mesh is blocked. Implemented by child classes
  20361. */
  20362. get: function () {
  20363. return false;
  20364. },
  20365. enumerable: true,
  20366. configurable: true
  20367. });
  20368. /**
  20369. * Returns the mesh itself by default. Implemented by child classes
  20370. * @param camera defines the camera to use to pick the right LOD level
  20371. * @returns the currentAbstractMesh
  20372. */
  20373. AbstractMesh.prototype.getLOD = function (camera) {
  20374. return this;
  20375. };
  20376. /**
  20377. * Returns 0 by default. Implemented by child classes
  20378. * @returns an integer
  20379. */
  20380. AbstractMesh.prototype.getTotalVertices = function () {
  20381. return 0;
  20382. };
  20383. /**
  20384. * Returns null by default. Implemented by child classes
  20385. * @returns null
  20386. */
  20387. AbstractMesh.prototype.getIndices = function () {
  20388. return null;
  20389. };
  20390. /**
  20391. * Returns the array of the requested vertex data kind. Implemented by child classes
  20392. * @param kind defines the vertex data kind to use
  20393. * @returns null
  20394. */
  20395. AbstractMesh.prototype.getVerticesData = function (kind) {
  20396. return null;
  20397. };
  20398. /**
  20399. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20400. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20401. * Note that a new underlying VertexBuffer object is created each call.
  20402. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20403. * @param kind defines vertex data kind:
  20404. * * BABYLON.VertexBuffer.PositionKind
  20405. * * BABYLON.VertexBuffer.UVKind
  20406. * * BABYLON.VertexBuffer.UV2Kind
  20407. * * BABYLON.VertexBuffer.UV3Kind
  20408. * * BABYLON.VertexBuffer.UV4Kind
  20409. * * BABYLON.VertexBuffer.UV5Kind
  20410. * * BABYLON.VertexBuffer.UV6Kind
  20411. * * BABYLON.VertexBuffer.ColorKind
  20412. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20413. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20414. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20415. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20416. * @param data defines the data source
  20417. * @param updatable defines if the data must be flagged as updatable (or static)
  20418. * @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
  20419. * @returns the current mesh
  20420. */
  20421. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20422. return this;
  20423. };
  20424. /**
  20425. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20426. * If the mesh has no geometry, it is simply returned as it is.
  20427. * @param kind defines vertex data kind:
  20428. * * BABYLON.VertexBuffer.PositionKind
  20429. * * BABYLON.VertexBuffer.UVKind
  20430. * * BABYLON.VertexBuffer.UV2Kind
  20431. * * BABYLON.VertexBuffer.UV3Kind
  20432. * * BABYLON.VertexBuffer.UV4Kind
  20433. * * BABYLON.VertexBuffer.UV5Kind
  20434. * * BABYLON.VertexBuffer.UV6Kind
  20435. * * BABYLON.VertexBuffer.ColorKind
  20436. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20437. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20438. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20439. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20440. * @param data defines the data source
  20441. * @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
  20442. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20443. * @returns the current mesh
  20444. */
  20445. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20446. return this;
  20447. };
  20448. /**
  20449. * Sets the mesh indices,
  20450. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20451. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20452. * @param totalVertices Defines the total number of vertices
  20453. * @returns the current mesh
  20454. */
  20455. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20456. return this;
  20457. };
  20458. /**
  20459. * Gets a boolean indicating if specific vertex data is present
  20460. * @param kind defines the vertex data kind to use
  20461. * @returns true is data kind is present
  20462. */
  20463. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20464. return false;
  20465. };
  20466. /**
  20467. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20468. * @returns a BoundingInfo
  20469. */
  20470. AbstractMesh.prototype.getBoundingInfo = function () {
  20471. if (this._masterMesh) {
  20472. return this._masterMesh.getBoundingInfo();
  20473. }
  20474. if (!this._boundingInfo) {
  20475. // this._boundingInfo is being created here
  20476. this._updateBoundingInfo();
  20477. }
  20478. // cannot be null.
  20479. return this._boundingInfo;
  20480. };
  20481. /**
  20482. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20483. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20484. * @returns the current mesh
  20485. */
  20486. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20487. if (includeDescendants === void 0) { includeDescendants = true; }
  20488. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20489. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20490. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20491. if (maxDimension === 0) {
  20492. return this;
  20493. }
  20494. var scale = 1 / maxDimension;
  20495. this.scaling.scaleInPlace(scale);
  20496. return this;
  20497. };
  20498. /**
  20499. * Overwrite the current bounding info
  20500. * @param boundingInfo defines the new bounding info
  20501. * @returns the current mesh
  20502. */
  20503. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20504. this._boundingInfo = boundingInfo;
  20505. return this;
  20506. };
  20507. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20508. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20509. get: function () {
  20510. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20511. },
  20512. enumerable: true,
  20513. configurable: true
  20514. });
  20515. /** @hidden */
  20516. AbstractMesh.prototype._preActivate = function () {
  20517. };
  20518. /** @hidden */
  20519. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20520. };
  20521. /** @hidden */
  20522. AbstractMesh.prototype._activate = function (renderId) {
  20523. this._renderId = renderId;
  20524. };
  20525. /**
  20526. * Gets the current world matrix
  20527. * @returns a Matrix
  20528. */
  20529. AbstractMesh.prototype.getWorldMatrix = function () {
  20530. if (this._masterMesh) {
  20531. return this._masterMesh.getWorldMatrix();
  20532. }
  20533. return _super.prototype.getWorldMatrix.call(this);
  20534. };
  20535. /** @hidden */
  20536. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20537. if (this._masterMesh) {
  20538. return this._masterMesh._getWorldMatrixDeterminant();
  20539. }
  20540. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20541. };
  20542. // ================================== Point of View Movement =================================
  20543. /**
  20544. * Perform relative position change from the point of view of behind the front of the mesh.
  20545. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20546. * Supports definition of mesh facing forward or backward
  20547. * @param amountRight defines the distance on the right axis
  20548. * @param amountUp defines the distance on the up axis
  20549. * @param amountForward defines the distance on the forward axis
  20550. * @returns the current mesh
  20551. */
  20552. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20553. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20554. return this;
  20555. };
  20556. /**
  20557. * Calculate relative position change from the point of view of behind the front of the mesh.
  20558. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20559. * Supports definition of mesh facing forward or backward
  20560. * @param amountRight defines the distance on the right axis
  20561. * @param amountUp defines the distance on the up axis
  20562. * @param amountForward defines the distance on the forward axis
  20563. * @returns the new displacement vector
  20564. */
  20565. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20566. var rotMatrix = new BABYLON.Matrix();
  20567. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20568. rotQuaternion.toRotationMatrix(rotMatrix);
  20569. var translationDelta = BABYLON.Vector3.Zero();
  20570. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20571. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20572. return translationDelta;
  20573. };
  20574. // ================================== Point of View Rotation =================================
  20575. /**
  20576. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20577. * Supports definition of mesh facing forward or backward
  20578. * @param flipBack defines the flip
  20579. * @param twirlClockwise defines the twirl
  20580. * @param tiltRight defines the tilt
  20581. * @returns the current mesh
  20582. */
  20583. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20584. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20585. return this;
  20586. };
  20587. /**
  20588. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20589. * Supports definition of mesh facing forward or backward.
  20590. * @param flipBack defines the flip
  20591. * @param twirlClockwise defines the twirl
  20592. * @param tiltRight defines the tilt
  20593. * @returns the new rotation vector
  20594. */
  20595. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20596. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20597. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20598. };
  20599. /**
  20600. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20601. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20602. * @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
  20603. * @returns the new bounding vectors
  20604. */
  20605. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20606. if (includeDescendants === void 0) { includeDescendants = true; }
  20607. if (predicate === void 0) { predicate = null; }
  20608. // Ensures that all world matrix will be recomputed.
  20609. this.getScene().incrementRenderId();
  20610. this.computeWorldMatrix(true);
  20611. var min;
  20612. var max;
  20613. var boundingInfo = this.getBoundingInfo();
  20614. if (!this.subMeshes) {
  20615. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20616. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20617. }
  20618. else {
  20619. min = boundingInfo.boundingBox.minimumWorld;
  20620. max = boundingInfo.boundingBox.maximumWorld;
  20621. }
  20622. if (includeDescendants) {
  20623. var descendants = this.getDescendants(false);
  20624. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20625. var descendant = descendants_1[_i];
  20626. var childMesh = descendant;
  20627. childMesh.computeWorldMatrix(true);
  20628. // Filters meshes based on custom predicate function.
  20629. if (predicate && !predicate(childMesh)) {
  20630. continue;
  20631. }
  20632. //make sure we have the needed params to get mix and max
  20633. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20634. continue;
  20635. }
  20636. var childBoundingInfo = childMesh.getBoundingInfo();
  20637. var boundingBox = childBoundingInfo.boundingBox;
  20638. var minBox = boundingBox.minimumWorld;
  20639. var maxBox = boundingBox.maximumWorld;
  20640. BABYLON.Tools.CheckExtends(minBox, min, max);
  20641. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20642. }
  20643. }
  20644. return {
  20645. min: min,
  20646. max: max
  20647. };
  20648. };
  20649. /** @hidden */
  20650. AbstractMesh.prototype._updateBoundingInfo = function () {
  20651. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20652. this._boundingInfo.update(this.worldMatrixFromCache);
  20653. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20654. return this;
  20655. };
  20656. /** @hidden */
  20657. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20658. if (!this.subMeshes) {
  20659. return this;
  20660. }
  20661. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20662. var subMesh = this.subMeshes[subIndex];
  20663. if (!subMesh.IsGlobal) {
  20664. subMesh.updateBoundingInfo(matrix);
  20665. }
  20666. }
  20667. return this;
  20668. };
  20669. /** @hidden */
  20670. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20671. // Bounding info
  20672. this._updateBoundingInfo();
  20673. };
  20674. /**
  20675. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20676. * A mesh is in the frustum if its bounding box intersects the frustum
  20677. * @param frustumPlanes defines the frustum to test
  20678. * @returns true if the mesh is in the frustum planes
  20679. */
  20680. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20681. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20682. };
  20683. /**
  20684. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20685. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20686. * @param frustumPlanes defines the frustum to test
  20687. * @returns true if the mesh is completely in the frustum planes
  20688. */
  20689. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20690. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20691. };
  20692. /**
  20693. * True if the mesh intersects another mesh or a SolidParticle object
  20694. * @param mesh defines a target mesh or SolidParticle to test
  20695. * @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)
  20696. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20697. * @returns true if there is an intersection
  20698. */
  20699. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20700. if (precise === void 0) { precise = false; }
  20701. if (!this._boundingInfo || !mesh._boundingInfo) {
  20702. return false;
  20703. }
  20704. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20705. return true;
  20706. }
  20707. if (includeDescendants) {
  20708. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20709. var child = _a[_i];
  20710. if (child.intersectsMesh(mesh, precise, true)) {
  20711. return true;
  20712. }
  20713. }
  20714. }
  20715. return false;
  20716. };
  20717. /**
  20718. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20719. * @param point defines the point to test
  20720. * @returns true if there is an intersection
  20721. */
  20722. AbstractMesh.prototype.intersectsPoint = function (point) {
  20723. if (!this._boundingInfo) {
  20724. return false;
  20725. }
  20726. return this._boundingInfo.intersectsPoint(point);
  20727. };
  20728. /**
  20729. * Gets the position of the current mesh in camera space
  20730. * @param camera defines the camera to use
  20731. * @returns a position
  20732. */
  20733. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20734. if (camera === void 0) { camera = null; }
  20735. if (!camera) {
  20736. camera = this.getScene().activeCamera;
  20737. }
  20738. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20739. };
  20740. /**
  20741. * Returns the distance from the mesh to the active camera
  20742. * @param camera defines the camera to use
  20743. * @returns the distance
  20744. */
  20745. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20746. if (camera === void 0) { camera = null; }
  20747. if (!camera) {
  20748. camera = this.getScene().activeCamera;
  20749. }
  20750. return this.absolutePosition.subtract(camera.position).length();
  20751. };
  20752. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20753. // Collisions
  20754. /**
  20755. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20756. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20757. */
  20758. get: function () {
  20759. return this._checkCollisions;
  20760. },
  20761. set: function (collisionEnabled) {
  20762. this._checkCollisions = collisionEnabled;
  20763. if (this.getScene().workerCollisions) {
  20764. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20765. }
  20766. },
  20767. enumerable: true,
  20768. configurable: true
  20769. });
  20770. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20771. /**
  20772. * Gets Collider object used to compute collisions (not physics)
  20773. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20774. */
  20775. get: function () {
  20776. return this._collider;
  20777. },
  20778. enumerable: true,
  20779. configurable: true
  20780. });
  20781. /**
  20782. * Move the mesh using collision engine
  20783. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20784. * @param displacement defines the requested displacement vector
  20785. * @returns the current mesh
  20786. */
  20787. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20788. var globalPosition = this.getAbsolutePosition();
  20789. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20790. if (!this._collider) {
  20791. this._collider = new BABYLON.Collider();
  20792. }
  20793. this._collider._radius = this.ellipsoid;
  20794. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20795. return this;
  20796. };
  20797. // Collisions
  20798. /** @hidden */
  20799. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20800. this._generatePointsArray();
  20801. if (!this._positions) {
  20802. return this;
  20803. }
  20804. // Transformation
  20805. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20806. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20807. subMesh._lastColliderWorldVertices = [];
  20808. subMesh._trianglePlanes = [];
  20809. var start = subMesh.verticesStart;
  20810. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20811. for (var i = start; i < end; i++) {
  20812. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20813. }
  20814. }
  20815. // Collide
  20816. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20817. if (collider.collisionFound) {
  20818. collider.collidedMesh = this;
  20819. }
  20820. return this;
  20821. };
  20822. /** @hidden */
  20823. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20824. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20825. var len = subMeshes.length;
  20826. for (var index = 0; index < len; index++) {
  20827. var subMesh = subMeshes.data[index];
  20828. // Bounding test
  20829. if (len > 1 && !subMesh._checkCollision(collider))
  20830. continue;
  20831. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20832. }
  20833. return this;
  20834. };
  20835. /** @hidden */
  20836. AbstractMesh.prototype._checkCollision = function (collider) {
  20837. // Bounding box test
  20838. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20839. return this;
  20840. // Transformation matrix
  20841. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20842. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20843. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20844. return this;
  20845. };
  20846. // Picking
  20847. /** @hidden */
  20848. AbstractMesh.prototype._generatePointsArray = function () {
  20849. return false;
  20850. };
  20851. /**
  20852. * Checks if the passed Ray intersects with the mesh
  20853. * @param ray defines the ray to use
  20854. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20855. * @returns the picking info
  20856. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20857. */
  20858. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20859. var pickingInfo = new BABYLON.PickingInfo();
  20860. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20861. return pickingInfo;
  20862. }
  20863. if (!this._generatePointsArray()) {
  20864. return pickingInfo;
  20865. }
  20866. var intersectInfo = null;
  20867. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20868. var len = subMeshes.length;
  20869. for (var index = 0; index < len; index++) {
  20870. var subMesh = subMeshes.data[index];
  20871. // Bounding test
  20872. if (len > 1 && !subMesh.canIntersects(ray))
  20873. continue;
  20874. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20875. if (currentIntersectInfo) {
  20876. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20877. intersectInfo = currentIntersectInfo;
  20878. intersectInfo.subMeshId = index;
  20879. if (fastCheck) {
  20880. break;
  20881. }
  20882. }
  20883. }
  20884. }
  20885. if (intersectInfo) {
  20886. // Get picked point
  20887. var world = this.getWorldMatrix();
  20888. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20889. var direction = ray.direction.clone();
  20890. direction = direction.scale(intersectInfo.distance);
  20891. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20892. var pickedPoint = worldOrigin.add(worldDirection);
  20893. // Return result
  20894. pickingInfo.hit = true;
  20895. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20896. pickingInfo.pickedPoint = pickedPoint;
  20897. pickingInfo.pickedMesh = this;
  20898. pickingInfo.bu = intersectInfo.bu || 0;
  20899. pickingInfo.bv = intersectInfo.bv || 0;
  20900. pickingInfo.faceId = intersectInfo.faceId;
  20901. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20902. return pickingInfo;
  20903. }
  20904. return pickingInfo;
  20905. };
  20906. /**
  20907. * Clones the current mesh
  20908. * @param name defines the mesh name
  20909. * @param newParent defines the new mesh parent
  20910. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20911. * @returns the new mesh
  20912. */
  20913. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20914. return null;
  20915. };
  20916. /**
  20917. * Disposes all the submeshes of the current meshnp
  20918. * @returns the current mesh
  20919. */
  20920. AbstractMesh.prototype.releaseSubMeshes = function () {
  20921. if (this.subMeshes) {
  20922. while (this.subMeshes.length) {
  20923. this.subMeshes[0].dispose();
  20924. }
  20925. }
  20926. else {
  20927. this.subMeshes = new Array();
  20928. }
  20929. return this;
  20930. };
  20931. /**
  20932. * Releases resources associated with this abstract mesh.
  20933. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20934. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20935. */
  20936. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20937. var _this = this;
  20938. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20939. var index;
  20940. // Smart Array Retainers.
  20941. this.getScene().freeActiveMeshes();
  20942. this.getScene().freeRenderingGroups();
  20943. // Action manager
  20944. if (this.actionManager !== undefined && this.actionManager !== null) {
  20945. this.actionManager.dispose();
  20946. this.actionManager = null;
  20947. }
  20948. // Skeleton
  20949. this._skeleton = null;
  20950. // Intersections in progress
  20951. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20952. var other = this._intersectionsInProgress[index];
  20953. var pos = other._intersectionsInProgress.indexOf(this);
  20954. other._intersectionsInProgress.splice(pos, 1);
  20955. }
  20956. this._intersectionsInProgress = [];
  20957. // Lights
  20958. var lights = this.getScene().lights;
  20959. lights.forEach(function (light) {
  20960. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20961. if (meshIndex !== -1) {
  20962. light.includedOnlyMeshes.splice(meshIndex, 1);
  20963. }
  20964. meshIndex = light.excludedMeshes.indexOf(_this);
  20965. if (meshIndex !== -1) {
  20966. light.excludedMeshes.splice(meshIndex, 1);
  20967. }
  20968. // Shadow generators
  20969. var generator = light.getShadowGenerator();
  20970. if (generator) {
  20971. var shadowMap = generator.getShadowMap();
  20972. if (shadowMap && shadowMap.renderList) {
  20973. meshIndex = shadowMap.renderList.indexOf(_this);
  20974. if (meshIndex !== -1) {
  20975. shadowMap.renderList.splice(meshIndex, 1);
  20976. }
  20977. }
  20978. }
  20979. });
  20980. // SubMeshes
  20981. if (this.getClassName() !== "InstancedMesh") {
  20982. this.releaseSubMeshes();
  20983. }
  20984. // Query
  20985. var engine = this.getScene().getEngine();
  20986. if (this._occlusionQuery) {
  20987. this._isOcclusionQueryInProgress = false;
  20988. engine.deleteQuery(this._occlusionQuery);
  20989. this._occlusionQuery = null;
  20990. }
  20991. // Engine
  20992. engine.wipeCaches();
  20993. // Remove from scene
  20994. this.getScene().removeMesh(this);
  20995. if (disposeMaterialAndTextures) {
  20996. if (this.material) {
  20997. this.material.dispose(false, true);
  20998. }
  20999. }
  21000. if (!doNotRecurse) {
  21001. // Particles
  21002. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21003. if (this.getScene().particleSystems[index].emitter === this) {
  21004. this.getScene().particleSystems[index].dispose();
  21005. index--;
  21006. }
  21007. }
  21008. }
  21009. // facet data
  21010. if (this._facetDataEnabled) {
  21011. this.disableFacetData();
  21012. }
  21013. this.onAfterWorldMatrixUpdateObservable.clear();
  21014. this.onCollideObservable.clear();
  21015. this.onCollisionPositionChangeObservable.clear();
  21016. this.onRebuildObservable.clear();
  21017. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21018. };
  21019. /**
  21020. * Adds the passed mesh as a child to the current mesh
  21021. * @param mesh defines the child mesh
  21022. * @returns the current mesh
  21023. */
  21024. AbstractMesh.prototype.addChild = function (mesh) {
  21025. mesh.setParent(this);
  21026. return this;
  21027. };
  21028. /**
  21029. * Removes the passed mesh from the current mesh children list
  21030. * @param mesh defines the child mesh
  21031. * @returns the current mesh
  21032. */
  21033. AbstractMesh.prototype.removeChild = function (mesh) {
  21034. mesh.setParent(null);
  21035. return this;
  21036. };
  21037. // Facet data
  21038. /** @hidden */
  21039. AbstractMesh.prototype._initFacetData = function () {
  21040. if (!this._facetNormals) {
  21041. this._facetNormals = new Array();
  21042. }
  21043. if (!this._facetPositions) {
  21044. this._facetPositions = new Array();
  21045. }
  21046. if (!this._facetPartitioning) {
  21047. this._facetPartitioning = new Array();
  21048. }
  21049. this._facetNb = (this.getIndices().length / 3) | 0;
  21050. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21051. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21052. for (var f = 0; f < this._facetNb; f++) {
  21053. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21054. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21055. }
  21056. this._facetDataEnabled = true;
  21057. return this;
  21058. };
  21059. /**
  21060. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21061. * This method can be called within the render loop.
  21062. * 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
  21063. * @returns the current mesh
  21064. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21065. */
  21066. AbstractMesh.prototype.updateFacetData = function () {
  21067. if (!this._facetDataEnabled) {
  21068. this._initFacetData();
  21069. }
  21070. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21071. var indices = this.getIndices();
  21072. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21073. var bInfo = this.getBoundingInfo();
  21074. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21075. // init arrays, matrix and sort function on first call
  21076. this._facetDepthSortEnabled = true;
  21077. if (indices instanceof Uint16Array) {
  21078. this._depthSortedIndices = new Uint16Array(indices);
  21079. }
  21080. else if (indices instanceof Uint32Array) {
  21081. this._depthSortedIndices = new Uint32Array(indices);
  21082. }
  21083. else {
  21084. var needs32bits = false;
  21085. for (var i = 0; i < indices.length; i++) {
  21086. if (indices[i] > 65535) {
  21087. needs32bits = true;
  21088. break;
  21089. }
  21090. }
  21091. if (needs32bits) {
  21092. this._depthSortedIndices = new Uint32Array(indices);
  21093. }
  21094. else {
  21095. this._depthSortedIndices = new Uint16Array(indices);
  21096. }
  21097. }
  21098. this._facetDepthSortFunction = function (f1, f2) {
  21099. return (f2.sqDistance - f1.sqDistance);
  21100. };
  21101. if (!this._facetDepthSortFrom) {
  21102. var camera = this.getScene().activeCamera;
  21103. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21104. }
  21105. this._depthSortedFacets = [];
  21106. for (var f = 0; f < this._facetNb; f++) {
  21107. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21108. this._depthSortedFacets.push(depthSortedFacet);
  21109. }
  21110. this._invertedMatrix = BABYLON.Matrix.Identity();
  21111. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21112. }
  21113. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21114. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21115. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21116. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21117. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21118. this._subDiv.max = this._partitioningSubdivisions;
  21119. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21120. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21121. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21122. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21123. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21124. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21125. // set the parameters for ComputeNormals()
  21126. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21127. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21128. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21129. this._facetParameters.bInfo = bInfo;
  21130. this._facetParameters.bbSize = this._bbSize;
  21131. this._facetParameters.subDiv = this._subDiv;
  21132. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21133. this._facetParameters.depthSort = this._facetDepthSort;
  21134. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21135. this.computeWorldMatrix(true);
  21136. this._worldMatrix.invertToRef(this._invertedMatrix);
  21137. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21138. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21139. }
  21140. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21141. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21142. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21143. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21144. var l = (this._depthSortedIndices.length / 3) | 0;
  21145. for (var f = 0; f < l; f++) {
  21146. var sind = this._depthSortedFacets[f].ind;
  21147. this._depthSortedIndices[f * 3] = indices[sind];
  21148. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21149. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21150. }
  21151. this.updateIndices(this._depthSortedIndices);
  21152. }
  21153. return this;
  21154. };
  21155. /**
  21156. * Returns the facetLocalNormals array.
  21157. * The normals are expressed in the mesh local spac
  21158. * @returns an array of Vector3
  21159. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21160. */
  21161. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21162. if (!this._facetNormals) {
  21163. this.updateFacetData();
  21164. }
  21165. return this._facetNormals;
  21166. };
  21167. /**
  21168. * Returns the facetLocalPositions array.
  21169. * The facet positions are expressed in the mesh local space
  21170. * @returns an array of Vector3
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21174. if (!this._facetPositions) {
  21175. this.updateFacetData();
  21176. }
  21177. return this._facetPositions;
  21178. };
  21179. /**
  21180. * Returns the facetLocalPartioning array
  21181. * @returns an array of array of numbers
  21182. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21183. */
  21184. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21185. if (!this._facetPartitioning) {
  21186. this.updateFacetData();
  21187. }
  21188. return this._facetPartitioning;
  21189. };
  21190. /**
  21191. * Returns the i-th facet position in the world system.
  21192. * This method allocates a new Vector3 per call
  21193. * @param i defines the facet index
  21194. * @returns a new Vector3
  21195. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21196. */
  21197. AbstractMesh.prototype.getFacetPosition = function (i) {
  21198. var pos = BABYLON.Vector3.Zero();
  21199. this.getFacetPositionToRef(i, pos);
  21200. return pos;
  21201. };
  21202. /**
  21203. * Sets the reference Vector3 with the i-th facet position in the world system
  21204. * @param i defines the facet index
  21205. * @param ref defines the target vector
  21206. * @returns the current mesh
  21207. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21208. */
  21209. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21210. var localPos = (this.getFacetLocalPositions())[i];
  21211. var world = this.getWorldMatrix();
  21212. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21213. return this;
  21214. };
  21215. /**
  21216. * Returns the i-th facet normal in the world system.
  21217. * This method allocates a new Vector3 per call
  21218. * @param i defines the facet index
  21219. * @returns a new Vector3
  21220. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21221. */
  21222. AbstractMesh.prototype.getFacetNormal = function (i) {
  21223. var norm = BABYLON.Vector3.Zero();
  21224. this.getFacetNormalToRef(i, norm);
  21225. return norm;
  21226. };
  21227. /**
  21228. * Sets the reference Vector3 with the i-th facet normal in the world system
  21229. * @param i defines the facet index
  21230. * @param ref defines the target vector
  21231. * @returns the current mesh
  21232. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21233. */
  21234. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21235. var localNorm = (this.getFacetLocalNormals())[i];
  21236. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21237. return this;
  21238. };
  21239. /**
  21240. * 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)
  21241. * @param x defines x coordinate
  21242. * @param y defines y coordinate
  21243. * @param z defines z coordinate
  21244. * @returns the array of facet indexes
  21245. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21246. */
  21247. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21248. var bInfo = this.getBoundingInfo();
  21249. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21250. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21251. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21252. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21253. return null;
  21254. }
  21255. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21256. };
  21257. /**
  21258. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21259. * @param projected sets as the (x,y,z) world projection on the facet
  21260. * @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
  21261. * @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
  21262. * @param x defines x coordinate
  21263. * @param y defines y coordinate
  21264. * @param z defines z coordinate
  21265. * @returns the face index if found (or null instead)
  21266. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21267. */
  21268. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21269. if (checkFace === void 0) { checkFace = false; }
  21270. if (facing === void 0) { facing = true; }
  21271. var world = this.getWorldMatrix();
  21272. var invMat = BABYLON.Tmp.Matrix[5];
  21273. world.invertToRef(invMat);
  21274. var invVect = BABYLON.Tmp.Vector3[8];
  21275. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21276. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21277. if (projected) {
  21278. // tranform the local computed projected vector to world coordinates
  21279. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21280. }
  21281. return closest;
  21282. };
  21283. /**
  21284. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21285. * @param projected sets as the (x,y,z) local projection on the facet
  21286. * @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
  21287. * @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
  21288. * @param x defines x coordinate
  21289. * @param y defines y coordinate
  21290. * @param z defines z coordinate
  21291. * @returns the face index if found (or null instead)
  21292. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21293. */
  21294. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21295. if (checkFace === void 0) { checkFace = false; }
  21296. if (facing === void 0) { facing = true; }
  21297. var closest = null;
  21298. var tmpx = 0.0;
  21299. var tmpy = 0.0;
  21300. var tmpz = 0.0;
  21301. var d = 0.0; // tmp dot facet normal * facet position
  21302. var t0 = 0.0;
  21303. var projx = 0.0;
  21304. var projy = 0.0;
  21305. var projz = 0.0;
  21306. // Get all the facets in the same partitioning block than (x, y, z)
  21307. var facetPositions = this.getFacetLocalPositions();
  21308. var facetNormals = this.getFacetLocalNormals();
  21309. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21310. if (!facetsInBlock) {
  21311. return null;
  21312. }
  21313. // Get the closest facet to (x, y, z)
  21314. var shortest = Number.MAX_VALUE; // init distance vars
  21315. var tmpDistance = shortest;
  21316. var fib; // current facet in the block
  21317. var norm; // current facet normal
  21318. var p0; // current facet barycenter position
  21319. // loop on all the facets in the current partitioning block
  21320. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21321. fib = facetsInBlock[idx];
  21322. norm = facetNormals[fib];
  21323. p0 = facetPositions[fib];
  21324. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21325. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21326. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21327. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21328. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21329. projx = x + norm.x * t0;
  21330. projy = y + norm.y * t0;
  21331. projz = z + norm.z * t0;
  21332. tmpx = projx - x;
  21333. tmpy = projy - y;
  21334. tmpz = projz - z;
  21335. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21336. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21337. shortest = tmpDistance;
  21338. closest = fib;
  21339. if (projected) {
  21340. projected.x = projx;
  21341. projected.y = projy;
  21342. projected.z = projz;
  21343. }
  21344. }
  21345. }
  21346. }
  21347. return closest;
  21348. };
  21349. /**
  21350. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21351. * @returns the parameters
  21352. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21353. */
  21354. AbstractMesh.prototype.getFacetDataParameters = function () {
  21355. return this._facetParameters;
  21356. };
  21357. /**
  21358. * Disables the feature FacetData and frees the related memory
  21359. * @returns the current mesh
  21360. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21361. */
  21362. AbstractMesh.prototype.disableFacetData = function () {
  21363. if (this._facetDataEnabled) {
  21364. this._facetDataEnabled = false;
  21365. this._facetPositions = new Array();
  21366. this._facetNormals = new Array();
  21367. this._facetPartitioning = new Array();
  21368. this._facetParameters = null;
  21369. this._depthSortedIndices = new Uint32Array(0);
  21370. }
  21371. return this;
  21372. };
  21373. /**
  21374. * Updates the AbstractMesh indices array
  21375. * @param indices defines the data source
  21376. * @returns the current mesh
  21377. */
  21378. AbstractMesh.prototype.updateIndices = function (indices) {
  21379. return this;
  21380. };
  21381. /**
  21382. * Creates new normals data for the mesh
  21383. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21384. * @returns the current mesh
  21385. */
  21386. AbstractMesh.prototype.createNormals = function (updatable) {
  21387. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21388. var indices = this.getIndices();
  21389. var normals;
  21390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21391. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21392. }
  21393. else {
  21394. normals = [];
  21395. }
  21396. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21397. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21398. return this;
  21399. };
  21400. /**
  21401. * Align the mesh with a normal
  21402. * @param normal defines the normal to use
  21403. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21404. * @returns the current mesh
  21405. */
  21406. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21407. if (!upDirection) {
  21408. upDirection = BABYLON.Axis.Y;
  21409. }
  21410. var axisX = BABYLON.Tmp.Vector3[0];
  21411. var axisZ = BABYLON.Tmp.Vector3[1];
  21412. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21413. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21414. if (this.rotationQuaternion) {
  21415. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21416. }
  21417. else {
  21418. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21419. }
  21420. return this;
  21421. };
  21422. /** @hidden */
  21423. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21424. this._isOccluded = false;
  21425. };
  21426. /** No occlusion */
  21427. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21428. /** Occlusion set to optimisitic */
  21429. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21430. /** Occlusion set to strict */
  21431. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21432. /** Use an accurante occlusion algorithm */
  21433. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21434. /** Use a conservative occlusion algorithm */
  21435. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21436. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21437. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21438. /** Culling strategy with bounding sphere only and then frustum culling */
  21439. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21440. return AbstractMesh;
  21441. }(BABYLON.TransformNode));
  21442. BABYLON.AbstractMesh = AbstractMesh;
  21443. })(BABYLON || (BABYLON = {}));
  21444. //# sourceMappingURL=babylon.abstractMesh.js.map
  21445. var BABYLON;
  21446. (function (BABYLON) {
  21447. /**
  21448. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21449. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21450. * 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.
  21451. */
  21452. var Light = /** @class */ (function (_super) {
  21453. __extends(Light, _super);
  21454. /**
  21455. * Creates a Light object in the scene.
  21456. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21457. * @param name The firendly name of the light
  21458. * @param scene The scene the light belongs too
  21459. */
  21460. function Light(name, scene) {
  21461. var _this = _super.call(this, name, scene) || this;
  21462. /**
  21463. * Diffuse gives the basic color to an object.
  21464. */
  21465. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21466. /**
  21467. * Specular produces a highlight color on an object.
  21468. * Note: This is note affecting PBR materials.
  21469. */
  21470. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21471. /**
  21472. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21473. * falling off base on range or angle.
  21474. * This can be set to any values in Light.FALLOFF_x.
  21475. *
  21476. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21477. * other types of materials.
  21478. */
  21479. _this.falloffType = Light.FALLOFF_DEFAULT;
  21480. /**
  21481. * Strength of the light.
  21482. * Note: By default it is define in the framework own unit.
  21483. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21484. */
  21485. _this.intensity = 1.0;
  21486. _this._range = Number.MAX_VALUE;
  21487. _this._inverseSquaredRange = 0;
  21488. /**
  21489. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21490. * of light.
  21491. */
  21492. _this._photometricScale = 1.0;
  21493. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21494. _this._radius = 0.00001;
  21495. /**
  21496. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21497. * exceeding the number allowed of the materials.
  21498. */
  21499. _this.renderPriority = 0;
  21500. _this._shadowEnabled = true;
  21501. _this._excludeWithLayerMask = 0;
  21502. _this._includeOnlyWithLayerMask = 0;
  21503. _this._lightmapMode = 0;
  21504. /**
  21505. * @hidden Internal use only.
  21506. */
  21507. _this._excludedMeshesIds = new Array();
  21508. /**
  21509. * @hidden Internal use only.
  21510. */
  21511. _this._includedOnlyMeshesIds = new Array();
  21512. _this.getScene().addLight(_this);
  21513. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21514. _this._buildUniformLayout();
  21515. _this.includedOnlyMeshes = new Array();
  21516. _this.excludedMeshes = new Array();
  21517. _this._resyncMeshes();
  21518. return _this;
  21519. }
  21520. Object.defineProperty(Light.prototype, "range", {
  21521. /**
  21522. * Defines how far from the source the light is impacting in scene units.
  21523. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21524. */
  21525. get: function () {
  21526. return this._range;
  21527. },
  21528. /**
  21529. * Defines how far from the source the light is impacting in scene units.
  21530. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21531. */
  21532. set: function (value) {
  21533. this._range = value;
  21534. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21535. },
  21536. enumerable: true,
  21537. configurable: true
  21538. });
  21539. Object.defineProperty(Light.prototype, "intensityMode", {
  21540. /**
  21541. * Gets the photometric scale used to interpret the intensity.
  21542. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21543. */
  21544. get: function () {
  21545. return this._intensityMode;
  21546. },
  21547. /**
  21548. * Sets the photometric scale used to interpret the intensity.
  21549. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21550. */
  21551. set: function (value) {
  21552. this._intensityMode = value;
  21553. this._computePhotometricScale();
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. ;
  21559. ;
  21560. Object.defineProperty(Light.prototype, "radius", {
  21561. /**
  21562. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21563. */
  21564. get: function () {
  21565. return this._radius;
  21566. },
  21567. /**
  21568. * sets the light radius used by PBR Materials to simulate soft area lights.
  21569. */
  21570. set: function (value) {
  21571. this._radius = value;
  21572. this._computePhotometricScale();
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. ;
  21578. ;
  21579. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21580. /**
  21581. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21582. * the current shadow generator.
  21583. */
  21584. get: function () {
  21585. return this._shadowEnabled;
  21586. },
  21587. /**
  21588. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21589. * the current shadow generator.
  21590. */
  21591. set: function (value) {
  21592. if (this._shadowEnabled === value) {
  21593. return;
  21594. }
  21595. this._shadowEnabled = value;
  21596. this._markMeshesAsLightDirty();
  21597. },
  21598. enumerable: true,
  21599. configurable: true
  21600. });
  21601. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21602. /**
  21603. * Gets the only meshes impacted by this light.
  21604. */
  21605. get: function () {
  21606. return this._includedOnlyMeshes;
  21607. },
  21608. /**
  21609. * Sets the only meshes impacted by this light.
  21610. */
  21611. set: function (value) {
  21612. this._includedOnlyMeshes = value;
  21613. this._hookArrayForIncludedOnly(value);
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21619. /**
  21620. * Gets the meshes not impacted by this light.
  21621. */
  21622. get: function () {
  21623. return this._excludedMeshes;
  21624. },
  21625. /**
  21626. * Sets the meshes not impacted by this light.
  21627. */
  21628. set: function (value) {
  21629. this._excludedMeshes = value;
  21630. this._hookArrayForExcluded(value);
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21636. /**
  21637. * Gets the layer id use to find what meshes are not impacted by the light.
  21638. * Inactive if 0
  21639. */
  21640. get: function () {
  21641. return this._excludeWithLayerMask;
  21642. },
  21643. /**
  21644. * Sets the layer id use to find what meshes are not impacted by the light.
  21645. * Inactive if 0
  21646. */
  21647. set: function (value) {
  21648. this._excludeWithLayerMask = value;
  21649. this._resyncMeshes();
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21655. /**
  21656. * Gets the layer id use to find what meshes are impacted by the light.
  21657. * Inactive if 0
  21658. */
  21659. get: function () {
  21660. return this._includeOnlyWithLayerMask;
  21661. },
  21662. /**
  21663. * Sets the layer id use to find what meshes are impacted by the light.
  21664. * Inactive if 0
  21665. */
  21666. set: function (value) {
  21667. this._includeOnlyWithLayerMask = value;
  21668. this._resyncMeshes();
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Object.defineProperty(Light.prototype, "lightmapMode", {
  21674. /**
  21675. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21676. */
  21677. get: function () {
  21678. return this._lightmapMode;
  21679. },
  21680. /**
  21681. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21682. */
  21683. set: function (value) {
  21684. if (this._lightmapMode === value) {
  21685. return;
  21686. }
  21687. this._lightmapMode = value;
  21688. this._markMeshesAsLightDirty();
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. /**
  21694. * Returns the string "Light".
  21695. * @returns the class name
  21696. */
  21697. Light.prototype.getClassName = function () {
  21698. return "Light";
  21699. };
  21700. /**
  21701. * Converts the light information to a readable string for debug purpose.
  21702. * @param fullDetails Supports for multiple levels of logging within scene loading
  21703. * @returns the human readable light info
  21704. */
  21705. Light.prototype.toString = function (fullDetails) {
  21706. var ret = "Name: " + this.name;
  21707. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21708. if (this.animations) {
  21709. for (var i = 0; i < this.animations.length; i++) {
  21710. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21711. }
  21712. }
  21713. if (fullDetails) {
  21714. }
  21715. return ret;
  21716. };
  21717. /** @hidden */
  21718. Light.prototype._syncParentEnabledState = function () {
  21719. _super.prototype._syncParentEnabledState.call(this);
  21720. this._resyncMeshes();
  21721. };
  21722. /**
  21723. * Set the enabled state of this node.
  21724. * @param value - the new enabled state
  21725. */
  21726. Light.prototype.setEnabled = function (value) {
  21727. _super.prototype.setEnabled.call(this, value);
  21728. this._resyncMeshes();
  21729. };
  21730. /**
  21731. * Returns the Light associated shadow generator if any.
  21732. * @return the associated shadow generator.
  21733. */
  21734. Light.prototype.getShadowGenerator = function () {
  21735. return this._shadowGenerator;
  21736. };
  21737. /**
  21738. * Returns a Vector3, the absolute light position in the World.
  21739. * @returns the world space position of the light
  21740. */
  21741. Light.prototype.getAbsolutePosition = function () {
  21742. return BABYLON.Vector3.Zero();
  21743. };
  21744. /**
  21745. * Specifies if the light will affect the passed mesh.
  21746. * @param mesh The mesh to test against the light
  21747. * @return true the mesh is affected otherwise, false.
  21748. */
  21749. Light.prototype.canAffectMesh = function (mesh) {
  21750. if (!mesh) {
  21751. return true;
  21752. }
  21753. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21754. return false;
  21755. }
  21756. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21757. return false;
  21758. }
  21759. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21760. return false;
  21761. }
  21762. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21763. return false;
  21764. }
  21765. return true;
  21766. };
  21767. /**
  21768. * Sort function to order lights for rendering.
  21769. * @param a First Light object to compare to second.
  21770. * @param b Second Light object to compare first.
  21771. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21772. */
  21773. Light.CompareLightsPriority = function (a, b) {
  21774. //shadow-casting lights have priority over non-shadow-casting lights
  21775. //the renderPrioirty is a secondary sort criterion
  21776. if (a.shadowEnabled !== b.shadowEnabled) {
  21777. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21778. }
  21779. return b.renderPriority - a.renderPriority;
  21780. };
  21781. /**
  21782. * Releases resources associated with this node.
  21783. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21784. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21785. */
  21786. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21787. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21788. if (this._shadowGenerator) {
  21789. this._shadowGenerator.dispose();
  21790. this._shadowGenerator = null;
  21791. }
  21792. // Animations
  21793. this.getScene().stopAnimation(this);
  21794. // Remove from meshes
  21795. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21796. var mesh = _a[_i];
  21797. mesh._removeLightSource(this);
  21798. }
  21799. this._uniformBuffer.dispose();
  21800. // Remove from scene
  21801. this.getScene().removeLight(this);
  21802. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21803. };
  21804. /**
  21805. * Returns the light type ID (integer).
  21806. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21807. */
  21808. Light.prototype.getTypeID = function () {
  21809. return 0;
  21810. };
  21811. /**
  21812. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21813. * @returns the scaled intensity in intensity mode unit
  21814. */
  21815. Light.prototype.getScaledIntensity = function () {
  21816. return this._photometricScale * this.intensity;
  21817. };
  21818. /**
  21819. * Returns a new Light object, named "name", from the current one.
  21820. * @param name The name of the cloned light
  21821. * @returns the new created light
  21822. */
  21823. Light.prototype.clone = function (name) {
  21824. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21825. if (!constructor) {
  21826. return null;
  21827. }
  21828. return BABYLON.SerializationHelper.Clone(constructor, this);
  21829. };
  21830. /**
  21831. * Serializes the current light into a Serialization object.
  21832. * @returns the serialized object.
  21833. */
  21834. Light.prototype.serialize = function () {
  21835. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21836. // Type
  21837. serializationObject.type = this.getTypeID();
  21838. // Parent
  21839. if (this.parent) {
  21840. serializationObject.parentId = this.parent.id;
  21841. }
  21842. // Inclusion / exclusions
  21843. if (this.excludedMeshes.length > 0) {
  21844. serializationObject.excludedMeshesIds = [];
  21845. this.excludedMeshes.forEach(function (mesh) {
  21846. serializationObject.excludedMeshesIds.push(mesh.id);
  21847. });
  21848. }
  21849. if (this.includedOnlyMeshes.length > 0) {
  21850. serializationObject.includedOnlyMeshesIds = [];
  21851. this.includedOnlyMeshes.forEach(function (mesh) {
  21852. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21853. });
  21854. }
  21855. // Animations
  21856. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21857. serializationObject.ranges = this.serializeAnimationRanges();
  21858. return serializationObject;
  21859. };
  21860. /**
  21861. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21862. * This new light is named "name" and added to the passed scene.
  21863. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21864. * @param name The friendly name of the light
  21865. * @param scene The scene the new light will belong to
  21866. * @returns the constructor function
  21867. */
  21868. Light.GetConstructorFromName = function (type, name, scene) {
  21869. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21870. if (constructorFunc) {
  21871. return constructorFunc;
  21872. }
  21873. // Default to no light for none present once.
  21874. return null;
  21875. };
  21876. /**
  21877. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21878. * @param parsedLight The JSON representation of the light
  21879. * @param scene The scene to create the parsed light in
  21880. * @returns the created light after parsing
  21881. */
  21882. Light.Parse = function (parsedLight, scene) {
  21883. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21884. if (!constructor) {
  21885. return null;
  21886. }
  21887. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21888. // Inclusion / exclusions
  21889. if (parsedLight.excludedMeshesIds) {
  21890. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21891. }
  21892. if (parsedLight.includedOnlyMeshesIds) {
  21893. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21894. }
  21895. // Parent
  21896. if (parsedLight.parentId) {
  21897. light._waitingParentId = parsedLight.parentId;
  21898. }
  21899. // Animations
  21900. if (parsedLight.animations) {
  21901. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21902. var parsedAnimation = parsedLight.animations[animationIndex];
  21903. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21904. }
  21905. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21906. }
  21907. if (parsedLight.autoAnimate) {
  21908. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21909. }
  21910. return light;
  21911. };
  21912. Light.prototype._hookArrayForExcluded = function (array) {
  21913. var _this = this;
  21914. var oldPush = array.push;
  21915. array.push = function () {
  21916. var items = [];
  21917. for (var _i = 0; _i < arguments.length; _i++) {
  21918. items[_i] = arguments[_i];
  21919. }
  21920. var result = oldPush.apply(array, items);
  21921. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21922. var item = items_1[_a];
  21923. item._resyncLighSource(_this);
  21924. }
  21925. return result;
  21926. };
  21927. var oldSplice = array.splice;
  21928. array.splice = function (index, deleteCount) {
  21929. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21930. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21931. var item = deleted_1[_i];
  21932. item._resyncLighSource(_this);
  21933. }
  21934. return deleted;
  21935. };
  21936. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21937. var item = array_1[_i];
  21938. item._resyncLighSource(this);
  21939. }
  21940. };
  21941. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21942. var _this = this;
  21943. var oldPush = array.push;
  21944. array.push = function () {
  21945. var items = [];
  21946. for (var _i = 0; _i < arguments.length; _i++) {
  21947. items[_i] = arguments[_i];
  21948. }
  21949. var result = oldPush.apply(array, items);
  21950. _this._resyncMeshes();
  21951. return result;
  21952. };
  21953. var oldSplice = array.splice;
  21954. array.splice = function (index, deleteCount) {
  21955. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21956. _this._resyncMeshes();
  21957. return deleted;
  21958. };
  21959. this._resyncMeshes();
  21960. };
  21961. Light.prototype._resyncMeshes = function () {
  21962. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21963. var mesh = _a[_i];
  21964. mesh._resyncLighSource(this);
  21965. }
  21966. };
  21967. /**
  21968. * Forces the meshes to update their light related information in their rendering used effects
  21969. * @hidden Internal Use Only
  21970. */
  21971. Light.prototype._markMeshesAsLightDirty = function () {
  21972. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21973. var mesh = _a[_i];
  21974. if (mesh._lightSources.indexOf(this) !== -1) {
  21975. mesh._markSubMeshesAsLightDirty();
  21976. }
  21977. }
  21978. };
  21979. /**
  21980. * Recomputes the cached photometric scale if needed.
  21981. */
  21982. Light.prototype._computePhotometricScale = function () {
  21983. this._photometricScale = this._getPhotometricScale();
  21984. this.getScene().resetCachedMaterial();
  21985. };
  21986. /**
  21987. * Returns the Photometric Scale according to the light type and intensity mode.
  21988. */
  21989. Light.prototype._getPhotometricScale = function () {
  21990. var photometricScale = 0.0;
  21991. var lightTypeID = this.getTypeID();
  21992. //get photometric mode
  21993. var photometricMode = this.intensityMode;
  21994. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21995. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21996. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21997. }
  21998. else {
  21999. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22000. }
  22001. }
  22002. //compute photometric scale
  22003. switch (lightTypeID) {
  22004. case Light.LIGHTTYPEID_POINTLIGHT:
  22005. case Light.LIGHTTYPEID_SPOTLIGHT:
  22006. switch (photometricMode) {
  22007. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22008. photometricScale = 1.0 / (4.0 * Math.PI);
  22009. break;
  22010. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22011. photometricScale = 1.0;
  22012. break;
  22013. case Light.INTENSITYMODE_LUMINANCE:
  22014. photometricScale = this.radius * this.radius;
  22015. break;
  22016. }
  22017. break;
  22018. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22019. switch (photometricMode) {
  22020. case Light.INTENSITYMODE_ILLUMINANCE:
  22021. photometricScale = 1.0;
  22022. break;
  22023. case Light.INTENSITYMODE_LUMINANCE:
  22024. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22025. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22026. var apexAngleRadians = this.radius;
  22027. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22028. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22029. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22030. photometricScale = solidAngle;
  22031. break;
  22032. }
  22033. break;
  22034. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22035. // No fall off in hemisperic light.
  22036. photometricScale = 1.0;
  22037. break;
  22038. }
  22039. return photometricScale;
  22040. };
  22041. /**
  22042. * Reorder the light in the scene according to their defined priority.
  22043. * @hidden Internal Use Only
  22044. */
  22045. Light.prototype._reorderLightsInScene = function () {
  22046. var scene = this.getScene();
  22047. if (this._renderPriority != 0) {
  22048. scene.requireLightSorting = true;
  22049. }
  22050. this.getScene().sortLightsByPriority();
  22051. };
  22052. /**
  22053. * Falloff Default: light is falling off following the material specification:
  22054. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22055. */
  22056. Light.FALLOFF_DEFAULT = 0;
  22057. /**
  22058. * Falloff Physical: light is falling off following the inverse squared distance law.
  22059. */
  22060. Light.FALLOFF_PHYSICAL = 1;
  22061. /**
  22062. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22063. * to enhance interoperability with other engines.
  22064. */
  22065. Light.FALLOFF_GLTF = 2;
  22066. /**
  22067. * Falloff Standard: light is falling off like in the standard material
  22068. * to enhance interoperability with other materials.
  22069. */
  22070. Light.FALLOFF_STANDARD = 3;
  22071. //lightmapMode Consts
  22072. /**
  22073. * If every light affecting the material is in this lightmapMode,
  22074. * material.lightmapTexture adds or multiplies
  22075. * (depends on material.useLightmapAsShadowmap)
  22076. * after every other light calculations.
  22077. */
  22078. Light.LIGHTMAP_DEFAULT = 0;
  22079. /**
  22080. * material.lightmapTexture as only diffuse lighting from this light
  22081. * adds only specular lighting from this light
  22082. * adds dynamic shadows
  22083. */
  22084. Light.LIGHTMAP_SPECULAR = 1;
  22085. /**
  22086. * material.lightmapTexture as only lighting
  22087. * no light calculation from this light
  22088. * only adds dynamic shadows from this light
  22089. */
  22090. Light.LIGHTMAP_SHADOWSONLY = 2;
  22091. // Intensity Mode Consts
  22092. /**
  22093. * Each light type uses the default quantity according to its type:
  22094. * point/spot lights use luminous intensity
  22095. * directional lights use illuminance
  22096. */
  22097. Light.INTENSITYMODE_AUTOMATIC = 0;
  22098. /**
  22099. * lumen (lm)
  22100. */
  22101. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22102. /**
  22103. * candela (lm/sr)
  22104. */
  22105. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22106. /**
  22107. * lux (lm/m^2)
  22108. */
  22109. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22110. /**
  22111. * nit (cd/m^2)
  22112. */
  22113. Light.INTENSITYMODE_LUMINANCE = 4;
  22114. // Light types ids const.
  22115. /**
  22116. * Light type const id of the point light.
  22117. */
  22118. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22119. /**
  22120. * Light type const id of the directional light.
  22121. */
  22122. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22123. /**
  22124. * Light type const id of the spot light.
  22125. */
  22126. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22127. /**
  22128. * Light type const id of the hemispheric light.
  22129. */
  22130. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22131. __decorate([
  22132. BABYLON.serializeAsColor3()
  22133. ], Light.prototype, "diffuse", void 0);
  22134. __decorate([
  22135. BABYLON.serializeAsColor3()
  22136. ], Light.prototype, "specular", void 0);
  22137. __decorate([
  22138. BABYLON.serialize()
  22139. ], Light.prototype, "falloffType", void 0);
  22140. __decorate([
  22141. BABYLON.serialize()
  22142. ], Light.prototype, "intensity", void 0);
  22143. __decorate([
  22144. BABYLON.serialize()
  22145. ], Light.prototype, "range", null);
  22146. __decorate([
  22147. BABYLON.serialize()
  22148. ], Light.prototype, "intensityMode", null);
  22149. __decorate([
  22150. BABYLON.serialize()
  22151. ], Light.prototype, "radius", null);
  22152. __decorate([
  22153. BABYLON.serialize()
  22154. ], Light.prototype, "_renderPriority", void 0);
  22155. __decorate([
  22156. BABYLON.expandToProperty("_reorderLightsInScene")
  22157. ], Light.prototype, "renderPriority", void 0);
  22158. __decorate([
  22159. BABYLON.serialize("shadowEnabled")
  22160. ], Light.prototype, "_shadowEnabled", void 0);
  22161. __decorate([
  22162. BABYLON.serialize("excludeWithLayerMask")
  22163. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22164. __decorate([
  22165. BABYLON.serialize("includeOnlyWithLayerMask")
  22166. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22167. __decorate([
  22168. BABYLON.serialize("lightmapMode")
  22169. ], Light.prototype, "_lightmapMode", void 0);
  22170. return Light;
  22171. }(BABYLON.Node));
  22172. BABYLON.Light = Light;
  22173. })(BABYLON || (BABYLON = {}));
  22174. //# sourceMappingURL=babylon.light.js.map
  22175. var BABYLON;
  22176. (function (BABYLON) {
  22177. var Camera = /** @class */ (function (_super) {
  22178. __extends(Camera, _super);
  22179. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22180. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22181. var _this = _super.call(this, name, scene) || this;
  22182. /**
  22183. * The vector the camera should consider as up.
  22184. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22185. */
  22186. _this.upVector = BABYLON.Vector3.Up();
  22187. _this.orthoLeft = null;
  22188. _this.orthoRight = null;
  22189. _this.orthoBottom = null;
  22190. _this.orthoTop = null;
  22191. /**
  22192. * FOV is set in Radians. (default is 0.8)
  22193. */
  22194. _this.fov = 0.8;
  22195. _this.minZ = 1;
  22196. _this.maxZ = 10000.0;
  22197. _this.inertia = 0.9;
  22198. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22199. _this.isIntermediate = false;
  22200. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22201. /**
  22202. * Restricts the camera to viewing objects with the same layerMask.
  22203. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22204. */
  22205. _this.layerMask = 0x0FFFFFFF;
  22206. /**
  22207. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22208. */
  22209. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22210. // Camera rig members
  22211. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22212. /** @hidden */
  22213. _this._rigCameras = new Array();
  22214. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22215. /** @hidden */
  22216. _this._skipRendering = false;
  22217. _this.customRenderTargets = new Array();
  22218. // Observables
  22219. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22220. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22221. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22222. _this.onRestoreStateObservable = new BABYLON.Observable();
  22223. // Cache
  22224. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22225. _this._projectionMatrix = new BABYLON.Matrix();
  22226. _this._doNotComputeProjectionMatrix = false;
  22227. _this._postProcesses = new Array();
  22228. _this._transformMatrix = BABYLON.Matrix.Zero();
  22229. _this._activeMeshes = new BABYLON.SmartArray(256);
  22230. _this._globalPosition = BABYLON.Vector3.Zero();
  22231. _this._refreshFrustumPlanes = true;
  22232. _this.getScene().addCamera(_this);
  22233. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22234. _this.getScene().activeCamera = _this;
  22235. }
  22236. _this.position = position;
  22237. return _this;
  22238. }
  22239. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22240. get: function () {
  22241. return Camera._PERSPECTIVE_CAMERA;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22247. get: function () {
  22248. return Camera._ORTHOGRAPHIC_CAMERA;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22254. /**
  22255. * This is the default FOV mode for perspective cameras.
  22256. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22257. *
  22258. */
  22259. get: function () {
  22260. return Camera._FOVMODE_VERTICAL_FIXED;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22266. /**
  22267. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22268. *
  22269. */
  22270. get: function () {
  22271. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22277. get: function () {
  22278. return Camera._RIG_MODE_NONE;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22284. get: function () {
  22285. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22291. get: function () {
  22292. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22298. get: function () {
  22299. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22305. get: function () {
  22306. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22312. get: function () {
  22313. return Camera._RIG_MODE_VR;
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22319. get: function () {
  22320. return Camera._RIG_MODE_WEBVR;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. /**
  22326. * Store current camera state (fov, position, etc..)
  22327. */
  22328. Camera.prototype.storeState = function () {
  22329. this._stateStored = true;
  22330. this._storedFov = this.fov;
  22331. return this;
  22332. };
  22333. /**
  22334. * Restores the camera state values if it has been stored. You must call storeState() first
  22335. */
  22336. Camera.prototype._restoreStateValues = function () {
  22337. if (!this._stateStored) {
  22338. return false;
  22339. }
  22340. this.fov = this._storedFov;
  22341. return true;
  22342. };
  22343. /**
  22344. * Restored camera state. You must call storeState() first
  22345. */
  22346. Camera.prototype.restoreState = function () {
  22347. if (this._restoreStateValues()) {
  22348. this.onRestoreStateObservable.notifyObservers(this);
  22349. return true;
  22350. }
  22351. return false;
  22352. };
  22353. Camera.prototype.getClassName = function () {
  22354. return "Camera";
  22355. };
  22356. /**
  22357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22358. */
  22359. Camera.prototype.toString = function (fullDetails) {
  22360. var ret = "Name: " + this.name;
  22361. ret += ", type: " + this.getClassName();
  22362. if (this.animations) {
  22363. for (var i = 0; i < this.animations.length; i++) {
  22364. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22365. }
  22366. }
  22367. if (fullDetails) {
  22368. }
  22369. return ret;
  22370. };
  22371. Object.defineProperty(Camera.prototype, "globalPosition", {
  22372. get: function () {
  22373. return this._globalPosition;
  22374. },
  22375. enumerable: true,
  22376. configurable: true
  22377. });
  22378. Camera.prototype.getActiveMeshes = function () {
  22379. return this._activeMeshes;
  22380. };
  22381. Camera.prototype.isActiveMesh = function (mesh) {
  22382. return (this._activeMeshes.indexOf(mesh) !== -1);
  22383. };
  22384. /**
  22385. * Is this camera ready to be used/rendered
  22386. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22387. * @return true if the camera is ready
  22388. */
  22389. Camera.prototype.isReady = function (completeCheck) {
  22390. if (completeCheck === void 0) { completeCheck = false; }
  22391. if (completeCheck) {
  22392. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22393. var pp = _a[_i];
  22394. if (pp && !pp.isReady()) {
  22395. return false;
  22396. }
  22397. }
  22398. }
  22399. return _super.prototype.isReady.call(this, completeCheck);
  22400. };
  22401. //Cache
  22402. /** @hidden */
  22403. Camera.prototype._initCache = function () {
  22404. _super.prototype._initCache.call(this);
  22405. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22406. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22407. this._cache.mode = undefined;
  22408. this._cache.minZ = undefined;
  22409. this._cache.maxZ = undefined;
  22410. this._cache.fov = undefined;
  22411. this._cache.fovMode = undefined;
  22412. this._cache.aspectRatio = undefined;
  22413. this._cache.orthoLeft = undefined;
  22414. this._cache.orthoRight = undefined;
  22415. this._cache.orthoBottom = undefined;
  22416. this._cache.orthoTop = undefined;
  22417. this._cache.renderWidth = undefined;
  22418. this._cache.renderHeight = undefined;
  22419. };
  22420. /** @hidden */
  22421. Camera.prototype._updateCache = function (ignoreParentClass) {
  22422. if (!ignoreParentClass) {
  22423. _super.prototype._updateCache.call(this);
  22424. }
  22425. this._cache.position.copyFrom(this.position);
  22426. this._cache.upVector.copyFrom(this.upVector);
  22427. };
  22428. // Synchronized
  22429. /** @hidden */
  22430. Camera.prototype._isSynchronized = function () {
  22431. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22432. };
  22433. /** @hidden */
  22434. Camera.prototype._isSynchronizedViewMatrix = function () {
  22435. if (!_super.prototype._isSynchronized.call(this))
  22436. return false;
  22437. return this._cache.position.equals(this.position)
  22438. && this._cache.upVector.equals(this.upVector)
  22439. && this.isSynchronizedWithParent();
  22440. };
  22441. /** @hidden */
  22442. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22443. var check = this._cache.mode === this.mode
  22444. && this._cache.minZ === this.minZ
  22445. && this._cache.maxZ === this.maxZ;
  22446. if (!check) {
  22447. return false;
  22448. }
  22449. var engine = this.getEngine();
  22450. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22451. check = this._cache.fov === this.fov
  22452. && this._cache.fovMode === this.fovMode
  22453. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22454. }
  22455. else {
  22456. check = this._cache.orthoLeft === this.orthoLeft
  22457. && this._cache.orthoRight === this.orthoRight
  22458. && this._cache.orthoBottom === this.orthoBottom
  22459. && this._cache.orthoTop === this.orthoTop
  22460. && this._cache.renderWidth === engine.getRenderWidth()
  22461. && this._cache.renderHeight === engine.getRenderHeight();
  22462. }
  22463. return check;
  22464. };
  22465. // Controls
  22466. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22467. };
  22468. Camera.prototype.detachControl = function (element) {
  22469. };
  22470. Camera.prototype.update = function () {
  22471. this._checkInputs();
  22472. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22473. this._updateRigCameras();
  22474. }
  22475. };
  22476. /** @hidden */
  22477. Camera.prototype._checkInputs = function () {
  22478. this.onAfterCheckInputsObservable.notifyObservers(this);
  22479. };
  22480. Object.defineProperty(Camera.prototype, "rigCameras", {
  22481. get: function () {
  22482. return this._rigCameras;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22488. get: function () {
  22489. return this._rigPostProcess;
  22490. },
  22491. enumerable: true,
  22492. configurable: true
  22493. });
  22494. /**
  22495. * Internal, gets the first post proces.
  22496. * @returns the first post process to be run on this camera.
  22497. */
  22498. Camera.prototype._getFirstPostProcess = function () {
  22499. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22500. if (this._postProcesses[ppIndex] !== null) {
  22501. return this._postProcesses[ppIndex];
  22502. }
  22503. }
  22504. return null;
  22505. };
  22506. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22507. // invalidate framebuffer
  22508. var firstPostProcess = this._getFirstPostProcess();
  22509. if (firstPostProcess) {
  22510. firstPostProcess.markTextureDirty();
  22511. }
  22512. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22513. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22514. var cam = this._rigCameras[i];
  22515. var rigPostProcess = cam._rigPostProcess;
  22516. // for VR rig, there does not have to be a post process
  22517. if (rigPostProcess) {
  22518. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22519. if (isPass) {
  22520. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22521. cam.isIntermediate = this._postProcesses.length === 0;
  22522. }
  22523. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22524. rigPostProcess.markTextureDirty();
  22525. }
  22526. else {
  22527. cam._postProcesses = this._postProcesses.slice(0);
  22528. }
  22529. }
  22530. };
  22531. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22532. if (insertAt === void 0) { insertAt = null; }
  22533. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22534. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22535. return 0;
  22536. }
  22537. if (insertAt == null || insertAt < 0) {
  22538. this._postProcesses.push(postProcess);
  22539. }
  22540. else if (this._postProcesses[insertAt] === null) {
  22541. this._postProcesses[insertAt] = postProcess;
  22542. }
  22543. else {
  22544. this._postProcesses.splice(insertAt, 0, postProcess);
  22545. }
  22546. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22547. return this._postProcesses.indexOf(postProcess);
  22548. };
  22549. Camera.prototype.detachPostProcess = function (postProcess) {
  22550. var idx = this._postProcesses.indexOf(postProcess);
  22551. if (idx !== -1) {
  22552. this._postProcesses[idx] = null;
  22553. }
  22554. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22555. };
  22556. Camera.prototype.getWorldMatrix = function () {
  22557. if (this._isSynchronizedViewMatrix()) {
  22558. return this._worldMatrix;
  22559. }
  22560. // Getting the the view matrix will also compute the world matrix.
  22561. this.getViewMatrix();
  22562. return this._worldMatrix;
  22563. };
  22564. /** @hidden */
  22565. Camera.prototype._getViewMatrix = function () {
  22566. return BABYLON.Matrix.Identity();
  22567. };
  22568. Camera.prototype.getViewMatrix = function (force) {
  22569. if (!force && this._isSynchronizedViewMatrix()) {
  22570. return this._computedViewMatrix;
  22571. }
  22572. this.updateCache();
  22573. this._computedViewMatrix = this._getViewMatrix();
  22574. this._currentRenderId = this.getScene().getRenderId();
  22575. this._childRenderId = this._currentRenderId;
  22576. this._refreshFrustumPlanes = true;
  22577. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22578. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22579. }
  22580. this.onViewMatrixChangedObservable.notifyObservers(this);
  22581. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22582. return this._computedViewMatrix;
  22583. };
  22584. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22585. this._doNotComputeProjectionMatrix = true;
  22586. if (projection !== undefined) {
  22587. this._projectionMatrix = projection;
  22588. }
  22589. };
  22590. ;
  22591. Camera.prototype.unfreezeProjectionMatrix = function () {
  22592. this._doNotComputeProjectionMatrix = false;
  22593. };
  22594. ;
  22595. Camera.prototype.getProjectionMatrix = function (force) {
  22596. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22597. return this._projectionMatrix;
  22598. }
  22599. // Cache
  22600. this._cache.mode = this.mode;
  22601. this._cache.minZ = this.minZ;
  22602. this._cache.maxZ = this.maxZ;
  22603. // Matrix
  22604. this._refreshFrustumPlanes = true;
  22605. var engine = this.getEngine();
  22606. var scene = this.getScene();
  22607. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22608. this._cache.fov = this.fov;
  22609. this._cache.fovMode = this.fovMode;
  22610. this._cache.aspectRatio = engine.getAspectRatio(this);
  22611. if (this.minZ <= 0) {
  22612. this.minZ = 0.1;
  22613. }
  22614. if (scene.useRightHandedSystem) {
  22615. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22616. }
  22617. else {
  22618. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22619. }
  22620. }
  22621. else {
  22622. var halfWidth = engine.getRenderWidth() / 2.0;
  22623. var halfHeight = engine.getRenderHeight() / 2.0;
  22624. if (scene.useRightHandedSystem) {
  22625. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22626. }
  22627. else {
  22628. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22629. }
  22630. this._cache.orthoLeft = this.orthoLeft;
  22631. this._cache.orthoRight = this.orthoRight;
  22632. this._cache.orthoBottom = this.orthoBottom;
  22633. this._cache.orthoTop = this.orthoTop;
  22634. this._cache.renderWidth = engine.getRenderWidth();
  22635. this._cache.renderHeight = engine.getRenderHeight();
  22636. }
  22637. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22638. return this._projectionMatrix;
  22639. };
  22640. /**
  22641. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22642. * @returns a Matrix
  22643. */
  22644. Camera.prototype.getTransformationMatrix = function () {
  22645. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22646. return this._transformMatrix;
  22647. };
  22648. Camera.prototype.updateFrustumPlanes = function () {
  22649. if (!this._refreshFrustumPlanes) {
  22650. return;
  22651. }
  22652. this.getTransformationMatrix();
  22653. if (!this._frustumPlanes) {
  22654. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22655. }
  22656. else {
  22657. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22658. }
  22659. this._refreshFrustumPlanes = false;
  22660. };
  22661. Camera.prototype.isInFrustum = function (target) {
  22662. this.updateFrustumPlanes();
  22663. return target.isInFrustum(this._frustumPlanes);
  22664. };
  22665. Camera.prototype.isCompletelyInFrustum = function (target) {
  22666. this.updateFrustumPlanes();
  22667. return target.isCompletelyInFrustum(this._frustumPlanes);
  22668. };
  22669. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22670. if (length === void 0) { length = 100; }
  22671. if (!transform) {
  22672. transform = this.getWorldMatrix();
  22673. }
  22674. if (!origin) {
  22675. origin = this.position;
  22676. }
  22677. var forward = new BABYLON.Vector3(0, 0, 1);
  22678. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22679. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22680. return new BABYLON.Ray(origin, direction, length);
  22681. };
  22682. /**
  22683. * Releases resources associated with this node.
  22684. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22685. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22686. */
  22687. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22688. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22689. // Observables
  22690. this.onViewMatrixChangedObservable.clear();
  22691. this.onProjectionMatrixChangedObservable.clear();
  22692. this.onAfterCheckInputsObservable.clear();
  22693. this.onRestoreStateObservable.clear();
  22694. // Inputs
  22695. if (this.inputs) {
  22696. this.inputs.clear();
  22697. }
  22698. // Animations
  22699. this.getScene().stopAnimation(this);
  22700. // Remove from scene
  22701. this.getScene().removeCamera(this);
  22702. while (this._rigCameras.length > 0) {
  22703. var camera = this._rigCameras.pop();
  22704. if (camera) {
  22705. camera.dispose();
  22706. }
  22707. }
  22708. // Postprocesses
  22709. if (this._rigPostProcess) {
  22710. this._rigPostProcess.dispose(this);
  22711. this._rigPostProcess = null;
  22712. this._postProcesses = [];
  22713. }
  22714. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22715. this._rigPostProcess = null;
  22716. this._postProcesses = [];
  22717. }
  22718. else {
  22719. var i = this._postProcesses.length;
  22720. while (--i >= 0) {
  22721. var postProcess = this._postProcesses[i];
  22722. if (postProcess) {
  22723. postProcess.dispose(this);
  22724. }
  22725. }
  22726. }
  22727. // Render targets
  22728. var i = this.customRenderTargets.length;
  22729. while (--i >= 0) {
  22730. this.customRenderTargets[i].dispose();
  22731. }
  22732. this.customRenderTargets = [];
  22733. // Active Meshes
  22734. this._activeMeshes.dispose();
  22735. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22736. };
  22737. Object.defineProperty(Camera.prototype, "leftCamera", {
  22738. // ---- Camera rigs section ----
  22739. get: function () {
  22740. if (this._rigCameras.length < 1) {
  22741. return null;
  22742. }
  22743. return this._rigCameras[0];
  22744. },
  22745. enumerable: true,
  22746. configurable: true
  22747. });
  22748. Object.defineProperty(Camera.prototype, "rightCamera", {
  22749. get: function () {
  22750. if (this._rigCameras.length < 2) {
  22751. return null;
  22752. }
  22753. return this._rigCameras[1];
  22754. },
  22755. enumerable: true,
  22756. configurable: true
  22757. });
  22758. Camera.prototype.getLeftTarget = function () {
  22759. if (this._rigCameras.length < 1) {
  22760. return null;
  22761. }
  22762. return this._rigCameras[0].getTarget();
  22763. };
  22764. Camera.prototype.getRightTarget = function () {
  22765. if (this._rigCameras.length < 2) {
  22766. return null;
  22767. }
  22768. return this._rigCameras[1].getTarget();
  22769. };
  22770. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22771. if (this.cameraRigMode === mode) {
  22772. return;
  22773. }
  22774. while (this._rigCameras.length > 0) {
  22775. var camera = this._rigCameras.pop();
  22776. if (camera) {
  22777. camera.dispose();
  22778. }
  22779. }
  22780. this.cameraRigMode = mode;
  22781. this._cameraRigParams = {};
  22782. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22783. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22784. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22785. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22786. // create the rig cameras, unless none
  22787. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22788. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22789. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22790. if (leftCamera && rightCamera) {
  22791. this._rigCameras.push(leftCamera);
  22792. this._rigCameras.push(rightCamera);
  22793. }
  22794. }
  22795. switch (this.cameraRigMode) {
  22796. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22797. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22798. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22799. break;
  22800. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22801. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22802. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22803. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22804. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22805. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22806. break;
  22807. case Camera.RIG_MODE_VR:
  22808. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22809. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22810. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22811. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22812. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22813. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22814. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22815. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22816. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22817. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22818. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22819. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22820. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22821. if (metrics.compensateDistortion) {
  22822. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22823. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22824. }
  22825. break;
  22826. case Camera.RIG_MODE_WEBVR:
  22827. if (rigParams.vrDisplay) {
  22828. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22829. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22830. //Left eye
  22831. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22832. this._rigCameras[0].setCameraRigParameter("left", true);
  22833. //leaving this for future reference
  22834. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22835. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22836. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22837. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22838. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22839. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22840. this._rigCameras[0].parent = this;
  22841. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22842. //Right eye
  22843. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22844. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22845. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22846. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22847. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22848. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22849. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22850. this._rigCameras[1].parent = this;
  22851. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22852. if (Camera.UseAlternateWebVRRendering) {
  22853. this._rigCameras[1]._skipRendering = true;
  22854. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22855. }
  22856. }
  22857. break;
  22858. }
  22859. this._cascadePostProcessesToRigCams();
  22860. this.update();
  22861. };
  22862. Camera.prototype._getVRProjectionMatrix = function () {
  22863. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22864. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22865. return this._projectionMatrix;
  22866. };
  22867. Camera.prototype._updateCameraRotationMatrix = function () {
  22868. //Here for WebVR
  22869. };
  22870. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22871. //Here for WebVR
  22872. };
  22873. /**
  22874. * This function MUST be overwritten by the different WebVR cameras available.
  22875. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22876. */
  22877. Camera.prototype._getWebVRProjectionMatrix = function () {
  22878. return BABYLON.Matrix.Identity();
  22879. };
  22880. /**
  22881. * This function MUST be overwritten by the different WebVR cameras available.
  22882. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22883. */
  22884. Camera.prototype._getWebVRViewMatrix = function () {
  22885. return BABYLON.Matrix.Identity();
  22886. };
  22887. Camera.prototype.setCameraRigParameter = function (name, value) {
  22888. if (!this._cameraRigParams) {
  22889. this._cameraRigParams = {};
  22890. }
  22891. this._cameraRigParams[name] = value;
  22892. //provisionnally:
  22893. if (name === "interaxialDistance") {
  22894. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22895. }
  22896. };
  22897. /**
  22898. * needs to be overridden by children so sub has required properties to be copied
  22899. */
  22900. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22901. return null;
  22902. };
  22903. /**
  22904. * May need to be overridden by children
  22905. * @hidden
  22906. */
  22907. Camera.prototype._updateRigCameras = function () {
  22908. for (var i = 0; i < this._rigCameras.length; i++) {
  22909. this._rigCameras[i].minZ = this.minZ;
  22910. this._rigCameras[i].maxZ = this.maxZ;
  22911. this._rigCameras[i].fov = this.fov;
  22912. }
  22913. // only update viewport when ANAGLYPH
  22914. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22915. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22916. }
  22917. };
  22918. /** @hidden */
  22919. Camera.prototype._setupInputs = function () {
  22920. };
  22921. Camera.prototype.serialize = function () {
  22922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22923. // Type
  22924. serializationObject.type = this.getClassName();
  22925. // Parent
  22926. if (this.parent) {
  22927. serializationObject.parentId = this.parent.id;
  22928. }
  22929. if (this.inputs) {
  22930. this.inputs.serialize(serializationObject);
  22931. }
  22932. // Animations
  22933. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22934. serializationObject.ranges = this.serializeAnimationRanges();
  22935. return serializationObject;
  22936. };
  22937. Camera.prototype.clone = function (name) {
  22938. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22939. };
  22940. Camera.prototype.getDirection = function (localAxis) {
  22941. var result = BABYLON.Vector3.Zero();
  22942. this.getDirectionToRef(localAxis, result);
  22943. return result;
  22944. };
  22945. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22946. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22947. };
  22948. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22949. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22950. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22951. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22952. interaxial_distance: interaxial_distance,
  22953. isStereoscopicSideBySide: isStereoscopicSideBySide
  22954. });
  22955. if (constructorFunc) {
  22956. return constructorFunc;
  22957. }
  22958. // Default to universal camera
  22959. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22960. };
  22961. Camera.prototype.computeWorldMatrix = function () {
  22962. return this.getWorldMatrix();
  22963. };
  22964. Camera.Parse = function (parsedCamera, scene) {
  22965. var type = parsedCamera.type;
  22966. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22967. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22968. // Parent
  22969. if (parsedCamera.parentId) {
  22970. camera._waitingParentId = parsedCamera.parentId;
  22971. }
  22972. //If camera has an input manager, let it parse inputs settings
  22973. if (camera.inputs) {
  22974. camera.inputs.parse(parsedCamera);
  22975. camera._setupInputs();
  22976. }
  22977. if (camera.setPosition) { // need to force position
  22978. camera.position.copyFromFloats(0, 0, 0);
  22979. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22980. }
  22981. // Target
  22982. if (parsedCamera.target) {
  22983. if (camera.setTarget) {
  22984. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22985. }
  22986. }
  22987. // Apply 3d rig, when found
  22988. if (parsedCamera.cameraRigMode) {
  22989. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22990. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22991. }
  22992. // Animations
  22993. if (parsedCamera.animations) {
  22994. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22995. var parsedAnimation = parsedCamera.animations[animationIndex];
  22996. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22997. }
  22998. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22999. }
  23000. if (parsedCamera.autoAnimate) {
  23001. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23002. }
  23003. return camera;
  23004. };
  23005. // Statics
  23006. Camera._PERSPECTIVE_CAMERA = 0;
  23007. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23008. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23009. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23010. Camera._RIG_MODE_NONE = 0;
  23011. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23012. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23013. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23014. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23015. Camera._RIG_MODE_VR = 20;
  23016. Camera._RIG_MODE_WEBVR = 21;
  23017. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23018. Camera.UseAlternateWebVRRendering = false;
  23019. __decorate([
  23020. BABYLON.serializeAsVector3()
  23021. ], Camera.prototype, "position", void 0);
  23022. __decorate([
  23023. BABYLON.serializeAsVector3()
  23024. ], Camera.prototype, "upVector", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "orthoLeft", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "orthoRight", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "orthoBottom", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "orthoTop", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "fov", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Camera.prototype, "minZ", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Camera.prototype, "maxZ", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Camera.prototype, "inertia", void 0);
  23049. __decorate([
  23050. BABYLON.serialize()
  23051. ], Camera.prototype, "mode", void 0);
  23052. __decorate([
  23053. BABYLON.serialize()
  23054. ], Camera.prototype, "layerMask", void 0);
  23055. __decorate([
  23056. BABYLON.serialize()
  23057. ], Camera.prototype, "fovMode", void 0);
  23058. __decorate([
  23059. BABYLON.serialize()
  23060. ], Camera.prototype, "cameraRigMode", void 0);
  23061. __decorate([
  23062. BABYLON.serialize()
  23063. ], Camera.prototype, "interaxialDistance", void 0);
  23064. __decorate([
  23065. BABYLON.serialize()
  23066. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23067. return Camera;
  23068. }(BABYLON.Node));
  23069. BABYLON.Camera = Camera;
  23070. })(BABYLON || (BABYLON = {}));
  23071. //# sourceMappingURL=babylon.camera.js.map
  23072. var BABYLON;
  23073. (function (BABYLON) {
  23074. var RenderingManager = /** @class */ (function () {
  23075. function RenderingManager(scene) {
  23076. /**
  23077. * @hidden
  23078. */
  23079. this._useSceneAutoClearSetup = false;
  23080. this._renderingGroups = new Array();
  23081. this._autoClearDepthStencil = {};
  23082. this._customOpaqueSortCompareFn = {};
  23083. this._customAlphaTestSortCompareFn = {};
  23084. this._customTransparentSortCompareFn = {};
  23085. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23086. this._scene = scene;
  23087. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23088. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23089. }
  23090. }
  23091. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23092. if (depth === void 0) { depth = true; }
  23093. if (stencil === void 0) { stencil = true; }
  23094. if (this._depthStencilBufferAlreadyCleaned) {
  23095. return;
  23096. }
  23097. this._scene.getEngine().clear(null, false, depth, stencil);
  23098. this._depthStencilBufferAlreadyCleaned = true;
  23099. };
  23100. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23101. // Update the observable context (not null as it only goes away on dispose)
  23102. var info = this._renderingGroupInfo;
  23103. info.scene = this._scene;
  23104. info.camera = this._scene.activeCamera;
  23105. // Dispatch sprites
  23106. if (this._scene.spriteManagers && renderSprites) {
  23107. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23108. var manager = this._scene.spriteManagers[index];
  23109. this.dispatchSprites(manager);
  23110. }
  23111. }
  23112. // Render
  23113. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23114. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23115. var renderingGroup = this._renderingGroups[index];
  23116. if (!renderingGroup)
  23117. continue;
  23118. var renderingGroupMask = Math.pow(2, index);
  23119. info.renderingGroupId = index;
  23120. // Before Observable
  23121. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23122. // Clear depth/stencil if needed
  23123. if (RenderingManager.AUTOCLEAR) {
  23124. var autoClear = this._useSceneAutoClearSetup ?
  23125. this._scene.getAutoClearDepthStencilSetup(index) :
  23126. this._autoClearDepthStencil[index];
  23127. if (autoClear && autoClear.autoClear) {
  23128. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23129. }
  23130. }
  23131. // Render
  23132. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23133. var step = _a[_i];
  23134. step.action(index);
  23135. }
  23136. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23137. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23138. var step = _c[_b];
  23139. step.action(index);
  23140. }
  23141. // After Observable
  23142. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23143. }
  23144. };
  23145. RenderingManager.prototype.reset = function () {
  23146. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23147. var renderingGroup = this._renderingGroups[index];
  23148. if (renderingGroup) {
  23149. renderingGroup.prepare();
  23150. }
  23151. }
  23152. };
  23153. RenderingManager.prototype.dispose = function () {
  23154. this.freeRenderingGroups();
  23155. this._renderingGroups.length = 0;
  23156. this._renderingGroupInfo = null;
  23157. };
  23158. /**
  23159. * Clear the info related to rendering groups preventing retention points during dispose.
  23160. */
  23161. RenderingManager.prototype.freeRenderingGroups = function () {
  23162. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23163. var renderingGroup = this._renderingGroups[index];
  23164. if (renderingGroup) {
  23165. renderingGroup.dispose();
  23166. }
  23167. }
  23168. };
  23169. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23170. if (this._renderingGroups[renderingGroupId] === undefined) {
  23171. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23172. }
  23173. };
  23174. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23175. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23176. this._prepareRenderingGroup(renderingGroupId);
  23177. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23178. };
  23179. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23180. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23181. this._prepareRenderingGroup(renderingGroupId);
  23182. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23183. };
  23184. /**
  23185. * @param subMesh The submesh to dispatch
  23186. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23187. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23188. */
  23189. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23190. if (mesh === undefined) {
  23191. mesh = subMesh.getMesh();
  23192. }
  23193. var renderingGroupId = mesh.renderingGroupId || 0;
  23194. this._prepareRenderingGroup(renderingGroupId);
  23195. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23196. };
  23197. /**
  23198. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23199. * This allowed control for front to back rendering or reversly depending of the special needs.
  23200. *
  23201. * @param renderingGroupId The rendering group id corresponding to its index
  23202. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23203. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23204. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23205. */
  23206. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23207. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23208. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23209. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23210. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23211. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23212. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23213. if (this._renderingGroups[renderingGroupId]) {
  23214. var group = this._renderingGroups[renderingGroupId];
  23215. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23216. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23217. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23218. }
  23219. };
  23220. /**
  23221. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23222. *
  23223. * @param renderingGroupId The rendering group id corresponding to its index
  23224. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23225. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23226. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23227. */
  23228. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23229. if (depth === void 0) { depth = true; }
  23230. if (stencil === void 0) { stencil = true; }
  23231. this._autoClearDepthStencil[renderingGroupId] = {
  23232. autoClear: autoClearDepthStencil,
  23233. depth: depth,
  23234. stencil: stencil
  23235. };
  23236. };
  23237. /**
  23238. * Gets the current auto clear configuration for one rendering group of the rendering
  23239. * manager.
  23240. * @param index the rendering group index to get the information for
  23241. * @returns The auto clear setup for the requested rendering group
  23242. */
  23243. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23244. return this._autoClearDepthStencil[index];
  23245. };
  23246. /**
  23247. * The max id used for rendering groups (not included)
  23248. */
  23249. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23250. /**
  23251. * The min id used for rendering groups (included)
  23252. */
  23253. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23254. /**
  23255. * Used to globally prevent autoclearing scenes.
  23256. */
  23257. RenderingManager.AUTOCLEAR = true;
  23258. return RenderingManager;
  23259. }());
  23260. BABYLON.RenderingManager = RenderingManager;
  23261. })(BABYLON || (BABYLON = {}));
  23262. //# sourceMappingURL=babylon.renderingManager.js.map
  23263. var BABYLON;
  23264. (function (BABYLON) {
  23265. var RenderingGroup = /** @class */ (function () {
  23266. /**
  23267. * Creates a new rendering group.
  23268. * @param index The rendering group index
  23269. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23270. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23271. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23272. */
  23273. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23274. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23275. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23276. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23277. this.index = index;
  23278. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23279. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23280. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23281. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23282. this._particleSystems = new BABYLON.SmartArray(256);
  23283. this._spriteManagers = new BABYLON.SmartArray(256);
  23284. this._edgesRenderers = new BABYLON.SmartArray(16);
  23285. this._scene = scene;
  23286. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23287. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23288. this.transparentSortCompareFn = transparentSortCompareFn;
  23289. }
  23290. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23291. /**
  23292. * Set the opaque sort comparison function.
  23293. * If null the sub meshes will be render in the order they were created
  23294. */
  23295. set: function (value) {
  23296. this._opaqueSortCompareFn = value;
  23297. if (value) {
  23298. this._renderOpaque = this.renderOpaqueSorted;
  23299. }
  23300. else {
  23301. this._renderOpaque = RenderingGroup.renderUnsorted;
  23302. }
  23303. },
  23304. enumerable: true,
  23305. configurable: true
  23306. });
  23307. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23308. /**
  23309. * Set the alpha test sort comparison function.
  23310. * If null the sub meshes will be render in the order they were created
  23311. */
  23312. set: function (value) {
  23313. this._alphaTestSortCompareFn = value;
  23314. if (value) {
  23315. this._renderAlphaTest = this.renderAlphaTestSorted;
  23316. }
  23317. else {
  23318. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23319. }
  23320. },
  23321. enumerable: true,
  23322. configurable: true
  23323. });
  23324. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23325. /**
  23326. * Set the transparent sort comparison function.
  23327. * If null the sub meshes will be render in the order they were created
  23328. */
  23329. set: function (value) {
  23330. if (value) {
  23331. this._transparentSortCompareFn = value;
  23332. }
  23333. else {
  23334. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23335. }
  23336. this._renderTransparent = this.renderTransparentSorted;
  23337. },
  23338. enumerable: true,
  23339. configurable: true
  23340. });
  23341. /**
  23342. * Render all the sub meshes contained in the group.
  23343. * @param customRenderFunction Used to override the default render behaviour of the group.
  23344. * @returns true if rendered some submeshes.
  23345. */
  23346. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23347. if (customRenderFunction) {
  23348. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23349. return;
  23350. }
  23351. var engine = this._scene.getEngine();
  23352. // Depth only
  23353. if (this._depthOnlySubMeshes.length !== 0) {
  23354. engine.setColorWrite(false);
  23355. this._renderAlphaTest(this._depthOnlySubMeshes);
  23356. engine.setColorWrite(true);
  23357. }
  23358. // Opaque
  23359. if (this._opaqueSubMeshes.length !== 0) {
  23360. this._renderOpaque(this._opaqueSubMeshes);
  23361. }
  23362. // Alpha test
  23363. if (this._alphaTestSubMeshes.length !== 0) {
  23364. this._renderAlphaTest(this._alphaTestSubMeshes);
  23365. }
  23366. var stencilState = engine.getStencilBuffer();
  23367. engine.setStencilBuffer(false);
  23368. // Sprites
  23369. if (renderSprites) {
  23370. this._renderSprites();
  23371. }
  23372. // Particles
  23373. if (renderParticles) {
  23374. this._renderParticles(activeMeshes);
  23375. }
  23376. if (this.onBeforeTransparentRendering) {
  23377. this.onBeforeTransparentRendering();
  23378. }
  23379. // Transparent
  23380. if (this._transparentSubMeshes.length !== 0) {
  23381. this._renderTransparent(this._transparentSubMeshes);
  23382. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23383. }
  23384. // Set back stencil to false in case it changes before the edge renderer.
  23385. engine.setStencilBuffer(false);
  23386. // Edges
  23387. if (this._edgesRenderers.length) {
  23388. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23389. this._edgesRenderers.data[edgesRendererIndex].render();
  23390. }
  23391. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23392. }
  23393. // Restore Stencil state.
  23394. engine.setStencilBuffer(stencilState);
  23395. };
  23396. /**
  23397. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23398. * @param subMeshes The submeshes to render
  23399. */
  23400. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23401. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23402. };
  23403. /**
  23404. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23405. * @param subMeshes The submeshes to render
  23406. */
  23407. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23408. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23409. };
  23410. /**
  23411. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23412. * @param subMeshes The submeshes to render
  23413. */
  23414. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23415. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23416. };
  23417. /**
  23418. * Renders the submeshes in a specified order.
  23419. * @param subMeshes The submeshes to sort before render
  23420. * @param sortCompareFn The comparison function use to sort
  23421. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23422. * @param transparent Specifies to activate blending if true
  23423. */
  23424. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23425. var subIndex = 0;
  23426. var subMesh;
  23427. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23428. for (; subIndex < subMeshes.length; subIndex++) {
  23429. subMesh = subMeshes.data[subIndex];
  23430. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23431. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23432. }
  23433. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23434. if (sortCompareFn) {
  23435. sortedArray.sort(sortCompareFn);
  23436. }
  23437. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23438. subMesh = sortedArray[subIndex];
  23439. if (transparent) {
  23440. var material = subMesh.getMaterial();
  23441. if (material && material.needDepthPrePass) {
  23442. var engine = material.getScene().getEngine();
  23443. engine.setColorWrite(false);
  23444. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23445. subMesh.render(false);
  23446. engine.setColorWrite(true);
  23447. }
  23448. }
  23449. subMesh.render(transparent);
  23450. }
  23451. };
  23452. /**
  23453. * Renders the submeshes in the order they were dispatched (no sort applied).
  23454. * @param subMeshes The submeshes to render
  23455. */
  23456. RenderingGroup.renderUnsorted = function (subMeshes) {
  23457. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23458. var submesh = subMeshes.data[subIndex];
  23459. submesh.render(false);
  23460. }
  23461. };
  23462. /**
  23463. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23464. * are rendered back to front if in the same alpha index.
  23465. *
  23466. * @param a The first submesh
  23467. * @param b The second submesh
  23468. * @returns The result of the comparison
  23469. */
  23470. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23471. // Alpha index first
  23472. if (a._alphaIndex > b._alphaIndex) {
  23473. return 1;
  23474. }
  23475. if (a._alphaIndex < b._alphaIndex) {
  23476. return -1;
  23477. }
  23478. // Then distance to camera
  23479. return RenderingGroup.backToFrontSortCompare(a, b);
  23480. };
  23481. /**
  23482. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23483. * are rendered back to front.
  23484. *
  23485. * @param a The first submesh
  23486. * @param b The second submesh
  23487. * @returns The result of the comparison
  23488. */
  23489. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23490. // Then distance to camera
  23491. if (a._distanceToCamera < b._distanceToCamera) {
  23492. return 1;
  23493. }
  23494. if (a._distanceToCamera > b._distanceToCamera) {
  23495. return -1;
  23496. }
  23497. return 0;
  23498. };
  23499. /**
  23500. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23501. * are rendered front to back (prevent overdraw).
  23502. *
  23503. * @param a The first submesh
  23504. * @param b The second submesh
  23505. * @returns The result of the comparison
  23506. */
  23507. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23508. // Then distance to camera
  23509. if (a._distanceToCamera < b._distanceToCamera) {
  23510. return -1;
  23511. }
  23512. if (a._distanceToCamera > b._distanceToCamera) {
  23513. return 1;
  23514. }
  23515. return 0;
  23516. };
  23517. /**
  23518. * Resets the different lists of submeshes to prepare a new frame.
  23519. */
  23520. RenderingGroup.prototype.prepare = function () {
  23521. this._opaqueSubMeshes.reset();
  23522. this._transparentSubMeshes.reset();
  23523. this._alphaTestSubMeshes.reset();
  23524. this._depthOnlySubMeshes.reset();
  23525. this._particleSystems.reset();
  23526. this._spriteManagers.reset();
  23527. this._edgesRenderers.reset();
  23528. };
  23529. RenderingGroup.prototype.dispose = function () {
  23530. this._opaqueSubMeshes.dispose();
  23531. this._transparentSubMeshes.dispose();
  23532. this._alphaTestSubMeshes.dispose();
  23533. this._depthOnlySubMeshes.dispose();
  23534. this._particleSystems.dispose();
  23535. this._spriteManagers.dispose();
  23536. this._edgesRenderers.dispose();
  23537. };
  23538. /**
  23539. * Inserts the submesh in its correct queue depending on its material.
  23540. * @param subMesh The submesh to dispatch
  23541. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23542. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23543. */
  23544. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23545. // Get mesh and materials if not provided
  23546. if (mesh === undefined) {
  23547. mesh = subMesh.getMesh();
  23548. }
  23549. if (material === undefined) {
  23550. material = subMesh.getMaterial();
  23551. }
  23552. if (material === null || material === undefined) {
  23553. return;
  23554. }
  23555. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23556. this._transparentSubMeshes.push(subMesh);
  23557. }
  23558. else if (material.needAlphaTesting()) { // Alpha test
  23559. if (material.needDepthPrePass) {
  23560. this._depthOnlySubMeshes.push(subMesh);
  23561. }
  23562. this._alphaTestSubMeshes.push(subMesh);
  23563. }
  23564. else {
  23565. if (material.needDepthPrePass) {
  23566. this._depthOnlySubMeshes.push(subMesh);
  23567. }
  23568. this._opaqueSubMeshes.push(subMesh); // Opaque
  23569. }
  23570. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23571. this._edgesRenderers.push(mesh._edgesRenderer);
  23572. }
  23573. };
  23574. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23575. this._spriteManagers.push(spriteManager);
  23576. };
  23577. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23578. this._particleSystems.push(particleSystem);
  23579. };
  23580. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23581. if (this._particleSystems.length === 0) {
  23582. return;
  23583. }
  23584. // Particles
  23585. var activeCamera = this._scene.activeCamera;
  23586. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23587. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23588. var particleSystem = this._particleSystems.data[particleIndex];
  23589. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23590. continue;
  23591. }
  23592. var emitter = particleSystem.emitter;
  23593. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23594. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23595. }
  23596. }
  23597. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23598. };
  23599. RenderingGroup.prototype._renderSprites = function () {
  23600. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23601. return;
  23602. }
  23603. // Sprites
  23604. var activeCamera = this._scene.activeCamera;
  23605. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23606. for (var id = 0; id < this._spriteManagers.length; id++) {
  23607. var spriteManager = this._spriteManagers.data[id];
  23608. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23609. spriteManager.render();
  23610. }
  23611. }
  23612. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23613. };
  23614. return RenderingGroup;
  23615. }());
  23616. BABYLON.RenderingGroup = RenderingGroup;
  23617. })(BABYLON || (BABYLON = {}));
  23618. //# sourceMappingURL=babylon.renderingGroup.js.map
  23619. var BABYLON;
  23620. (function (BABYLON) {
  23621. /**
  23622. * Groups all the scene component constants in one place to ease maintenance.
  23623. * @hidden
  23624. */
  23625. var SceneComponentConstants = /** @class */ (function () {
  23626. function SceneComponentConstants() {
  23627. }
  23628. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23629. SceneComponentConstants.NAME_LAYER = "Layer";
  23630. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23631. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23632. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23633. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23634. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23635. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23636. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23637. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23638. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23639. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23640. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23641. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23642. SceneComponentConstants.NAME_OCTREE = "Octree";
  23643. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23644. SceneComponentConstants.NAME_AUDIO = "Audio";
  23645. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23646. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23647. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23648. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23649. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23650. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23651. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23652. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23653. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23654. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23655. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23656. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23657. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23658. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23659. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23660. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23661. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23662. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23663. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23664. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23665. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23666. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23667. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23668. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23669. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23670. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23671. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23672. return SceneComponentConstants;
  23673. }());
  23674. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23675. /**
  23676. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23677. * @hidden
  23678. */
  23679. var Stage = /** @class */ (function (_super) {
  23680. __extends(Stage, _super);
  23681. /**
  23682. * Hide ctor from the rest of the world.
  23683. * @param items The items to add.
  23684. */
  23685. function Stage(items) {
  23686. return _super.apply(this, items) || this;
  23687. }
  23688. /**
  23689. * Creates a new Stage.
  23690. * @returns A new instance of a Stage
  23691. */
  23692. Stage.Create = function () {
  23693. return Object.create(Stage.prototype);
  23694. };
  23695. /**
  23696. * Registers a step in an ordered way in the targeted stage.
  23697. * @param index Defines the position to register the step in
  23698. * @param component Defines the component attached to the step
  23699. * @param action Defines the action to launch during the step
  23700. */
  23701. Stage.prototype.registerStep = function (index, component, action) {
  23702. var i = 0;
  23703. var maxIndex = Number.MAX_VALUE;
  23704. for (; i < this.length && i < maxIndex; i++) {
  23705. var step = this[i];
  23706. maxIndex = step.index;
  23707. }
  23708. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23709. };
  23710. /**
  23711. * Clears all the steps from the stage.
  23712. */
  23713. Stage.prototype.clear = function () {
  23714. this.length = 0;
  23715. };
  23716. return Stage;
  23717. }(Array));
  23718. BABYLON.Stage = Stage;
  23719. })(BABYLON || (BABYLON = {}));
  23720. //# sourceMappingURL=babylon.sceneComponent.js.map
  23721. var BABYLON;
  23722. (function (BABYLON) {
  23723. /**
  23724. * Base class of the scene acting as a container for the different elements composing a scene.
  23725. * This class is dynamically extended by the different components of the scene increasing
  23726. * flexibility and reducing coupling
  23727. */
  23728. var AbstractScene = /** @class */ (function () {
  23729. function AbstractScene() {
  23730. /**
  23731. * Gets the list of root nodes (ie. nodes with no parent)
  23732. */
  23733. this.rootNodes = new Array();
  23734. /** All of the cameras added to this scene
  23735. * @see http://doc.babylonjs.com/babylon101/cameras
  23736. */
  23737. this.cameras = new Array();
  23738. /**
  23739. * All of the lights added to this scene
  23740. * @see http://doc.babylonjs.com/babylon101/lights
  23741. */
  23742. this.lights = new Array();
  23743. /**
  23744. * All of the (abstract) meshes added to this scene
  23745. */
  23746. this.meshes = new Array();
  23747. /**
  23748. * The list of skeletons added to the scene
  23749. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23750. */
  23751. this.skeletons = new Array();
  23752. /**
  23753. * All of the particle systems added to this scene
  23754. * @see http://doc.babylonjs.com/babylon101/particles
  23755. */
  23756. this.particleSystems = new Array();
  23757. /**
  23758. * Gets a list of Animations associated with the scene
  23759. */
  23760. this.animations = [];
  23761. /**
  23762. * All of the animation groups added to this scene
  23763. * @see http://doc.babylonjs.com/how_to/group
  23764. */
  23765. this.animationGroups = new Array();
  23766. /**
  23767. * All of the multi-materials added to this scene
  23768. * @see http://doc.babylonjs.com/how_to/multi_materials
  23769. */
  23770. this.multiMaterials = new Array();
  23771. /**
  23772. * All of the materials added to this scene
  23773. * @see http://doc.babylonjs.com/babylon101/materials
  23774. */
  23775. this.materials = new Array();
  23776. /**
  23777. * The list of morph target managers added to the scene
  23778. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23779. */
  23780. this.morphTargetManagers = new Array();
  23781. /**
  23782. * The list of geometries used in the scene.
  23783. */
  23784. this.geometries = new Array();
  23785. /**
  23786. * All of the tranform nodes added to this scene
  23787. * @see http://doc.babylonjs.com/how_to/transformnode
  23788. */
  23789. this.transformNodes = new Array();
  23790. /**
  23791. * ActionManagers available on the scene.
  23792. */
  23793. this.actionManagers = new Array();
  23794. /**
  23795. * Textures to keep.
  23796. */
  23797. this.textures = new Array();
  23798. }
  23799. /**
  23800. * Adds a parser in the list of available ones
  23801. * @param name Defines the name of the parser
  23802. * @param parser Defines the parser to add
  23803. */
  23804. AbstractScene.AddParser = function (name, parser) {
  23805. this._BabylonFileParsers[name] = parser;
  23806. };
  23807. /**
  23808. * Gets a general parser from the list of avaialble ones
  23809. * @param name Defines the name of the parser
  23810. * @returns the requested parser or null
  23811. */
  23812. AbstractScene.GetParser = function (name) {
  23813. if (this._BabylonFileParsers[name]) {
  23814. return this._BabylonFileParsers[name];
  23815. }
  23816. return null;
  23817. };
  23818. /**
  23819. * Adds n individual parser in the list of available ones
  23820. * @param name Defines the name of the parser
  23821. * @param parser Defines the parser to add
  23822. */
  23823. AbstractScene.AddIndividualParser = function (name, parser) {
  23824. this._IndividualBabylonFileParsers[name] = parser;
  23825. };
  23826. /**
  23827. * Gets an individual parser from the list of avaialble ones
  23828. * @param name Defines the name of the parser
  23829. * @returns the requested parser or null
  23830. */
  23831. AbstractScene.GetIndividualParser = function (name) {
  23832. if (this._IndividualBabylonFileParsers[name]) {
  23833. return this._IndividualBabylonFileParsers[name];
  23834. }
  23835. return null;
  23836. };
  23837. /**
  23838. * Parser json data and populate both a scene and its associated container object
  23839. * @param jsonData Defines the data to parse
  23840. * @param scene Defines the scene to parse the data for
  23841. * @param container Defines the container attached to the parsing sequence
  23842. * @param rootUrl Defines the root url of the data
  23843. */
  23844. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23845. for (var parserName in this._BabylonFileParsers) {
  23846. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23847. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23848. }
  23849. }
  23850. };
  23851. /**
  23852. * Stores the list of available parsers in the application.
  23853. */
  23854. AbstractScene._BabylonFileParsers = {};
  23855. /**
  23856. * Stores the list of available individual parsers in the application.
  23857. */
  23858. AbstractScene._IndividualBabylonFileParsers = {};
  23859. return AbstractScene;
  23860. }());
  23861. BABYLON.AbstractScene = AbstractScene;
  23862. })(BABYLON || (BABYLON = {}));
  23863. //# sourceMappingURL=babylon.abstractScene.js.map
  23864. var BABYLON;
  23865. (function (BABYLON) {
  23866. /** @hidden */
  23867. var ClickInfo = /** @class */ (function () {
  23868. function ClickInfo() {
  23869. this._singleClick = false;
  23870. this._doubleClick = false;
  23871. this._hasSwiped = false;
  23872. this._ignore = false;
  23873. }
  23874. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23875. get: function () {
  23876. return this._singleClick;
  23877. },
  23878. set: function (b) {
  23879. this._singleClick = b;
  23880. },
  23881. enumerable: true,
  23882. configurable: true
  23883. });
  23884. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23885. get: function () {
  23886. return this._doubleClick;
  23887. },
  23888. set: function (b) {
  23889. this._doubleClick = b;
  23890. },
  23891. enumerable: true,
  23892. configurable: true
  23893. });
  23894. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23895. get: function () {
  23896. return this._hasSwiped;
  23897. },
  23898. set: function (b) {
  23899. this._hasSwiped = b;
  23900. },
  23901. enumerable: true,
  23902. configurable: true
  23903. });
  23904. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23905. get: function () {
  23906. return this._ignore;
  23907. },
  23908. set: function (b) {
  23909. this._ignore = b;
  23910. },
  23911. enumerable: true,
  23912. configurable: true
  23913. });
  23914. return ClickInfo;
  23915. }());
  23916. /**
  23917. * This class is used by the onRenderingGroupObservable
  23918. */
  23919. var RenderingGroupInfo = /** @class */ (function () {
  23920. function RenderingGroupInfo() {
  23921. }
  23922. return RenderingGroupInfo;
  23923. }());
  23924. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23925. /**
  23926. * Represents a scene to be rendered by the engine.
  23927. * @see http://doc.babylonjs.com/features/scene
  23928. */
  23929. var Scene = /** @class */ (function (_super) {
  23930. __extends(Scene, _super);
  23931. /**
  23932. * Creates a new Scene
  23933. * @param engine defines the engine to use to render this scene
  23934. */
  23935. function Scene(engine) {
  23936. var _this = _super.call(this) || this;
  23937. // Members
  23938. /**
  23939. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23940. */
  23941. _this.autoClear = true;
  23942. /**
  23943. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23944. */
  23945. _this.autoClearDepthAndStencil = true;
  23946. /**
  23947. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23948. */
  23949. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23950. /**
  23951. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23952. */
  23953. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23954. _this._forceWireframe = false;
  23955. _this._forcePointsCloud = false;
  23956. /**
  23957. * Gets or sets a boolean indicating if animations are enabled
  23958. */
  23959. _this.animationsEnabled = true;
  23960. _this._animationPropertiesOverride = null;
  23961. /**
  23962. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23963. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23964. */
  23965. _this.useConstantAnimationDeltaTime = false;
  23966. /**
  23967. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23968. * Please note that it requires to run a ray cast through the scene on every frame
  23969. */
  23970. _this.constantlyUpdateMeshUnderPointer = false;
  23971. /**
  23972. * Defines the HTML cursor to use when hovering over interactive elements
  23973. */
  23974. _this.hoverCursor = "pointer";
  23975. /**
  23976. * Defines the HTML default cursor to use (empty by default)
  23977. */
  23978. _this.defaultCursor = "";
  23979. /**
  23980. * This is used to call preventDefault() on pointer down
  23981. * in order to block unwanted artifacts like system double clicks
  23982. */
  23983. _this.preventDefaultOnPointerDown = true;
  23984. // Metadata
  23985. /**
  23986. * Gets or sets user defined metadata
  23987. */
  23988. _this.metadata = null;
  23989. /**
  23990. * Use this array to add regular expressions used to disable offline support for specific urls
  23991. */
  23992. _this.disableOfflineSupportExceptionRules = new Array();
  23993. /**
  23994. * An event triggered when the scene is disposed.
  23995. */
  23996. _this.onDisposeObservable = new BABYLON.Observable();
  23997. _this._onDisposeObserver = null;
  23998. /**
  23999. * An event triggered before rendering the scene (right after animations and physics)
  24000. */
  24001. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24002. _this._onBeforeRenderObserver = null;
  24003. /**
  24004. * An event triggered after rendering the scene
  24005. */
  24006. _this.onAfterRenderObservable = new BABYLON.Observable();
  24007. _this._onAfterRenderObserver = null;
  24008. /**
  24009. * An event triggered before animating the scene
  24010. */
  24011. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24012. /**
  24013. * An event triggered after animations processing
  24014. */
  24015. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24016. /**
  24017. * An event triggered before draw calls are ready to be sent
  24018. */
  24019. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24020. /**
  24021. * An event triggered after draw calls have been sent
  24022. */
  24023. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24024. /**
  24025. * An event triggered when the scene is ready
  24026. */
  24027. _this.onReadyObservable = new BABYLON.Observable();
  24028. /**
  24029. * An event triggered before rendering a camera
  24030. */
  24031. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24032. _this._onBeforeCameraRenderObserver = null;
  24033. /**
  24034. * An event triggered after rendering a camera
  24035. */
  24036. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24037. _this._onAfterCameraRenderObserver = null;
  24038. /**
  24039. * An event triggered when active meshes evaluation is about to start
  24040. */
  24041. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24042. /**
  24043. * An event triggered when active meshes evaluation is done
  24044. */
  24045. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when particles rendering is about to start
  24048. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24049. */
  24050. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24051. /**
  24052. * An event triggered when particles rendering is done
  24053. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24054. */
  24055. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24056. /**
  24057. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24058. */
  24059. _this.onDataLoadedObservable = new BABYLON.Observable();
  24060. /**
  24061. * An event triggered when a camera is created
  24062. */
  24063. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24064. /**
  24065. * An event triggered when a camera is removed
  24066. */
  24067. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered when a light is created
  24070. */
  24071. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24072. /**
  24073. * An event triggered when a light is removed
  24074. */
  24075. _this.onLightRemovedObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered when a geometry is created
  24078. */
  24079. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24080. /**
  24081. * An event triggered when a geometry is removed
  24082. */
  24083. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24084. /**
  24085. * An event triggered when a transform node is created
  24086. */
  24087. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24088. /**
  24089. * An event triggered when a transform node is removed
  24090. */
  24091. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered when a mesh is created
  24094. */
  24095. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered when a mesh is removed
  24098. */
  24099. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered when render targets are about to be rendered
  24102. * Can happen multiple times per frame.
  24103. */
  24104. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24105. /**
  24106. * An event triggered when render targets were rendered.
  24107. * Can happen multiple times per frame.
  24108. */
  24109. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24110. /**
  24111. * An event triggered before calculating deterministic simulation step
  24112. */
  24113. _this.onBeforeStepObservable = new BABYLON.Observable();
  24114. /**
  24115. * An event triggered after calculating deterministic simulation step
  24116. */
  24117. _this.onAfterStepObservable = new BABYLON.Observable();
  24118. /**
  24119. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24120. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24121. * 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)
  24122. */
  24123. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24124. /**
  24125. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24126. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24127. * 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)
  24128. */
  24129. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24130. /**
  24131. * This Observable will when a mesh has been imported into the scene.
  24132. */
  24133. _this.onMeshImportedObservable = new BABYLON.Observable();
  24134. // Animations
  24135. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24136. /**
  24137. * 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).
  24138. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24139. */
  24140. _this.onPrePointerObservable = new BABYLON.Observable();
  24141. /**
  24142. * Observable event triggered each time an input event is received from the rendering canvas
  24143. */
  24144. _this.onPointerObservable = new BABYLON.Observable();
  24145. _this._meshPickProceed = false;
  24146. _this._currentPickResult = null;
  24147. _this._previousPickResult = null;
  24148. _this._totalPointersPressed = 0;
  24149. _this._doubleClickOccured = false;
  24150. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24151. _this.cameraToUseForPointers = null;
  24152. _this._pointerX = 0;
  24153. _this._pointerY = 0;
  24154. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24155. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24156. _this._startingPointerTime = 0;
  24157. _this._previousStartingPointerTime = 0;
  24158. _this._pointerCaptures = {};
  24159. // Deterministic lockstep
  24160. _this._timeAccumulator = 0;
  24161. _this._currentStepId = 0;
  24162. _this._currentInternalStep = 0;
  24163. // Keyboard
  24164. /**
  24165. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24166. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24167. */
  24168. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24169. /**
  24170. * Observable event triggered each time an keyboard event is received from the hosting window
  24171. */
  24172. _this.onKeyboardObservable = new BABYLON.Observable();
  24173. // Coordinates system
  24174. _this._useRightHandedSystem = false;
  24175. // Fog
  24176. _this._fogEnabled = true;
  24177. _this._fogMode = Scene.FOGMODE_NONE;
  24178. /**
  24179. * Gets or sets the fog color to use
  24180. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24181. */
  24182. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24183. /**
  24184. * Gets or sets the fog density to use
  24185. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24186. */
  24187. _this.fogDensity = 0.1;
  24188. /**
  24189. * Gets or sets the fog start distance to use
  24190. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24191. */
  24192. _this.fogStart = 0;
  24193. /**
  24194. * Gets or sets the fog end distance to use
  24195. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24196. */
  24197. _this.fogEnd = 1000.0;
  24198. // Lights
  24199. _this._shadowsEnabled = true;
  24200. _this._lightsEnabled = true;
  24201. /** All of the active cameras added to this scene. */
  24202. _this.activeCameras = new Array();
  24203. // Textures
  24204. _this._texturesEnabled = true;
  24205. // Particles
  24206. /**
  24207. * Gets or sets a boolean indicating if particles are enabled on this scene
  24208. */
  24209. _this.particlesEnabled = true;
  24210. // Sprites
  24211. /**
  24212. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24213. */
  24214. _this.spritesEnabled = true;
  24215. // Skeletons
  24216. _this._skeletonsEnabled = true;
  24217. // Lens flares
  24218. /**
  24219. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24220. */
  24221. _this.lensFlaresEnabled = true;
  24222. // Collisions
  24223. /**
  24224. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24225. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24226. */
  24227. _this.collisionsEnabled = true;
  24228. /**
  24229. * Defines the gravity applied to this scene (used only for collisions)
  24230. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24231. */
  24232. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24233. // Postprocesses
  24234. /**
  24235. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24236. */
  24237. _this.postProcessesEnabled = true;
  24238. /**
  24239. * The list of postprocesses added to the scene
  24240. */
  24241. _this.postProcesses = new Array();
  24242. // Customs render targets
  24243. /**
  24244. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24245. */
  24246. _this.renderTargetsEnabled = true;
  24247. /**
  24248. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24249. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24250. */
  24251. _this.dumpNextRenderTargets = false;
  24252. /**
  24253. * The list of user defined render targets added to the scene
  24254. */
  24255. _this.customRenderTargets = new Array();
  24256. /**
  24257. * Gets the list of meshes imported to the scene through SceneLoader
  24258. */
  24259. _this.importedMeshesFiles = new Array();
  24260. // Probes
  24261. /**
  24262. * Gets or sets a boolean indicating if probes are enabled on this scene
  24263. */
  24264. _this.probesEnabled = true;
  24265. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24266. // Procedural textures
  24267. /**
  24268. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24269. */
  24270. _this.proceduralTexturesEnabled = true;
  24271. // Performance counters
  24272. _this._totalVertices = new BABYLON.PerfCounter();
  24273. /** @hidden */
  24274. _this._activeIndices = new BABYLON.PerfCounter();
  24275. /** @hidden */
  24276. _this._activeParticles = new BABYLON.PerfCounter();
  24277. /** @hidden */
  24278. _this._activeBones = new BABYLON.PerfCounter();
  24279. _this._animationTime = 0;
  24280. /**
  24281. * Gets or sets a general scale for animation speed
  24282. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24283. */
  24284. _this.animationTimeScale = 1;
  24285. _this._renderId = 0;
  24286. _this._frameId = 0;
  24287. _this._executeWhenReadyTimeoutId = -1;
  24288. _this._intermediateRendering = false;
  24289. _this._viewUpdateFlag = -1;
  24290. _this._projectionUpdateFlag = -1;
  24291. _this._alternateViewUpdateFlag = -1;
  24292. _this._alternateProjectionUpdateFlag = -1;
  24293. /** @hidden */
  24294. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24295. _this._activeRequests = new Array();
  24296. _this._pendingData = new Array();
  24297. _this._isDisposed = false;
  24298. /**
  24299. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24300. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24301. */
  24302. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24303. _this._activeMeshes = new BABYLON.SmartArray(256);
  24304. _this._processedMaterials = new BABYLON.SmartArray(256);
  24305. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24306. /** @hidden */
  24307. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24308. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24309. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24310. /** @hidden */
  24311. _this._activeAnimatables = new Array();
  24312. _this._transformMatrix = BABYLON.Matrix.Zero();
  24313. _this._useAlternateCameraConfiguration = false;
  24314. _this._alternateRendering = false;
  24315. /**
  24316. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24317. * This is useful if there are more lights that the maximum simulteanous authorized
  24318. */
  24319. _this.requireLightSorting = false;
  24320. /**
  24321. * @hidden
  24322. * Backing store of defined scene components.
  24323. */
  24324. _this._components = [];
  24325. /**
  24326. * @hidden
  24327. * Backing store of defined scene components.
  24328. */
  24329. _this._serializableComponents = [];
  24330. /**
  24331. * List of components to register on the next registration step.
  24332. */
  24333. _this._transientComponents = [];
  24334. /**
  24335. * @hidden
  24336. * Defines the actions happening before camera updates.
  24337. */
  24338. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24339. /**
  24340. * @hidden
  24341. * Defines the actions happening before clear the canvas.
  24342. */
  24343. _this._beforeClearStage = BABYLON.Stage.Create();
  24344. /**
  24345. * @hidden
  24346. * Defines the actions when collecting render targets for the frame.
  24347. */
  24348. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24349. /**
  24350. * @hidden
  24351. * Defines the actions happening for one camera in the frame.
  24352. */
  24353. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24354. /**
  24355. * @hidden
  24356. * Defines the actions happening during the per mesh ready checks.
  24357. */
  24358. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24359. /**
  24360. * @hidden
  24361. * Defines the actions happening before evaluate active mesh checks.
  24362. */
  24363. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24364. /**
  24365. * @hidden
  24366. * Defines the actions happening during the evaluate sub mesh checks.
  24367. */
  24368. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24369. /**
  24370. * @hidden
  24371. * Defines the actions happening during the active mesh stage.
  24372. */
  24373. _this._activeMeshStage = BABYLON.Stage.Create();
  24374. /**
  24375. * @hidden
  24376. * Defines the actions happening during the per camera render target step.
  24377. */
  24378. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24379. /**
  24380. * @hidden
  24381. * Defines the actions happening just before the active camera is drawing.
  24382. */
  24383. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24384. /**
  24385. * @hidden
  24386. * Defines the actions happening just before a rendering group is drawing.
  24387. */
  24388. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24389. /**
  24390. * @hidden
  24391. * Defines the actions happening just before a mesh is drawing.
  24392. */
  24393. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24394. /**
  24395. * @hidden
  24396. * Defines the actions happening just after a mesh has been drawn.
  24397. */
  24398. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24399. /**
  24400. * @hidden
  24401. * Defines the actions happening just after a rendering group has been drawn.
  24402. */
  24403. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24404. /**
  24405. * @hidden
  24406. * Defines the actions happening just after the active camera has been drawn.
  24407. */
  24408. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24409. /**
  24410. * @hidden
  24411. * Defines the actions happening just after rendering all cameras and computing intersections.
  24412. */
  24413. _this._afterRenderStage = BABYLON.Stage.Create();
  24414. /**
  24415. * @hidden
  24416. * Defines the actions happening when a pointer move event happens.
  24417. */
  24418. _this._pointerMoveStage = BABYLON.Stage.Create();
  24419. /**
  24420. * @hidden
  24421. * Defines the actions happening when a pointer down event happens.
  24422. */
  24423. _this._pointerDownStage = BABYLON.Stage.Create();
  24424. /**
  24425. * @hidden
  24426. * Defines the actions happening when a pointer up event happens.
  24427. */
  24428. _this._pointerUpStage = BABYLON.Stage.Create();
  24429. _this._defaultMeshCandidates = {
  24430. data: [],
  24431. length: 0
  24432. };
  24433. _this._defaultSubMeshCandidates = {
  24434. data: [],
  24435. length: 0
  24436. };
  24437. _this._activeMeshesFrozen = false;
  24438. /** @hidden */
  24439. _this._allowPostProcessClearColor = true;
  24440. /**
  24441. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24442. */
  24443. _this.getDeterministicFrameTime = function () {
  24444. return 1000.0 / 60.0; // frame time in ms
  24445. };
  24446. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24447. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24448. _this.blockMaterialDirtyMechanism = false;
  24449. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24450. _this._engine.scenes.push(_this);
  24451. _this._uid = null;
  24452. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24453. if (BABYLON.PostProcessManager) {
  24454. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24455. }
  24456. if (BABYLON.Tools.IsWindowObjectExist()) {
  24457. _this.attachControl();
  24458. }
  24459. //collision coordinator initialization. For now legacy per default.
  24460. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24461. // Uniform Buffer
  24462. _this._createUbo();
  24463. // Default Image processing definition
  24464. if (BABYLON.ImageProcessingConfiguration) {
  24465. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24466. }
  24467. _this.setDefaultCandidateProviders();
  24468. return _this;
  24469. }
  24470. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24471. /**
  24472. * Texture used in all pbr material as the reflection texture.
  24473. * As in the majority of the scene they are the same (exception for multi room and so on),
  24474. * this is easier to reference from here than from all the materials.
  24475. */
  24476. get: function () {
  24477. return this._environmentTexture;
  24478. },
  24479. /**
  24480. * Texture used in all pbr material as the reflection texture.
  24481. * As in the majority of the scene they are the same (exception for multi room and so on),
  24482. * this is easier to set here than in all the materials.
  24483. */
  24484. set: function (value) {
  24485. if (this._environmentTexture === value) {
  24486. return;
  24487. }
  24488. this._environmentTexture = value;
  24489. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24495. /**
  24496. * Default image processing configuration used either in the rendering
  24497. * Forward main pass or through the imageProcessingPostProcess if present.
  24498. * As in the majority of the scene they are the same (exception for multi camera),
  24499. * this is easier to reference from here than from all the materials and post process.
  24500. *
  24501. * No setter as we it is a shared configuration, you can set the values instead.
  24502. */
  24503. get: function () {
  24504. return this._imageProcessingConfiguration;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24510. get: function () {
  24511. return this._forceWireframe;
  24512. },
  24513. /**
  24514. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24515. */
  24516. set: function (value) {
  24517. if (this._forceWireframe === value) {
  24518. return;
  24519. }
  24520. this._forceWireframe = value;
  24521. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24522. },
  24523. enumerable: true,
  24524. configurable: true
  24525. });
  24526. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24527. get: function () {
  24528. return this._forcePointsCloud;
  24529. },
  24530. /**
  24531. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24532. */
  24533. set: function (value) {
  24534. if (this._forcePointsCloud === value) {
  24535. return;
  24536. }
  24537. this._forcePointsCloud = value;
  24538. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24544. /**
  24545. * Gets or sets the animation properties override
  24546. */
  24547. get: function () {
  24548. return this._animationPropertiesOverride;
  24549. },
  24550. set: function (value) {
  24551. this._animationPropertiesOverride = value;
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "onDispose", {
  24557. /** Sets a function to be executed when this scene is disposed. */
  24558. set: function (callback) {
  24559. if (this._onDisposeObserver) {
  24560. this.onDisposeObservable.remove(this._onDisposeObserver);
  24561. }
  24562. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "beforeRender", {
  24568. /** Sets a function to be executed before rendering this scene */
  24569. set: function (callback) {
  24570. if (this._onBeforeRenderObserver) {
  24571. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24572. }
  24573. if (callback) {
  24574. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24575. }
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Scene.prototype, "afterRender", {
  24581. /** Sets a function to be executed after rendering this scene */
  24582. set: function (callback) {
  24583. if (this._onAfterRenderObserver) {
  24584. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24585. }
  24586. if (callback) {
  24587. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24588. }
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24594. /** Sets a function to be executed before rendering a camera*/
  24595. set: function (callback) {
  24596. if (this._onBeforeCameraRenderObserver) {
  24597. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24598. }
  24599. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24600. },
  24601. enumerable: true,
  24602. configurable: true
  24603. });
  24604. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24605. /** Sets a function to be executed after rendering a camera*/
  24606. set: function (callback) {
  24607. if (this._onAfterCameraRenderObserver) {
  24608. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24609. }
  24610. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24616. /**
  24617. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24618. */
  24619. get: function () {
  24620. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24626. get: function () {
  24627. return this._useRightHandedSystem;
  24628. },
  24629. /**
  24630. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24631. */
  24632. set: function (value) {
  24633. if (this._useRightHandedSystem === value) {
  24634. return;
  24635. }
  24636. this._useRightHandedSystem = value;
  24637. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. /**
  24643. * Sets the step Id used by deterministic lock step
  24644. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24645. * @param newStepId defines the step Id
  24646. */
  24647. Scene.prototype.setStepId = function (newStepId) {
  24648. this._currentStepId = newStepId;
  24649. };
  24650. ;
  24651. /**
  24652. * Gets the step Id used by deterministic lock step
  24653. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24654. * @returns the step Id
  24655. */
  24656. Scene.prototype.getStepId = function () {
  24657. return this._currentStepId;
  24658. };
  24659. ;
  24660. /**
  24661. * Gets the internal step used by deterministic lock step
  24662. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24663. * @returns the internal step
  24664. */
  24665. Scene.prototype.getInternalStep = function () {
  24666. return this._currentInternalStep;
  24667. };
  24668. ;
  24669. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24670. get: function () {
  24671. return this._fogEnabled;
  24672. },
  24673. /**
  24674. * Gets or sets a boolean indicating if fog is enabled on this scene
  24675. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24676. */
  24677. set: function (value) {
  24678. if (this._fogEnabled === value) {
  24679. return;
  24680. }
  24681. this._fogEnabled = value;
  24682. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. Object.defineProperty(Scene.prototype, "fogMode", {
  24688. get: function () {
  24689. return this._fogMode;
  24690. },
  24691. /**
  24692. * Gets or sets the fog mode to use
  24693. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24694. */
  24695. set: function (value) {
  24696. if (this._fogMode === value) {
  24697. return;
  24698. }
  24699. this._fogMode = value;
  24700. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24706. get: function () {
  24707. return this._shadowsEnabled;
  24708. },
  24709. /**
  24710. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24711. */
  24712. set: function (value) {
  24713. if (this._shadowsEnabled === value) {
  24714. return;
  24715. }
  24716. this._shadowsEnabled = value;
  24717. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24723. get: function () {
  24724. return this._lightsEnabled;
  24725. },
  24726. /**
  24727. * Gets or sets a boolean indicating if lights are enabled on this scene
  24728. */
  24729. set: function (value) {
  24730. if (this._lightsEnabled === value) {
  24731. return;
  24732. }
  24733. this._lightsEnabled = value;
  24734. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24740. /** The default material used on meshes when no material is affected */
  24741. get: function () {
  24742. if (!this._defaultMaterial) {
  24743. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24744. }
  24745. return this._defaultMaterial;
  24746. },
  24747. /** The default material used on meshes when no material is affected */
  24748. set: function (value) {
  24749. this._defaultMaterial = value;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24755. get: function () {
  24756. return this._texturesEnabled;
  24757. },
  24758. /**
  24759. * Gets or sets a boolean indicating if textures are enabled on this scene
  24760. */
  24761. set: function (value) {
  24762. if (this._texturesEnabled === value) {
  24763. return;
  24764. }
  24765. this._texturesEnabled = value;
  24766. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24772. get: function () {
  24773. return this._skeletonsEnabled;
  24774. },
  24775. /**
  24776. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24777. */
  24778. set: function (value) {
  24779. if (this._skeletonsEnabled === value) {
  24780. return;
  24781. }
  24782. this._skeletonsEnabled = value;
  24783. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24789. /** @hidden */
  24790. get: function () {
  24791. return this._alternateRendering;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24797. /**
  24798. * Gets the list of frustum planes (built from the active camera)
  24799. */
  24800. get: function () {
  24801. return this._frustumPlanes;
  24802. },
  24803. enumerable: true,
  24804. configurable: true
  24805. });
  24806. /**
  24807. * Registers the transient components if needed.
  24808. */
  24809. Scene.prototype._registerTransientComponents = function () {
  24810. // Register components that have been associated lately to the scene.
  24811. if (this._transientComponents.length > 0) {
  24812. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24813. var component = _a[_i];
  24814. component.register();
  24815. }
  24816. this._transientComponents = [];
  24817. }
  24818. };
  24819. /**
  24820. * @hidden
  24821. * Add a component to the scene.
  24822. * Note that the ccomponent could be registered on th next frame if this is called after
  24823. * the register component stage.
  24824. * @param component Defines the component to add to the scene
  24825. */
  24826. Scene.prototype._addComponent = function (component) {
  24827. this._components.push(component);
  24828. this._transientComponents.push(component);
  24829. var serializableComponent = component;
  24830. if (serializableComponent.addFromContainer) {
  24831. this._serializableComponents.push(serializableComponent);
  24832. }
  24833. };
  24834. /**
  24835. * @hidden
  24836. * Gets a component from the scene.
  24837. * @param name defines the name of the component to retrieve
  24838. * @returns the component or null if not present
  24839. */
  24840. Scene.prototype._getComponent = function (name) {
  24841. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24842. var component = _a[_i];
  24843. if (component.name === name) {
  24844. return component;
  24845. }
  24846. }
  24847. return null;
  24848. };
  24849. /**
  24850. * @hidden
  24851. */
  24852. Scene.prototype._getDefaultMeshCandidates = function () {
  24853. this._defaultMeshCandidates.data = this.meshes;
  24854. this._defaultMeshCandidates.length = this.meshes.length;
  24855. return this._defaultMeshCandidates;
  24856. };
  24857. /**
  24858. * @hidden
  24859. */
  24860. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24861. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24862. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24863. return this._defaultSubMeshCandidates;
  24864. };
  24865. /**
  24866. * Sets the default candidate providers for the scene.
  24867. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24868. * and getCollidingSubMeshCandidates to their default function
  24869. */
  24870. Scene.prototype.setDefaultCandidateProviders = function () {
  24871. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24872. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24873. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24874. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24875. };
  24876. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24877. /**
  24878. * Gets a boolean indicating if collisions are processed on a web worker
  24879. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24880. */
  24881. get: function () {
  24882. return this._workerCollisions;
  24883. },
  24884. set: function (enabled) {
  24885. if (!BABYLON.CollisionCoordinatorLegacy) {
  24886. return;
  24887. }
  24888. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24889. this._workerCollisions = enabled;
  24890. if (this.collisionCoordinator) {
  24891. this.collisionCoordinator.destroy();
  24892. }
  24893. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24894. this.collisionCoordinator.init(this);
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24900. /**
  24901. * Gets the mesh that is currently under the pointer
  24902. */
  24903. get: function () {
  24904. return this._pointerOverMesh;
  24905. },
  24906. enumerable: true,
  24907. configurable: true
  24908. });
  24909. Object.defineProperty(Scene.prototype, "pointerX", {
  24910. /**
  24911. * Gets the current on-screen X position of the pointer
  24912. */
  24913. get: function () {
  24914. return this._pointerX;
  24915. },
  24916. enumerable: true,
  24917. configurable: true
  24918. });
  24919. Object.defineProperty(Scene.prototype, "pointerY", {
  24920. /**
  24921. * Gets the current on-screen Y position of the pointer
  24922. */
  24923. get: function () {
  24924. return this._pointerY;
  24925. },
  24926. enumerable: true,
  24927. configurable: true
  24928. });
  24929. /**
  24930. * Gets the cached material (ie. the latest rendered one)
  24931. * @returns the cached material
  24932. */
  24933. Scene.prototype.getCachedMaterial = function () {
  24934. return this._cachedMaterial;
  24935. };
  24936. /**
  24937. * Gets the cached effect (ie. the latest rendered one)
  24938. * @returns the cached effect
  24939. */
  24940. Scene.prototype.getCachedEffect = function () {
  24941. return this._cachedEffect;
  24942. };
  24943. /**
  24944. * Gets the cached visibility state (ie. the latest rendered one)
  24945. * @returns the cached visibility state
  24946. */
  24947. Scene.prototype.getCachedVisibility = function () {
  24948. return this._cachedVisibility;
  24949. };
  24950. /**
  24951. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24952. * @param material defines the current material
  24953. * @param effect defines the current effect
  24954. * @param visibility defines the current visibility state
  24955. * @returns true if one parameter is not cached
  24956. */
  24957. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24958. if (visibility === void 0) { visibility = 1; }
  24959. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24960. };
  24961. /**
  24962. * Gets the engine associated with the scene
  24963. * @returns an Engine
  24964. */
  24965. Scene.prototype.getEngine = function () {
  24966. return this._engine;
  24967. };
  24968. /**
  24969. * Gets the total number of vertices rendered per frame
  24970. * @returns the total number of vertices rendered per frame
  24971. */
  24972. Scene.prototype.getTotalVertices = function () {
  24973. return this._totalVertices.current;
  24974. };
  24975. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24976. /**
  24977. * Gets the performance counter for total vertices
  24978. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24979. */
  24980. get: function () {
  24981. return this._totalVertices;
  24982. },
  24983. enumerable: true,
  24984. configurable: true
  24985. });
  24986. /**
  24987. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24988. * @returns the total number of active indices rendered per frame
  24989. */
  24990. Scene.prototype.getActiveIndices = function () {
  24991. return this._activeIndices.current;
  24992. };
  24993. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24994. /**
  24995. * Gets the performance counter for active indices
  24996. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24997. */
  24998. get: function () {
  24999. return this._activeIndices;
  25000. },
  25001. enumerable: true,
  25002. configurable: true
  25003. });
  25004. /**
  25005. * Gets the total number of active particles rendered per frame
  25006. * @returns the total number of active particles rendered per frame
  25007. */
  25008. Scene.prototype.getActiveParticles = function () {
  25009. return this._activeParticles.current;
  25010. };
  25011. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25012. /**
  25013. * Gets the performance counter for active particles
  25014. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25015. */
  25016. get: function () {
  25017. return this._activeParticles;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. /**
  25023. * Gets the total number of active bones rendered per frame
  25024. * @returns the total number of active bones rendered per frame
  25025. */
  25026. Scene.prototype.getActiveBones = function () {
  25027. return this._activeBones.current;
  25028. };
  25029. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25030. /**
  25031. * Gets the performance counter for active bones
  25032. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25033. */
  25034. get: function () {
  25035. return this._activeBones;
  25036. },
  25037. enumerable: true,
  25038. configurable: true
  25039. });
  25040. /** @hidden */
  25041. Scene.prototype.getInterFramePerfCounter = function () {
  25042. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25043. return 0;
  25044. };
  25045. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25046. /** @hidden */
  25047. get: function () {
  25048. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25049. return null;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. /** @hidden */
  25055. Scene.prototype.getLastFrameDuration = function () {
  25056. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25057. return 0;
  25058. };
  25059. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25060. /** @hidden */
  25061. get: function () {
  25062. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25063. return null;
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. /** @hidden */
  25069. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25070. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25071. return 0;
  25072. };
  25073. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25074. /** @hidden */
  25075. get: function () {
  25076. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25077. return null;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. /**
  25083. * Gets the array of active meshes
  25084. * @returns an array of AbstractMesh
  25085. */
  25086. Scene.prototype.getActiveMeshes = function () {
  25087. return this._activeMeshes;
  25088. };
  25089. /** @hidden */
  25090. Scene.prototype.getRenderTargetsDuration = function () {
  25091. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25092. return 0;
  25093. };
  25094. /** @hidden */
  25095. Scene.prototype.getRenderDuration = function () {
  25096. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25097. return 0;
  25098. };
  25099. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25100. /** @hidden */
  25101. get: function () {
  25102. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25103. return null;
  25104. },
  25105. enumerable: true,
  25106. configurable: true
  25107. });
  25108. /** @hidden */
  25109. Scene.prototype.getParticlesDuration = function () {
  25110. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25111. return 0;
  25112. };
  25113. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25114. /** @hidden */
  25115. get: function () {
  25116. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25117. return null;
  25118. },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. /** @hidden */
  25123. Scene.prototype.getSpritesDuration = function () {
  25124. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25125. return 0;
  25126. };
  25127. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25128. /** @hidden */
  25129. get: function () {
  25130. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25131. return null;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. /**
  25137. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25138. * @returns a number
  25139. */
  25140. Scene.prototype.getAnimationRatio = function () {
  25141. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25142. };
  25143. /**
  25144. * Gets an unique Id for the current render phase
  25145. * @returns a number
  25146. */
  25147. Scene.prototype.getRenderId = function () {
  25148. return this._renderId;
  25149. };
  25150. /**
  25151. * Gets an unique Id for the current frame
  25152. * @returns a number
  25153. */
  25154. Scene.prototype.getFrameId = function () {
  25155. return this._frameId;
  25156. };
  25157. /** Call this function if you want to manually increment the render Id*/
  25158. Scene.prototype.incrementRenderId = function () {
  25159. this._renderId++;
  25160. };
  25161. Scene.prototype._updatePointerPosition = function (evt) {
  25162. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25163. if (!canvasRect) {
  25164. return;
  25165. }
  25166. this._pointerX = evt.clientX - canvasRect.left;
  25167. this._pointerY = evt.clientY - canvasRect.top;
  25168. this._unTranslatedPointerX = this._pointerX;
  25169. this._unTranslatedPointerY = this._pointerY;
  25170. };
  25171. Scene.prototype._createUbo = function () {
  25172. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25173. this._sceneUbo.addUniform("viewProjection", 16);
  25174. this._sceneUbo.addUniform("view", 16);
  25175. };
  25176. Scene.prototype._createAlternateUbo = function () {
  25177. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25178. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25179. this._alternateSceneUbo.addUniform("view", 16);
  25180. };
  25181. // Pointers handling
  25182. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25183. if (pointerInfo.pickInfo) {
  25184. if (!pointerInfo.pickInfo.ray) {
  25185. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25186. }
  25187. }
  25188. };
  25189. /**
  25190. * Use this method to simulate a pointer move on a mesh
  25191. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25192. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25193. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25194. * @returns the current scene
  25195. */
  25196. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25197. var evt = new PointerEvent("pointermove", pointerEventInit);
  25198. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25199. return this;
  25200. }
  25201. return this._processPointerMove(pickResult, evt);
  25202. };
  25203. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25204. var canvas = this._engine.getRenderingCanvas();
  25205. if (!canvas) {
  25206. return this;
  25207. }
  25208. // Restore pointer
  25209. canvas.style.cursor = this.defaultCursor;
  25210. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25211. if (isMeshPicked) {
  25212. this.setPointerOverMesh(pickResult.pickedMesh);
  25213. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25214. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25215. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25216. }
  25217. else {
  25218. canvas.style.cursor = this.hoverCursor;
  25219. }
  25220. }
  25221. }
  25222. else {
  25223. this.setPointerOverMesh(null);
  25224. }
  25225. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25226. var step = _a[_i];
  25227. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25228. }
  25229. if (pickResult) {
  25230. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25231. if (this.onPointerMove) {
  25232. this.onPointerMove(evt, pickResult, type);
  25233. }
  25234. if (this.onPointerObservable.hasObservers()) {
  25235. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25236. this._setRayOnPointerInfo(pi);
  25237. this.onPointerObservable.notifyObservers(pi, type);
  25238. }
  25239. }
  25240. return this;
  25241. };
  25242. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25243. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25244. if (pickResult) {
  25245. pi.ray = pickResult.ray;
  25246. }
  25247. this.onPrePointerObservable.notifyObservers(pi, type);
  25248. if (pi.skipOnPointerObservable) {
  25249. return true;
  25250. }
  25251. else {
  25252. return false;
  25253. }
  25254. };
  25255. /**
  25256. * Use this method to simulate a pointer down on a mesh
  25257. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25258. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25259. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25260. * @returns the current scene
  25261. */
  25262. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25263. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25264. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25265. return this;
  25266. }
  25267. return this._processPointerDown(pickResult, evt);
  25268. };
  25269. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25270. var _this = this;
  25271. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25272. this._pickedDownMesh = pickResult.pickedMesh;
  25273. var actionManager = pickResult.pickedMesh.actionManager;
  25274. if (actionManager) {
  25275. if (actionManager.hasPickTriggers) {
  25276. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25277. switch (evt.button) {
  25278. case 0:
  25279. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25280. break;
  25281. case 1:
  25282. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25283. break;
  25284. case 2:
  25285. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25286. break;
  25287. }
  25288. }
  25289. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25290. window.setTimeout(function () {
  25291. 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);
  25292. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25293. if (_this._totalPointersPressed !== 0 &&
  25294. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25295. !_this._isPointerSwiping()) {
  25296. _this._startingPointerTime = 0;
  25297. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25298. }
  25299. }
  25300. }, Scene.LongPressDelay);
  25301. }
  25302. }
  25303. }
  25304. else {
  25305. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25306. var step = _a[_i];
  25307. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25308. }
  25309. }
  25310. if (pickResult) {
  25311. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25312. if (this.onPointerDown) {
  25313. this.onPointerDown(evt, pickResult, type);
  25314. }
  25315. if (this.onPointerObservable.hasObservers()) {
  25316. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25317. this._setRayOnPointerInfo(pi);
  25318. this.onPointerObservable.notifyObservers(pi, type);
  25319. }
  25320. }
  25321. return this;
  25322. };
  25323. /**
  25324. * Use this method to simulate a pointer up on a mesh
  25325. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25326. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25327. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25328. * @returns the current scene
  25329. */
  25330. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25331. var evt = new PointerEvent("pointerup", pointerEventInit);
  25332. var clickInfo = new ClickInfo();
  25333. clickInfo.singleClick = true;
  25334. clickInfo.ignore = true;
  25335. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25336. return this;
  25337. }
  25338. return this._processPointerUp(pickResult, evt, clickInfo);
  25339. };
  25340. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25341. if (pickResult && pickResult && pickResult.pickedMesh) {
  25342. this._pickedUpMesh = pickResult.pickedMesh;
  25343. if (this._pickedDownMesh === this._pickedUpMesh) {
  25344. if (this.onPointerPick) {
  25345. this.onPointerPick(evt, pickResult);
  25346. }
  25347. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25348. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25349. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25350. this._setRayOnPointerInfo(pi);
  25351. this.onPointerObservable.notifyObservers(pi, type_1);
  25352. }
  25353. }
  25354. if (pickResult.pickedMesh.actionManager) {
  25355. if (clickInfo.ignore) {
  25356. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25357. }
  25358. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25359. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25360. }
  25361. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25363. }
  25364. }
  25365. }
  25366. else {
  25367. if (!clickInfo.ignore) {
  25368. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25369. var step = _a[_i];
  25370. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25371. }
  25372. }
  25373. }
  25374. if (this._pickedDownMesh &&
  25375. this._pickedDownMesh.actionManager &&
  25376. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25377. this._pickedDownMesh !== this._pickedUpMesh) {
  25378. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25379. }
  25380. var type = BABYLON.PointerEventTypes.POINTERUP;
  25381. if (this.onPointerObservable.hasObservers()) {
  25382. if (!clickInfo.ignore) {
  25383. if (!clickInfo.hasSwiped) {
  25384. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25385. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25386. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25387. this._setRayOnPointerInfo(pi);
  25388. this.onPointerObservable.notifyObservers(pi, type_2);
  25389. }
  25390. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25391. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25392. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25393. this._setRayOnPointerInfo(pi);
  25394. this.onPointerObservable.notifyObservers(pi, type_3);
  25395. }
  25396. }
  25397. }
  25398. else {
  25399. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25400. this._setRayOnPointerInfo(pi);
  25401. this.onPointerObservable.notifyObservers(pi, type);
  25402. }
  25403. }
  25404. if (this.onPointerUp) {
  25405. this.onPointerUp(evt, pickResult, type);
  25406. }
  25407. return this;
  25408. };
  25409. /**
  25410. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25411. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25412. * @returns true if the pointer was captured
  25413. */
  25414. Scene.prototype.isPointerCaptured = function (pointerId) {
  25415. if (pointerId === void 0) { pointerId = 0; }
  25416. return this._pointerCaptures[pointerId];
  25417. };
  25418. /** @hidden */
  25419. Scene.prototype._isPointerSwiping = function () {
  25420. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25421. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25422. };
  25423. /**
  25424. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25425. * @param attachUp defines if you want to attach events to pointerup
  25426. * @param attachDown defines if you want to attach events to pointerdown
  25427. * @param attachMove defines if you want to attach events to pointermove
  25428. */
  25429. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25430. var _this = this;
  25431. if (attachUp === void 0) { attachUp = true; }
  25432. if (attachDown === void 0) { attachDown = true; }
  25433. if (attachMove === void 0) { attachMove = true; }
  25434. this._initActionManager = function (act, clickInfo) {
  25435. if (!_this._meshPickProceed) {
  25436. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25437. _this._currentPickResult = pickResult;
  25438. if (pickResult) {
  25439. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25440. }
  25441. _this._meshPickProceed = true;
  25442. }
  25443. return act;
  25444. };
  25445. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25446. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25447. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25448. btn !== _this._previousButtonPressed) {
  25449. _this._doubleClickOccured = false;
  25450. clickInfo.singleClick = true;
  25451. clickInfo.ignore = false;
  25452. cb(clickInfo, _this._currentPickResult);
  25453. }
  25454. };
  25455. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25456. var clickInfo = new ClickInfo();
  25457. _this._currentPickResult = null;
  25458. var act = null;
  25459. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25460. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25461. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25462. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25463. act = _this._initActionManager(act, clickInfo);
  25464. if (act)
  25465. checkPicking = act.hasPickTriggers;
  25466. }
  25467. if (checkPicking) {
  25468. var btn = evt.button;
  25469. clickInfo.hasSwiped = _this._isPointerSwiping();
  25470. if (!clickInfo.hasSwiped) {
  25471. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25472. if (!checkSingleClickImmediately) {
  25473. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25474. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25475. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25476. act = _this._initActionManager(act, clickInfo);
  25477. if (act)
  25478. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25479. }
  25480. }
  25481. if (checkSingleClickImmediately) {
  25482. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25483. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25484. btn !== _this._previousButtonPressed) {
  25485. clickInfo.singleClick = true;
  25486. cb(clickInfo, _this._currentPickResult);
  25487. }
  25488. }
  25489. // at least one double click is required to be check and exclusive double click is enabled
  25490. else {
  25491. // wait that no double click has been raised during the double click delay
  25492. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25493. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25494. }
  25495. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25496. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25497. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25498. act = _this._initActionManager(act, clickInfo);
  25499. if (act)
  25500. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25501. }
  25502. if (checkDoubleClick) {
  25503. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25504. if (btn === _this._previousButtonPressed &&
  25505. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25506. !_this._doubleClickOccured) {
  25507. // pointer has not moved for 2 clicks, it's a double click
  25508. if (!clickInfo.hasSwiped &&
  25509. !_this._isPointerSwiping()) {
  25510. _this._previousStartingPointerTime = 0;
  25511. _this._doubleClickOccured = true;
  25512. clickInfo.doubleClick = true;
  25513. clickInfo.ignore = false;
  25514. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25515. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25516. }
  25517. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25518. cb(clickInfo, _this._currentPickResult);
  25519. }
  25520. // if the two successive clicks are too far, it's just two simple clicks
  25521. else {
  25522. _this._doubleClickOccured = false;
  25523. _this._previousStartingPointerTime = _this._startingPointerTime;
  25524. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25525. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25526. _this._previousButtonPressed = btn;
  25527. if (Scene.ExclusiveDoubleClickMode) {
  25528. if (_this._previousDelayedSimpleClickTimeout) {
  25529. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25530. }
  25531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25532. cb(clickInfo, _this._previousPickResult);
  25533. }
  25534. else {
  25535. cb(clickInfo, _this._currentPickResult);
  25536. }
  25537. }
  25538. }
  25539. // just the first click of the double has been raised
  25540. else {
  25541. _this._doubleClickOccured = false;
  25542. _this._previousStartingPointerTime = _this._startingPointerTime;
  25543. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25544. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25545. _this._previousButtonPressed = btn;
  25546. }
  25547. }
  25548. }
  25549. }
  25550. clickInfo.ignore = true;
  25551. cb(clickInfo, _this._currentPickResult);
  25552. };
  25553. this._onPointerMove = function (evt) {
  25554. _this._updatePointerPosition(evt);
  25555. // PreObservable support
  25556. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25557. return;
  25558. }
  25559. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25560. return;
  25561. }
  25562. if (!_this.pointerMovePredicate) {
  25563. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25564. }
  25565. // Meshes
  25566. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25567. _this._processPointerMove(pickResult, evt);
  25568. };
  25569. this._onPointerDown = function (evt) {
  25570. _this._totalPointersPressed++;
  25571. _this._pickedDownMesh = null;
  25572. _this._meshPickProceed = false;
  25573. _this._updatePointerPosition(evt);
  25574. if (_this.preventDefaultOnPointerDown && canvas) {
  25575. evt.preventDefault();
  25576. canvas.focus();
  25577. }
  25578. // PreObservable support
  25579. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25580. return;
  25581. }
  25582. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25583. return;
  25584. }
  25585. _this._pointerCaptures[evt.pointerId] = true;
  25586. _this._startingPointerPosition.x = _this._pointerX;
  25587. _this._startingPointerPosition.y = _this._pointerY;
  25588. _this._startingPointerTime = Date.now();
  25589. if (!_this.pointerDownPredicate) {
  25590. _this.pointerDownPredicate = function (mesh) {
  25591. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25592. };
  25593. }
  25594. // Meshes
  25595. _this._pickedDownMesh = null;
  25596. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25597. _this._processPointerDown(pickResult, evt);
  25598. };
  25599. this._onPointerUp = function (evt) {
  25600. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25601. return; // So we need to test it the pointer down was pressed before.
  25602. }
  25603. _this._totalPointersPressed--;
  25604. _this._pickedUpMesh = null;
  25605. _this._meshPickProceed = false;
  25606. _this._updatePointerPosition(evt);
  25607. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25608. // PreObservable support
  25609. if (_this.onPrePointerObservable.hasObservers()) {
  25610. if (!clickInfo.ignore) {
  25611. if (!clickInfo.hasSwiped) {
  25612. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25613. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25614. return;
  25615. }
  25616. }
  25617. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25618. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25619. return;
  25620. }
  25621. }
  25622. }
  25623. }
  25624. else {
  25625. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25626. return;
  25627. }
  25628. }
  25629. }
  25630. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25631. return;
  25632. }
  25633. _this._pointerCaptures[evt.pointerId] = false;
  25634. if (!_this.pointerUpPredicate) {
  25635. _this.pointerUpPredicate = function (mesh) {
  25636. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25637. };
  25638. }
  25639. // Meshes
  25640. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25641. _this._initActionManager(null, clickInfo);
  25642. }
  25643. if (!pickResult) {
  25644. pickResult = _this._currentPickResult;
  25645. }
  25646. _this._processPointerUp(pickResult, evt, clickInfo);
  25647. _this._previousPickResult = _this._currentPickResult;
  25648. });
  25649. };
  25650. this._onKeyDown = function (evt) {
  25651. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25652. if (_this.onPreKeyboardObservable.hasObservers()) {
  25653. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25654. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25655. if (pi.skipOnPointerObservable) {
  25656. return;
  25657. }
  25658. }
  25659. if (_this.onKeyboardObservable.hasObservers()) {
  25660. var pi = new BABYLON.KeyboardInfo(type, evt);
  25661. _this.onKeyboardObservable.notifyObservers(pi, type);
  25662. }
  25663. if (_this.actionManager) {
  25664. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25665. }
  25666. };
  25667. this._onKeyUp = function (evt) {
  25668. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25669. if (_this.onPreKeyboardObservable.hasObservers()) {
  25670. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25671. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25672. if (pi.skipOnPointerObservable) {
  25673. return;
  25674. }
  25675. }
  25676. if (_this.onKeyboardObservable.hasObservers()) {
  25677. var pi = new BABYLON.KeyboardInfo(type, evt);
  25678. _this.onKeyboardObservable.notifyObservers(pi, type);
  25679. }
  25680. if (_this.actionManager) {
  25681. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25682. }
  25683. };
  25684. var engine = this.getEngine();
  25685. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25686. if (!canvas) {
  25687. return;
  25688. }
  25689. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25690. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25691. });
  25692. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25693. if (!canvas) {
  25694. return;
  25695. }
  25696. canvas.removeEventListener("keydown", _this._onKeyDown);
  25697. canvas.removeEventListener("keyup", _this._onKeyUp);
  25698. });
  25699. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25700. var canvas = this._engine.getRenderingCanvas();
  25701. if (!canvas) {
  25702. return;
  25703. }
  25704. if (attachMove) {
  25705. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25706. // Wheel
  25707. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25708. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25709. }
  25710. if (attachDown) {
  25711. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25712. }
  25713. if (attachUp) {
  25714. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25715. }
  25716. canvas.tabIndex = 1;
  25717. };
  25718. /** Detaches all event handlers*/
  25719. Scene.prototype.detachControl = function () {
  25720. var engine = this.getEngine();
  25721. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25722. var canvas = engine.getRenderingCanvas();
  25723. if (!canvas) {
  25724. return;
  25725. }
  25726. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25727. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25728. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25729. if (this._onCanvasBlurObserver) {
  25730. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25731. }
  25732. if (this._onCanvasFocusObserver) {
  25733. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25734. }
  25735. // Wheel
  25736. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25737. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25738. // Keyboard
  25739. canvas.removeEventListener("keydown", this._onKeyDown);
  25740. canvas.removeEventListener("keyup", this._onKeyUp);
  25741. // Observables
  25742. this.onKeyboardObservable.clear();
  25743. this.onPreKeyboardObservable.clear();
  25744. this.onPointerObservable.clear();
  25745. this.onPrePointerObservable.clear();
  25746. };
  25747. /**
  25748. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25749. * Delay loaded resources are not taking in account
  25750. * @return true if all required resources are ready
  25751. */
  25752. Scene.prototype.isReady = function () {
  25753. if (this._isDisposed) {
  25754. return false;
  25755. }
  25756. if (this._pendingData.length > 0) {
  25757. return false;
  25758. }
  25759. var index;
  25760. var engine = this.getEngine();
  25761. // Geometries
  25762. for (index = 0; index < this.geometries.length; index++) {
  25763. var geometry = this.geometries[index];
  25764. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25765. return false;
  25766. }
  25767. }
  25768. // Meshes
  25769. for (index = 0; index < this.meshes.length; index++) {
  25770. var mesh = this.meshes[index];
  25771. if (!mesh.isEnabled()) {
  25772. continue;
  25773. }
  25774. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25775. continue;
  25776. }
  25777. if (!mesh.isReady(true)) {
  25778. return false;
  25779. }
  25780. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25781. // Is Ready For Mesh
  25782. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25783. var step = _a[_i];
  25784. if (!step.action(mesh, hardwareInstancedRendering)) {
  25785. return false;
  25786. }
  25787. }
  25788. }
  25789. // Post-processes
  25790. if (this.activeCameras && this.activeCameras.length > 0) {
  25791. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25792. var camera = _c[_b];
  25793. if (!camera.isReady(true)) {
  25794. return false;
  25795. }
  25796. }
  25797. }
  25798. else if (this.activeCamera) {
  25799. if (!this.activeCamera.isReady(true)) {
  25800. return false;
  25801. }
  25802. }
  25803. // Particles
  25804. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25805. var particleSystem = _e[_d];
  25806. if (!particleSystem.isReady()) {
  25807. return false;
  25808. }
  25809. }
  25810. return true;
  25811. };
  25812. /** Resets all cached information relative to material (including effect and visibility) */
  25813. Scene.prototype.resetCachedMaterial = function () {
  25814. this._cachedMaterial = null;
  25815. this._cachedEffect = null;
  25816. this._cachedVisibility = null;
  25817. };
  25818. /**
  25819. * Registers a function to be called before every frame render
  25820. * @param func defines the function to register
  25821. */
  25822. Scene.prototype.registerBeforeRender = function (func) {
  25823. this.onBeforeRenderObservable.add(func);
  25824. };
  25825. /**
  25826. * Unregisters a function called before every frame render
  25827. * @param func defines the function to unregister
  25828. */
  25829. Scene.prototype.unregisterBeforeRender = function (func) {
  25830. this.onBeforeRenderObservable.removeCallback(func);
  25831. };
  25832. /**
  25833. * Registers a function to be called after every frame render
  25834. * @param func defines the function to register
  25835. */
  25836. Scene.prototype.registerAfterRender = function (func) {
  25837. this.onAfterRenderObservable.add(func);
  25838. };
  25839. /**
  25840. * Unregisters a function called after every frame render
  25841. * @param func defines the function to unregister
  25842. */
  25843. Scene.prototype.unregisterAfterRender = function (func) {
  25844. this.onAfterRenderObservable.removeCallback(func);
  25845. };
  25846. Scene.prototype._executeOnceBeforeRender = function (func) {
  25847. var _this = this;
  25848. var execFunc = function () {
  25849. func();
  25850. setTimeout(function () {
  25851. _this.unregisterBeforeRender(execFunc);
  25852. });
  25853. };
  25854. this.registerBeforeRender(execFunc);
  25855. };
  25856. /**
  25857. * The provided function will run before render once and will be disposed afterwards.
  25858. * A timeout delay can be provided so that the function will be executed in N ms.
  25859. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25860. * @param func The function to be executed.
  25861. * @param timeout optional delay in ms
  25862. */
  25863. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25864. var _this = this;
  25865. if (timeout !== undefined) {
  25866. setTimeout(function () {
  25867. _this._executeOnceBeforeRender(func);
  25868. }, timeout);
  25869. }
  25870. else {
  25871. this._executeOnceBeforeRender(func);
  25872. }
  25873. };
  25874. /** @hidden */
  25875. Scene.prototype._addPendingData = function (data) {
  25876. this._pendingData.push(data);
  25877. };
  25878. /** @hidden */
  25879. Scene.prototype._removePendingData = function (data) {
  25880. var wasLoading = this.isLoading;
  25881. var index = this._pendingData.indexOf(data);
  25882. if (index !== -1) {
  25883. this._pendingData.splice(index, 1);
  25884. }
  25885. if (wasLoading && !this.isLoading) {
  25886. this.onDataLoadedObservable.notifyObservers(this);
  25887. }
  25888. };
  25889. /**
  25890. * Returns the number of items waiting to be loaded
  25891. * @returns the number of items waiting to be loaded
  25892. */
  25893. Scene.prototype.getWaitingItemsCount = function () {
  25894. return this._pendingData.length;
  25895. };
  25896. Object.defineProperty(Scene.prototype, "isLoading", {
  25897. /**
  25898. * Returns a boolean indicating if the scene is still loading data
  25899. */
  25900. get: function () {
  25901. return this._pendingData.length > 0;
  25902. },
  25903. enumerable: true,
  25904. configurable: true
  25905. });
  25906. /**
  25907. * Registers a function to be executed when the scene is ready
  25908. * @param {Function} func - the function to be executed
  25909. */
  25910. Scene.prototype.executeWhenReady = function (func) {
  25911. var _this = this;
  25912. this.onReadyObservable.add(func);
  25913. if (this._executeWhenReadyTimeoutId !== -1) {
  25914. return;
  25915. }
  25916. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25917. _this._checkIsReady();
  25918. }, 150);
  25919. };
  25920. /**
  25921. * Returns a promise that resolves when the scene is ready
  25922. * @returns A promise that resolves when the scene is ready
  25923. */
  25924. Scene.prototype.whenReadyAsync = function () {
  25925. var _this = this;
  25926. return new Promise(function (resolve) {
  25927. _this.executeWhenReady(function () {
  25928. resolve();
  25929. });
  25930. });
  25931. };
  25932. /** @hidden */
  25933. Scene.prototype._checkIsReady = function () {
  25934. var _this = this;
  25935. this._registerTransientComponents();
  25936. if (this.isReady()) {
  25937. this.onReadyObservable.notifyObservers(this);
  25938. this.onReadyObservable.clear();
  25939. this._executeWhenReadyTimeoutId = -1;
  25940. return;
  25941. }
  25942. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25943. _this._checkIsReady();
  25944. }, 150);
  25945. };
  25946. // Animations
  25947. /**
  25948. * Will start the animation sequence of a given target
  25949. * @param target defines the target
  25950. * @param from defines from which frame should animation start
  25951. * @param to defines until which frame should animation run.
  25952. * @param weight defines the weight to apply to the animation (1.0 by default)
  25953. * @param loop defines if the animation loops
  25954. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25955. * @param onAnimationEnd defines the function to be executed when the animation ends
  25956. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25957. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25958. * @returns the animatable object created for this animation
  25959. */
  25960. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25961. if (weight === void 0) { weight = 1.0; }
  25962. if (speedRatio === void 0) { speedRatio = 1.0; }
  25963. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25964. returnedAnimatable.weight = weight;
  25965. return returnedAnimatable;
  25966. };
  25967. /**
  25968. * Will start the animation sequence of a given target
  25969. * @param target defines the target
  25970. * @param from defines from which frame should animation start
  25971. * @param to defines until which frame should animation run.
  25972. * @param loop defines if the animation loops
  25973. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25974. * @param onAnimationEnd defines the function to be executed when the animation ends
  25975. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25976. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25977. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25978. * @returns the animatable object created for this animation
  25979. */
  25980. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25981. if (speedRatio === void 0) { speedRatio = 1.0; }
  25982. if (stopCurrent === void 0) { stopCurrent = true; }
  25983. if (from > to && speedRatio > 0) {
  25984. speedRatio *= -1;
  25985. }
  25986. if (stopCurrent) {
  25987. this.stopAnimation(target, undefined, targetMask);
  25988. }
  25989. if (!animatable) {
  25990. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25991. }
  25992. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25993. // Local animations
  25994. if (target.animations && shouldRunTargetAnimations) {
  25995. animatable.appendAnimations(target, target.animations);
  25996. }
  25997. // Children animations
  25998. if (target.getAnimatables) {
  25999. var animatables = target.getAnimatables();
  26000. for (var index = 0; index < animatables.length; index++) {
  26001. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26002. }
  26003. }
  26004. animatable.reset();
  26005. return animatable;
  26006. };
  26007. /**
  26008. * Begin a new animation on a given node
  26009. * @param target defines the target where the animation will take place
  26010. * @param animations defines the list of animations to start
  26011. * @param from defines the initial value
  26012. * @param to defines the final value
  26013. * @param loop defines if you want animation to loop (off by default)
  26014. * @param speedRatio defines the speed ratio to apply to all animations
  26015. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26016. * @returns the list of created animatables
  26017. */
  26018. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26019. if (speedRatio === undefined) {
  26020. speedRatio = 1.0;
  26021. }
  26022. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26023. return animatable;
  26024. };
  26025. /**
  26026. * Begin a new animation on a given node and its hierarchy
  26027. * @param target defines the root node where the animation will take place
  26028. * @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.
  26029. * @param animations defines the list of animations to start
  26030. * @param from defines the initial value
  26031. * @param to defines the final value
  26032. * @param loop defines if you want animation to loop (off by default)
  26033. * @param speedRatio defines the speed ratio to apply to all animations
  26034. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26035. * @returns the list of animatables created for all nodes
  26036. */
  26037. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26038. var children = target.getDescendants(directDescendantsOnly);
  26039. var result = [];
  26040. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26041. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26042. var child = children_1[_i];
  26043. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26044. }
  26045. return result;
  26046. };
  26047. /**
  26048. * Gets the animatable associated with a specific target
  26049. * @param target defines the target of the animatable
  26050. * @returns the required animatable if found
  26051. */
  26052. Scene.prototype.getAnimatableByTarget = function (target) {
  26053. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26054. if (this._activeAnimatables[index].target === target) {
  26055. return this._activeAnimatables[index];
  26056. }
  26057. }
  26058. return null;
  26059. };
  26060. /**
  26061. * Gets all animatables associated with a given target
  26062. * @param target defines the target to look animatables for
  26063. * @returns an array of Animatables
  26064. */
  26065. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26066. var result = [];
  26067. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26068. if (this._activeAnimatables[index].target === target) {
  26069. result.push(this._activeAnimatables[index]);
  26070. }
  26071. }
  26072. return result;
  26073. };
  26074. Object.defineProperty(Scene.prototype, "animatables", {
  26075. /**
  26076. * Gets all animatable attached to the scene
  26077. */
  26078. get: function () {
  26079. return this._activeAnimatables;
  26080. },
  26081. enumerable: true,
  26082. configurable: true
  26083. });
  26084. /**
  26085. * Will stop the animation of the given target
  26086. * @param target - the target
  26087. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26088. * @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)
  26089. */
  26090. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26091. var animatables = this.getAllAnimatablesByTarget(target);
  26092. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26093. var animatable = animatables_1[_i];
  26094. animatable.stop(animationName, targetMask);
  26095. }
  26096. };
  26097. /**
  26098. * Stops and removes all animations that have been applied to the scene
  26099. */
  26100. Scene.prototype.stopAllAnimations = function () {
  26101. if (this._activeAnimatables) {
  26102. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26103. this._activeAnimatables[i].stop();
  26104. }
  26105. this._activeAnimatables = [];
  26106. }
  26107. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26108. var group = _a[_i];
  26109. group.stop();
  26110. }
  26111. };
  26112. Scene.prototype._animate = function () {
  26113. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26114. return;
  26115. }
  26116. // Getting time
  26117. var now = BABYLON.Tools.Now;
  26118. if (!this._animationTimeLast) {
  26119. if (this._pendingData.length > 0) {
  26120. return;
  26121. }
  26122. this._animationTimeLast = now;
  26123. }
  26124. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26125. this._animationTime += deltaTime;
  26126. this._animationTimeLast = now;
  26127. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26128. this._activeAnimatables[index]._animate(this._animationTime);
  26129. }
  26130. // Late animation bindings
  26131. this._processLateAnimationBindings();
  26132. };
  26133. /** @hidden */
  26134. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26135. var target = runtimeAnimation.target;
  26136. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26137. if (!target._lateAnimationHolders) {
  26138. target._lateAnimationHolders = {};
  26139. }
  26140. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26141. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26142. totalWeight: 0,
  26143. animations: [],
  26144. originalValue: originalValue
  26145. };
  26146. }
  26147. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26148. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26149. };
  26150. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26151. var normalizer = 1.0;
  26152. var finalPosition = BABYLON.Tmp.Vector3[0];
  26153. var finalScaling = BABYLON.Tmp.Vector3[1];
  26154. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26155. var startIndex = 0;
  26156. var originalAnimation = holder.animations[0];
  26157. var originalValue = holder.originalValue;
  26158. var scale = 1;
  26159. if (holder.totalWeight < 1.0) {
  26160. // We need to mix the original value in
  26161. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26162. scale = 1.0 - holder.totalWeight;
  26163. }
  26164. else {
  26165. startIndex = 1;
  26166. // We need to normalize the weights
  26167. normalizer = holder.totalWeight;
  26168. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26169. scale = originalAnimation.weight / normalizer;
  26170. if (scale == 1) {
  26171. return originalAnimation.currentValue;
  26172. }
  26173. }
  26174. finalScaling.scaleInPlace(scale);
  26175. finalPosition.scaleInPlace(scale);
  26176. finalQuaternion.scaleInPlace(scale);
  26177. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26178. var runtimeAnimation = holder.animations[animIndex];
  26179. var scale = runtimeAnimation.weight / normalizer;
  26180. var currentPosition = BABYLON.Tmp.Vector3[2];
  26181. var currentScaling = BABYLON.Tmp.Vector3[3];
  26182. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26183. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26184. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26185. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26186. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26187. }
  26188. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26189. return originalAnimation._workValue;
  26190. };
  26191. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26192. var originalAnimation = holder.animations[0];
  26193. var originalValue = holder.originalValue;
  26194. if (holder.animations.length === 1) {
  26195. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26196. return refQuaternion;
  26197. }
  26198. var normalizer = 1.0;
  26199. var quaternions;
  26200. var weights;
  26201. if (holder.totalWeight < 1.0) {
  26202. var scale = 1.0 - holder.totalWeight;
  26203. quaternions = [];
  26204. weights = [];
  26205. quaternions.push(originalValue);
  26206. weights.push(scale);
  26207. }
  26208. else {
  26209. if (holder.animations.length === 2) { // Slerp as soon as we can
  26210. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26211. return refQuaternion;
  26212. }
  26213. quaternions = [];
  26214. weights = [];
  26215. normalizer = holder.totalWeight;
  26216. }
  26217. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26218. var runtimeAnimation = holder.animations[animIndex];
  26219. quaternions.push(runtimeAnimation.currentValue);
  26220. weights.push(runtimeAnimation.weight / normalizer);
  26221. }
  26222. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26223. var cumulativeAmount = 0;
  26224. var cumulativeQuaternion = null;
  26225. for (var index = 0; index < quaternions.length;) {
  26226. if (!cumulativeQuaternion) {
  26227. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26228. cumulativeQuaternion = refQuaternion;
  26229. cumulativeAmount = weights[index] + weights[index + 1];
  26230. index += 2;
  26231. continue;
  26232. }
  26233. cumulativeAmount += weights[index];
  26234. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26235. index++;
  26236. }
  26237. return cumulativeQuaternion;
  26238. };
  26239. Scene.prototype._processLateAnimationBindings = function () {
  26240. if (!this._registeredForLateAnimationBindings.length) {
  26241. return;
  26242. }
  26243. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26244. var target = this._registeredForLateAnimationBindings.data[index];
  26245. for (var path in target._lateAnimationHolders) {
  26246. var holder = target._lateAnimationHolders[path];
  26247. var originalAnimation = holder.animations[0];
  26248. var originalValue = holder.originalValue;
  26249. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26250. var finalValue = target[path];
  26251. if (matrixDecomposeMode) {
  26252. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26253. }
  26254. else {
  26255. var quaternionMode = originalValue.w !== undefined;
  26256. if (quaternionMode) {
  26257. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26258. }
  26259. else {
  26260. var startIndex = 0;
  26261. var normalizer = 1.0;
  26262. if (holder.totalWeight < 1.0) {
  26263. // We need to mix the original value in
  26264. if (originalValue.scale) {
  26265. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26266. }
  26267. else {
  26268. finalValue = originalValue * (1.0 - holder.totalWeight);
  26269. }
  26270. }
  26271. else {
  26272. // We need to normalize the weights
  26273. normalizer = holder.totalWeight;
  26274. var scale_1 = originalAnimation.weight / normalizer;
  26275. if (scale_1 !== 1) {
  26276. if (originalAnimation.currentValue.scale) {
  26277. finalValue = originalAnimation.currentValue.scale(scale_1);
  26278. }
  26279. else {
  26280. finalValue = originalAnimation.currentValue * scale_1;
  26281. }
  26282. }
  26283. else {
  26284. finalValue = originalAnimation.currentValue;
  26285. }
  26286. startIndex = 1;
  26287. }
  26288. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26289. var runtimeAnimation = holder.animations[animIndex];
  26290. var scale = runtimeAnimation.weight / normalizer;
  26291. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26292. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26293. }
  26294. else {
  26295. finalValue += runtimeAnimation.currentValue * scale;
  26296. }
  26297. }
  26298. }
  26299. }
  26300. target[path] = finalValue;
  26301. }
  26302. target._lateAnimationHolders = {};
  26303. }
  26304. this._registeredForLateAnimationBindings.reset();
  26305. };
  26306. // Matrix
  26307. /** @hidden */
  26308. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26309. this._useAlternateCameraConfiguration = active;
  26310. };
  26311. /**
  26312. * Gets the current view matrix
  26313. * @returns a Matrix
  26314. */
  26315. Scene.prototype.getViewMatrix = function () {
  26316. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26317. };
  26318. /**
  26319. * Gets the current projection matrix
  26320. * @returns a Matrix
  26321. */
  26322. Scene.prototype.getProjectionMatrix = function () {
  26323. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26324. };
  26325. /**
  26326. * Gets the current transform matrix
  26327. * @returns a Matrix made of View * Projection
  26328. */
  26329. Scene.prototype.getTransformMatrix = function () {
  26330. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26331. };
  26332. /**
  26333. * Sets the current transform matrix
  26334. * @param view defines the View matrix to use
  26335. * @param projection defines the Projection matrix to use
  26336. */
  26337. Scene.prototype.setTransformMatrix = function (view, projection) {
  26338. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26339. return;
  26340. }
  26341. this._viewUpdateFlag = view.updateFlag;
  26342. this._projectionUpdateFlag = projection.updateFlag;
  26343. this._viewMatrix = view;
  26344. this._projectionMatrix = projection;
  26345. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26346. // Update frustum
  26347. if (!this._frustumPlanes) {
  26348. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26349. }
  26350. else {
  26351. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26352. }
  26353. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26354. var otherCamera = this.activeCamera._alternateCamera;
  26355. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26356. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26357. }
  26358. if (this._sceneUbo.useUbo) {
  26359. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26360. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26361. this._sceneUbo.update();
  26362. }
  26363. };
  26364. /** @hidden */
  26365. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26366. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26367. return;
  26368. }
  26369. this._alternateViewUpdateFlag = view.updateFlag;
  26370. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26371. this._alternateViewMatrix = view;
  26372. this._alternateProjectionMatrix = projection;
  26373. if (!this._alternateTransformMatrix) {
  26374. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26375. }
  26376. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26377. if (!this._alternateSceneUbo) {
  26378. this._createAlternateUbo();
  26379. }
  26380. if (this._alternateSceneUbo.useUbo) {
  26381. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26382. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26383. this._alternateSceneUbo.update();
  26384. }
  26385. };
  26386. /**
  26387. * Gets the uniform buffer used to store scene data
  26388. * @returns a UniformBuffer
  26389. */
  26390. Scene.prototype.getSceneUniformBuffer = function () {
  26391. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26392. };
  26393. /**
  26394. * Gets an unique (relatively to the current scene) Id
  26395. * @returns an unique number for the scene
  26396. */
  26397. Scene.prototype.getUniqueId = function () {
  26398. var result = Scene._uniqueIdCounter;
  26399. Scene._uniqueIdCounter++;
  26400. return result;
  26401. };
  26402. /**
  26403. * Add a mesh to the list of scene's meshes
  26404. * @param newMesh defines the mesh to add
  26405. * @param recursive if all child meshes should also be added to the scene
  26406. */
  26407. Scene.prototype.addMesh = function (newMesh, recursive) {
  26408. var _this = this;
  26409. if (recursive === void 0) { recursive = false; }
  26410. this.meshes.push(newMesh);
  26411. //notify the collision coordinator
  26412. if (this.collisionCoordinator) {
  26413. this.collisionCoordinator.onMeshAdded(newMesh);
  26414. }
  26415. newMesh._resyncLightSources();
  26416. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26417. if (recursive) {
  26418. newMesh.getChildMeshes().forEach(function (m) {
  26419. _this.addMesh(m);
  26420. });
  26421. }
  26422. };
  26423. /**
  26424. * Remove a mesh for the list of scene's meshes
  26425. * @param toRemove defines the mesh to remove
  26426. * @param recursive if all child meshes should also be removed from the scene
  26427. * @returns the index where the mesh was in the mesh list
  26428. */
  26429. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26430. var _this = this;
  26431. if (recursive === void 0) { recursive = false; }
  26432. var index = this.meshes.indexOf(toRemove);
  26433. if (index !== -1) {
  26434. // Remove from the scene if mesh found
  26435. this.meshes.splice(index, 1);
  26436. }
  26437. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26438. if (recursive) {
  26439. toRemove.getChildMeshes().forEach(function (m) {
  26440. _this.removeMesh(m);
  26441. });
  26442. }
  26443. return index;
  26444. };
  26445. /**
  26446. * Add a transform node to the list of scene's transform nodes
  26447. * @param newTransformNode defines the transform node to add
  26448. */
  26449. Scene.prototype.addTransformNode = function (newTransformNode) {
  26450. this.transformNodes.push(newTransformNode);
  26451. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26452. };
  26453. /**
  26454. * Remove a transform node for the list of scene's transform nodes
  26455. * @param toRemove defines the transform node to remove
  26456. * @returns the index where the transform node was in the transform node list
  26457. */
  26458. Scene.prototype.removeTransformNode = function (toRemove) {
  26459. var index = this.transformNodes.indexOf(toRemove);
  26460. if (index !== -1) {
  26461. // Remove from the scene if found
  26462. this.transformNodes.splice(index, 1);
  26463. }
  26464. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26465. return index;
  26466. };
  26467. /**
  26468. * Remove a skeleton for the list of scene's skeletons
  26469. * @param toRemove defines the skeleton to remove
  26470. * @returns the index where the skeleton was in the skeleton list
  26471. */
  26472. Scene.prototype.removeSkeleton = function (toRemove) {
  26473. var index = this.skeletons.indexOf(toRemove);
  26474. if (index !== -1) {
  26475. // Remove from the scene if found
  26476. this.skeletons.splice(index, 1);
  26477. }
  26478. return index;
  26479. };
  26480. /**
  26481. * Remove a morph target for the list of scene's morph targets
  26482. * @param toRemove defines the morph target to remove
  26483. * @returns the index where the morph target was in the morph target list
  26484. */
  26485. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26486. var index = this.morphTargetManagers.indexOf(toRemove);
  26487. if (index !== -1) {
  26488. // Remove from the scene if found
  26489. this.morphTargetManagers.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Remove a light for the list of scene's lights
  26495. * @param toRemove defines the light to remove
  26496. * @returns the index where the light was in the light list
  26497. */
  26498. Scene.prototype.removeLight = function (toRemove) {
  26499. var index = this.lights.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. // Remove from meshes
  26502. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26503. var mesh = _a[_i];
  26504. mesh._removeLightSource(toRemove);
  26505. }
  26506. // Remove from the scene if mesh found
  26507. this.lights.splice(index, 1);
  26508. this.sortLightsByPriority();
  26509. }
  26510. this.onLightRemovedObservable.notifyObservers(toRemove);
  26511. return index;
  26512. };
  26513. /**
  26514. * Remove a camera for the list of scene's cameras
  26515. * @param toRemove defines the camera to remove
  26516. * @returns the index where the camera was in the camera list
  26517. */
  26518. Scene.prototype.removeCamera = function (toRemove) {
  26519. var index = this.cameras.indexOf(toRemove);
  26520. if (index !== -1) {
  26521. // Remove from the scene if mesh found
  26522. this.cameras.splice(index, 1);
  26523. }
  26524. // Remove from activeCameras
  26525. var index2 = this.activeCameras.indexOf(toRemove);
  26526. if (index2 !== -1) {
  26527. // Remove from the scene if mesh found
  26528. this.activeCameras.splice(index2, 1);
  26529. }
  26530. // Reset the activeCamera
  26531. if (this.activeCamera === toRemove) {
  26532. if (this.cameras.length > 0) {
  26533. this.activeCamera = this.cameras[0];
  26534. }
  26535. else {
  26536. this.activeCamera = null;
  26537. }
  26538. }
  26539. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26540. return index;
  26541. };
  26542. /**
  26543. * Remove a particle system for the list of scene's particle systems
  26544. * @param toRemove defines the particle system to remove
  26545. * @returns the index where the particle system was in the particle system list
  26546. */
  26547. Scene.prototype.removeParticleSystem = function (toRemove) {
  26548. var index = this.particleSystems.indexOf(toRemove);
  26549. if (index !== -1) {
  26550. this.particleSystems.splice(index, 1);
  26551. }
  26552. return index;
  26553. };
  26554. /**
  26555. * Remove a animation for the list of scene's animations
  26556. * @param toRemove defines the animation to remove
  26557. * @returns the index where the animation was in the animation list
  26558. */
  26559. Scene.prototype.removeAnimation = function (toRemove) {
  26560. var index = this.animations.indexOf(toRemove);
  26561. if (index !== -1) {
  26562. this.animations.splice(index, 1);
  26563. }
  26564. return index;
  26565. };
  26566. /**
  26567. * Removes the given animation group from this scene.
  26568. * @param toRemove The animation group to remove
  26569. * @returns The index of the removed animation group
  26570. */
  26571. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26572. var index = this.animationGroups.indexOf(toRemove);
  26573. if (index !== -1) {
  26574. this.animationGroups.splice(index, 1);
  26575. }
  26576. return index;
  26577. };
  26578. /**
  26579. * Removes the given multi-material from this scene.
  26580. * @param toRemove The multi-material to remove
  26581. * @returns The index of the removed multi-material
  26582. */
  26583. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26584. var index = this.multiMaterials.indexOf(toRemove);
  26585. if (index !== -1) {
  26586. this.multiMaterials.splice(index, 1);
  26587. }
  26588. return index;
  26589. };
  26590. /**
  26591. * Removes the given material from this scene.
  26592. * @param toRemove The material to remove
  26593. * @returns The index of the removed material
  26594. */
  26595. Scene.prototype.removeMaterial = function (toRemove) {
  26596. var index = this.materials.indexOf(toRemove);
  26597. if (index !== -1) {
  26598. this.materials.splice(index, 1);
  26599. }
  26600. return index;
  26601. };
  26602. /**
  26603. * Removes the given action manager from this scene.
  26604. * @param toRemove The action manager to remove
  26605. * @returns The index of the removed action manager
  26606. */
  26607. Scene.prototype.removeActionManager = function (toRemove) {
  26608. var index = this.actionManagers.indexOf(toRemove);
  26609. if (index !== -1) {
  26610. this.actionManagers.splice(index, 1);
  26611. }
  26612. return index;
  26613. };
  26614. /**
  26615. * Removes the given texture from this scene.
  26616. * @param toRemove The texture to remove
  26617. * @returns The index of the removed texture
  26618. */
  26619. Scene.prototype.removeTexture = function (toRemove) {
  26620. var index = this.textures.indexOf(toRemove);
  26621. if (index !== -1) {
  26622. this.textures.splice(index, 1);
  26623. }
  26624. return index;
  26625. };
  26626. /**
  26627. * Adds the given light to this scene
  26628. * @param newLight The light to add
  26629. */
  26630. Scene.prototype.addLight = function (newLight) {
  26631. this.lights.push(newLight);
  26632. this.sortLightsByPriority();
  26633. // Add light to all meshes (To support if the light is removed and then readded)
  26634. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26635. var mesh = _a[_i];
  26636. if (mesh._lightSources.indexOf(newLight) === -1) {
  26637. mesh._lightSources.push(newLight);
  26638. mesh._resyncLightSources();
  26639. }
  26640. }
  26641. this.onNewLightAddedObservable.notifyObservers(newLight);
  26642. };
  26643. /**
  26644. * Sorts the list list based on light priorities
  26645. */
  26646. Scene.prototype.sortLightsByPriority = function () {
  26647. if (this.requireLightSorting) {
  26648. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26649. }
  26650. };
  26651. /**
  26652. * Adds the given camera to this scene
  26653. * @param newCamera The camera to add
  26654. */
  26655. Scene.prototype.addCamera = function (newCamera) {
  26656. this.cameras.push(newCamera);
  26657. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26658. };
  26659. /**
  26660. * Adds the given skeleton to this scene
  26661. * @param newSkeleton The skeleton to add
  26662. */
  26663. Scene.prototype.addSkeleton = function (newSkeleton) {
  26664. this.skeletons.push(newSkeleton);
  26665. };
  26666. /**
  26667. * Adds the given particle system to this scene
  26668. * @param newParticleSystem The particle system to add
  26669. */
  26670. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26671. this.particleSystems.push(newParticleSystem);
  26672. };
  26673. /**
  26674. * Adds the given animation to this scene
  26675. * @param newAnimation The animation to add
  26676. */
  26677. Scene.prototype.addAnimation = function (newAnimation) {
  26678. this.animations.push(newAnimation);
  26679. };
  26680. /**
  26681. * Adds the given animation group to this scene.
  26682. * @param newAnimationGroup The animation group to add
  26683. */
  26684. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26685. this.animationGroups.push(newAnimationGroup);
  26686. };
  26687. /**
  26688. * Adds the given multi-material to this scene
  26689. * @param newMultiMaterial The multi-material to add
  26690. */
  26691. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26692. this.multiMaterials.push(newMultiMaterial);
  26693. };
  26694. /**
  26695. * Adds the given material to this scene
  26696. * @param newMaterial The material to add
  26697. */
  26698. Scene.prototype.addMaterial = function (newMaterial) {
  26699. this.materials.push(newMaterial);
  26700. };
  26701. /**
  26702. * Adds the given morph target to this scene
  26703. * @param newMorphTargetManager The morph target to add
  26704. */
  26705. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26706. this.morphTargetManagers.push(newMorphTargetManager);
  26707. };
  26708. /**
  26709. * Adds the given geometry to this scene
  26710. * @param newGeometry The geometry to add
  26711. */
  26712. Scene.prototype.addGeometry = function (newGeometry) {
  26713. this.geometries.push(newGeometry);
  26714. };
  26715. /**
  26716. * Adds the given action manager to this scene
  26717. * @param newActionManager The action manager to add
  26718. */
  26719. Scene.prototype.addActionManager = function (newActionManager) {
  26720. this.actionManagers.push(newActionManager);
  26721. };
  26722. /**
  26723. * Adds the given texture to this scene.
  26724. * @param newTexture The texture to add
  26725. */
  26726. Scene.prototype.addTexture = function (newTexture) {
  26727. this.textures.push(newTexture);
  26728. };
  26729. /**
  26730. * Switch active camera
  26731. * @param newCamera defines the new active camera
  26732. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26733. */
  26734. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26735. if (attachControl === void 0) { attachControl = true; }
  26736. var canvas = this._engine.getRenderingCanvas();
  26737. if (!canvas) {
  26738. return;
  26739. }
  26740. if (this.activeCamera) {
  26741. this.activeCamera.detachControl(canvas);
  26742. }
  26743. this.activeCamera = newCamera;
  26744. if (attachControl) {
  26745. newCamera.attachControl(canvas);
  26746. }
  26747. };
  26748. /**
  26749. * sets the active camera of the scene using its ID
  26750. * @param id defines the camera's ID
  26751. * @return the new active camera or null if none found.
  26752. */
  26753. Scene.prototype.setActiveCameraByID = function (id) {
  26754. var camera = this.getCameraByID(id);
  26755. if (camera) {
  26756. this.activeCamera = camera;
  26757. return camera;
  26758. }
  26759. return null;
  26760. };
  26761. /**
  26762. * sets the active camera of the scene using its name
  26763. * @param name defines the camera's name
  26764. * @returns the new active camera or null if none found.
  26765. */
  26766. Scene.prototype.setActiveCameraByName = function (name) {
  26767. var camera = this.getCameraByName(name);
  26768. if (camera) {
  26769. this.activeCamera = camera;
  26770. return camera;
  26771. }
  26772. return null;
  26773. };
  26774. /**
  26775. * get an animation group using its name
  26776. * @param name defines the material's name
  26777. * @return the animation group or null if none found.
  26778. */
  26779. Scene.prototype.getAnimationGroupByName = function (name) {
  26780. for (var index = 0; index < this.animationGroups.length; index++) {
  26781. if (this.animationGroups[index].name === name) {
  26782. return this.animationGroups[index];
  26783. }
  26784. }
  26785. return null;
  26786. };
  26787. /**
  26788. * get a material using its id
  26789. * @param id defines the material's ID
  26790. * @return the material or null if none found.
  26791. */
  26792. Scene.prototype.getMaterialByID = function (id) {
  26793. for (var index = 0; index < this.materials.length; index++) {
  26794. if (this.materials[index].id === id) {
  26795. return this.materials[index];
  26796. }
  26797. }
  26798. return null;
  26799. };
  26800. /**
  26801. * Gets a material using its name
  26802. * @param name defines the material's name
  26803. * @return the material or null if none found.
  26804. */
  26805. Scene.prototype.getMaterialByName = function (name) {
  26806. for (var index = 0; index < this.materials.length; index++) {
  26807. if (this.materials[index].name === name) {
  26808. return this.materials[index];
  26809. }
  26810. }
  26811. return null;
  26812. };
  26813. /**
  26814. * Gets a camera using its id
  26815. * @param id defines the id to look for
  26816. * @returns the camera or null if not found
  26817. */
  26818. Scene.prototype.getCameraByID = function (id) {
  26819. for (var index = 0; index < this.cameras.length; index++) {
  26820. if (this.cameras[index].id === id) {
  26821. return this.cameras[index];
  26822. }
  26823. }
  26824. return null;
  26825. };
  26826. /**
  26827. * Gets a camera using its unique id
  26828. * @param uniqueId defines the unique id to look for
  26829. * @returns the camera or null if not found
  26830. */
  26831. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26832. for (var index = 0; index < this.cameras.length; index++) {
  26833. if (this.cameras[index].uniqueId === uniqueId) {
  26834. return this.cameras[index];
  26835. }
  26836. }
  26837. return null;
  26838. };
  26839. /**
  26840. * Gets a camera using its name
  26841. * @param name defines the camera's name
  26842. * @return the camera or null if none found.
  26843. */
  26844. Scene.prototype.getCameraByName = function (name) {
  26845. for (var index = 0; index < this.cameras.length; index++) {
  26846. if (this.cameras[index].name === name) {
  26847. return this.cameras[index];
  26848. }
  26849. }
  26850. return null;
  26851. };
  26852. /**
  26853. * Gets a bone using its id
  26854. * @param id defines the bone's id
  26855. * @return the bone or null if not found
  26856. */
  26857. Scene.prototype.getBoneByID = function (id) {
  26858. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26859. var skeleton = this.skeletons[skeletonIndex];
  26860. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26861. if (skeleton.bones[boneIndex].id === id) {
  26862. return skeleton.bones[boneIndex];
  26863. }
  26864. }
  26865. }
  26866. return null;
  26867. };
  26868. /**
  26869. * Gets a bone using its id
  26870. * @param name defines the bone's name
  26871. * @return the bone or null if not found
  26872. */
  26873. Scene.prototype.getBoneByName = function (name) {
  26874. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26875. var skeleton = this.skeletons[skeletonIndex];
  26876. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26877. if (skeleton.bones[boneIndex].name === name) {
  26878. return skeleton.bones[boneIndex];
  26879. }
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a light node using its name
  26886. * @param name defines the the light's name
  26887. * @return the light or null if none found.
  26888. */
  26889. Scene.prototype.getLightByName = function (name) {
  26890. for (var index = 0; index < this.lights.length; index++) {
  26891. if (this.lights[index].name === name) {
  26892. return this.lights[index];
  26893. }
  26894. }
  26895. return null;
  26896. };
  26897. /**
  26898. * Gets a light node using its id
  26899. * @param id defines the light's id
  26900. * @return the light or null if none found.
  26901. */
  26902. Scene.prototype.getLightByID = function (id) {
  26903. for (var index = 0; index < this.lights.length; index++) {
  26904. if (this.lights[index].id === id) {
  26905. return this.lights[index];
  26906. }
  26907. }
  26908. return null;
  26909. };
  26910. /**
  26911. * Gets a light node using its scene-generated unique ID
  26912. * @param uniqueId defines the light's unique id
  26913. * @return the light or null if none found.
  26914. */
  26915. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26916. for (var index = 0; index < this.lights.length; index++) {
  26917. if (this.lights[index].uniqueId === uniqueId) {
  26918. return this.lights[index];
  26919. }
  26920. }
  26921. return null;
  26922. };
  26923. /**
  26924. * Gets a particle system by id
  26925. * @param id defines the particle system id
  26926. * @return the corresponding system or null if none found
  26927. */
  26928. Scene.prototype.getParticleSystemByID = function (id) {
  26929. for (var index = 0; index < this.particleSystems.length; index++) {
  26930. if (this.particleSystems[index].id === id) {
  26931. return this.particleSystems[index];
  26932. }
  26933. }
  26934. return null;
  26935. };
  26936. /**
  26937. * Gets a geometry using its ID
  26938. * @param id defines the geometry's id
  26939. * @return the geometry or null if none found.
  26940. */
  26941. Scene.prototype.getGeometryByID = function (id) {
  26942. for (var index = 0; index < this.geometries.length; index++) {
  26943. if (this.geometries[index].id === id) {
  26944. return this.geometries[index];
  26945. }
  26946. }
  26947. return null;
  26948. };
  26949. /**
  26950. * Add a new geometry to this scene
  26951. * @param geometry defines the geometry to be added to the scene.
  26952. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26953. * @return a boolean defining if the geometry was added or not
  26954. */
  26955. Scene.prototype.pushGeometry = function (geometry, force) {
  26956. if (!force && this.getGeometryByID(geometry.id)) {
  26957. return false;
  26958. }
  26959. this.geometries.push(geometry);
  26960. //notify the collision coordinator
  26961. if (this.collisionCoordinator) {
  26962. this.collisionCoordinator.onGeometryAdded(geometry);
  26963. }
  26964. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26965. return true;
  26966. };
  26967. /**
  26968. * Removes an existing geometry
  26969. * @param geometry defines the geometry to be removed from the scene
  26970. * @return a boolean defining if the geometry was removed or not
  26971. */
  26972. Scene.prototype.removeGeometry = function (geometry) {
  26973. var index = this.geometries.indexOf(geometry);
  26974. if (index > -1) {
  26975. this.geometries.splice(index, 1);
  26976. //notify the collision coordinator
  26977. if (this.collisionCoordinator) {
  26978. this.collisionCoordinator.onGeometryDeleted(geometry);
  26979. }
  26980. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26981. return true;
  26982. }
  26983. return false;
  26984. };
  26985. /**
  26986. * Gets the list of geometries attached to the scene
  26987. * @returns an array of Geometry
  26988. */
  26989. Scene.prototype.getGeometries = function () {
  26990. return this.geometries;
  26991. };
  26992. /**
  26993. * Gets the first added mesh found of a given ID
  26994. * @param id defines the id to search for
  26995. * @return the mesh found or null if not found at all
  26996. */
  26997. Scene.prototype.getMeshByID = function (id) {
  26998. for (var index = 0; index < this.meshes.length; index++) {
  26999. if (this.meshes[index].id === id) {
  27000. return this.meshes[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a list of meshes using their id
  27007. * @param id defines the id to search for
  27008. * @returns a list of meshes
  27009. */
  27010. Scene.prototype.getMeshesByID = function (id) {
  27011. return this.meshes.filter(function (m) {
  27012. return m.id === id;
  27013. });
  27014. };
  27015. /**
  27016. * Gets the first added transform node found of a given ID
  27017. * @param id defines the id to search for
  27018. * @return the found transform node or null if not found at all.
  27019. */
  27020. Scene.prototype.getTransformNodeByID = function (id) {
  27021. for (var index = 0; index < this.transformNodes.length; index++) {
  27022. if (this.transformNodes[index].id === id) {
  27023. return this.transformNodes[index];
  27024. }
  27025. }
  27026. return null;
  27027. };
  27028. /**
  27029. * Gets a list of transform nodes using their id
  27030. * @param id defines the id to search for
  27031. * @returns a list of transform nodes
  27032. */
  27033. Scene.prototype.getTransformNodesByID = function (id) {
  27034. return this.transformNodes.filter(function (m) {
  27035. return m.id === id;
  27036. });
  27037. };
  27038. /**
  27039. * Gets a mesh with its auto-generated unique id
  27040. * @param uniqueId defines the unique id to search for
  27041. * @return the found mesh or null if not found at all.
  27042. */
  27043. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27044. for (var index = 0; index < this.meshes.length; index++) {
  27045. if (this.meshes[index].uniqueId === uniqueId) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a the last added mesh using a given id
  27053. * @param id defines the id to search for
  27054. * @return the found mesh or null if not found at all.
  27055. */
  27056. Scene.prototype.getLastMeshByID = function (id) {
  27057. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27058. if (this.meshes[index].id === id) {
  27059. return this.meshes[index];
  27060. }
  27061. }
  27062. return null;
  27063. };
  27064. /**
  27065. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27066. * @param id defines the id to search for
  27067. * @return the found node or null if not found at all
  27068. */
  27069. Scene.prototype.getLastEntryByID = function (id) {
  27070. var index;
  27071. for (index = this.meshes.length - 1; index >= 0; index--) {
  27072. if (this.meshes[index].id === id) {
  27073. return this.meshes[index];
  27074. }
  27075. }
  27076. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27077. if (this.transformNodes[index].id === id) {
  27078. return this.transformNodes[index];
  27079. }
  27080. }
  27081. for (index = this.cameras.length - 1; index >= 0; index--) {
  27082. if (this.cameras[index].id === id) {
  27083. return this.cameras[index];
  27084. }
  27085. }
  27086. for (index = this.lights.length - 1; index >= 0; index--) {
  27087. if (this.lights[index].id === id) {
  27088. return this.lights[index];
  27089. }
  27090. }
  27091. return null;
  27092. };
  27093. /**
  27094. * Gets a node (Mesh, Camera, Light) using a given id
  27095. * @param id defines the id to search for
  27096. * @return the found node or null if not found at all
  27097. */
  27098. Scene.prototype.getNodeByID = function (id) {
  27099. var mesh = this.getMeshByID(id);
  27100. if (mesh) {
  27101. return mesh;
  27102. }
  27103. var light = this.getLightByID(id);
  27104. if (light) {
  27105. return light;
  27106. }
  27107. var camera = this.getCameraByID(id);
  27108. if (camera) {
  27109. return camera;
  27110. }
  27111. var bone = this.getBoneByID(id);
  27112. return bone;
  27113. };
  27114. /**
  27115. * Gets a node (Mesh, Camera, Light) using a given name
  27116. * @param name defines the name to search for
  27117. * @return the found node or null if not found at all.
  27118. */
  27119. Scene.prototype.getNodeByName = function (name) {
  27120. var mesh = this.getMeshByName(name);
  27121. if (mesh) {
  27122. return mesh;
  27123. }
  27124. var light = this.getLightByName(name);
  27125. if (light) {
  27126. return light;
  27127. }
  27128. var camera = this.getCameraByName(name);
  27129. if (camera) {
  27130. return camera;
  27131. }
  27132. var bone = this.getBoneByName(name);
  27133. return bone;
  27134. };
  27135. /**
  27136. * Gets a mesh using a given name
  27137. * @param name defines the name to search for
  27138. * @return the found mesh or null if not found at all.
  27139. */
  27140. Scene.prototype.getMeshByName = function (name) {
  27141. for (var index = 0; index < this.meshes.length; index++) {
  27142. if (this.meshes[index].name === name) {
  27143. return this.meshes[index];
  27144. }
  27145. }
  27146. return null;
  27147. };
  27148. /**
  27149. * Gets a transform node using a given name
  27150. * @param name defines the name to search for
  27151. * @return the found transform node or null if not found at all.
  27152. */
  27153. Scene.prototype.getTransformNodeByName = function (name) {
  27154. for (var index = 0; index < this.transformNodes.length; index++) {
  27155. if (this.transformNodes[index].name === name) {
  27156. return this.transformNodes[index];
  27157. }
  27158. }
  27159. return null;
  27160. };
  27161. /**
  27162. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27163. * @param id defines the id to search for
  27164. * @return the found skeleton or null if not found at all.
  27165. */
  27166. Scene.prototype.getLastSkeletonByID = function (id) {
  27167. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27168. if (this.skeletons[index].id === id) {
  27169. return this.skeletons[index];
  27170. }
  27171. }
  27172. return null;
  27173. };
  27174. /**
  27175. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27176. * @param id defines the id to search for
  27177. * @return the found skeleton or null if not found at all.
  27178. */
  27179. Scene.prototype.getSkeletonById = function (id) {
  27180. for (var index = 0; index < this.skeletons.length; index++) {
  27181. if (this.skeletons[index].id === id) {
  27182. return this.skeletons[index];
  27183. }
  27184. }
  27185. return null;
  27186. };
  27187. /**
  27188. * Gets a skeleton using a given name
  27189. * @param name defines the name to search for
  27190. * @return the found skeleton or null if not found at all.
  27191. */
  27192. Scene.prototype.getSkeletonByName = function (name) {
  27193. for (var index = 0; index < this.skeletons.length; index++) {
  27194. if (this.skeletons[index].name === name) {
  27195. return this.skeletons[index];
  27196. }
  27197. }
  27198. return null;
  27199. };
  27200. /**
  27201. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27202. * @param id defines the id to search for
  27203. * @return the found morph target manager or null if not found at all.
  27204. */
  27205. Scene.prototype.getMorphTargetManagerById = function (id) {
  27206. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27207. if (this.morphTargetManagers[index].uniqueId === id) {
  27208. return this.morphTargetManagers[index];
  27209. }
  27210. }
  27211. return null;
  27212. };
  27213. /**
  27214. * Gets a boolean indicating if the given mesh is active
  27215. * @param mesh defines the mesh to look for
  27216. * @returns true if the mesh is in the active list
  27217. */
  27218. Scene.prototype.isActiveMesh = function (mesh) {
  27219. return (this._activeMeshes.indexOf(mesh) !== -1);
  27220. };
  27221. Object.defineProperty(Scene.prototype, "uid", {
  27222. /**
  27223. * Return a unique id as a string which can serve as an identifier for the scene
  27224. */
  27225. get: function () {
  27226. if (!this._uid) {
  27227. this._uid = BABYLON.Tools.RandomId();
  27228. }
  27229. return this._uid;
  27230. },
  27231. enumerable: true,
  27232. configurable: true
  27233. });
  27234. /**
  27235. * Add an externaly attached data from its key.
  27236. * This method call will fail and return false, if such key already exists.
  27237. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27238. * @param key the unique key that identifies the data
  27239. * @param data the data object to associate to the key for this Engine instance
  27240. * @return true if no such key were already present and the data was added successfully, false otherwise
  27241. */
  27242. Scene.prototype.addExternalData = function (key, data) {
  27243. if (!this._externalData) {
  27244. this._externalData = new BABYLON.StringDictionary();
  27245. }
  27246. return this._externalData.add(key, data);
  27247. };
  27248. /**
  27249. * Get an externaly attached data from its key
  27250. * @param key the unique key that identifies the data
  27251. * @return the associated data, if present (can be null), or undefined if not present
  27252. */
  27253. Scene.prototype.getExternalData = function (key) {
  27254. if (!this._externalData) {
  27255. return null;
  27256. }
  27257. return this._externalData.get(key);
  27258. };
  27259. /**
  27260. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27261. * @param key the unique key that identifies the data
  27262. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27263. * @return the associated data, can be null if the factory returned null.
  27264. */
  27265. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27266. if (!this._externalData) {
  27267. this._externalData = new BABYLON.StringDictionary();
  27268. }
  27269. return this._externalData.getOrAddWithFactory(key, factory);
  27270. };
  27271. /**
  27272. * Remove an externaly attached data from the Engine instance
  27273. * @param key the unique key that identifies the data
  27274. * @return true if the data was successfully removed, false if it doesn't exist
  27275. */
  27276. Scene.prototype.removeExternalData = function (key) {
  27277. return this._externalData.remove(key);
  27278. };
  27279. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27280. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27281. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27282. var step = _a[_i];
  27283. step.action(mesh, subMesh);
  27284. }
  27285. var material = subMesh.getMaterial();
  27286. if (material !== null && material !== undefined) {
  27287. // Render targets
  27288. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27289. if (this._processedMaterials.indexOf(material) === -1) {
  27290. this._processedMaterials.push(material);
  27291. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27292. }
  27293. }
  27294. // Dispatch
  27295. this._activeIndices.addCount(subMesh.indexCount, false);
  27296. this._renderingManager.dispatch(subMesh, mesh, material);
  27297. }
  27298. }
  27299. };
  27300. /**
  27301. * Clear the processed materials smart array preventing retention point in material dispose.
  27302. */
  27303. Scene.prototype.freeProcessedMaterials = function () {
  27304. this._processedMaterials.dispose();
  27305. };
  27306. /**
  27307. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27308. */
  27309. Scene.prototype.freeActiveMeshes = function () {
  27310. this._activeMeshes.dispose();
  27311. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27312. this.activeCamera._activeMeshes.dispose();
  27313. }
  27314. if (this.activeCameras) {
  27315. for (var i = 0; i < this.activeCameras.length; i++) {
  27316. var activeCamera = this.activeCameras[i];
  27317. if (activeCamera && activeCamera._activeMeshes) {
  27318. activeCamera._activeMeshes.dispose();
  27319. }
  27320. }
  27321. }
  27322. };
  27323. /**
  27324. * Clear the info related to rendering groups preventing retention points during dispose.
  27325. */
  27326. Scene.prototype.freeRenderingGroups = function () {
  27327. if (this._renderingManager) {
  27328. this._renderingManager.freeRenderingGroups();
  27329. }
  27330. if (this.textures) {
  27331. for (var i = 0; i < this.textures.length; i++) {
  27332. var texture = this.textures[i];
  27333. if (texture && texture.renderList) {
  27334. texture.freeRenderingGroups();
  27335. }
  27336. }
  27337. }
  27338. };
  27339. /** @hidden */
  27340. Scene.prototype._isInIntermediateRendering = function () {
  27341. return this._intermediateRendering;
  27342. };
  27343. /**
  27344. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27345. * @returns the current scene
  27346. */
  27347. Scene.prototype.freezeActiveMeshes = function () {
  27348. if (!this.activeCamera) {
  27349. return this;
  27350. }
  27351. if (!this._frustumPlanes) {
  27352. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27353. }
  27354. this._evaluateActiveMeshes();
  27355. this._activeMeshesFrozen = true;
  27356. return this;
  27357. };
  27358. /**
  27359. * Use this function to restart evaluating active meshes on every frame
  27360. * @returns the current scene
  27361. */
  27362. Scene.prototype.unfreezeActiveMeshes = function () {
  27363. this._activeMeshesFrozen = false;
  27364. return this;
  27365. };
  27366. Scene.prototype._evaluateActiveMeshes = function () {
  27367. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27368. return;
  27369. }
  27370. if (!this.activeCamera) {
  27371. return;
  27372. }
  27373. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27374. this.activeCamera._activeMeshes.reset();
  27375. this._activeMeshes.reset();
  27376. this._renderingManager.reset();
  27377. this._processedMaterials.reset();
  27378. this._activeParticleSystems.reset();
  27379. this._activeSkeletons.reset();
  27380. this._softwareSkinnedMeshes.reset();
  27381. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27382. var step = _a[_i];
  27383. step.action();
  27384. }
  27385. // Determine mesh candidates
  27386. var meshes = this.getActiveMeshCandidates();
  27387. // Check each mesh
  27388. var len = meshes.length;
  27389. for (var i = 0; i < len; i++) {
  27390. var mesh = meshes.data[i];
  27391. if (mesh.isBlocked) {
  27392. continue;
  27393. }
  27394. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27395. if (!mesh.isReady() || !mesh.isEnabled()) {
  27396. continue;
  27397. }
  27398. mesh.computeWorldMatrix();
  27399. // Intersections
  27400. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27401. this._meshesForIntersections.pushNoDuplicate(mesh);
  27402. }
  27403. // Switch to current LOD
  27404. var meshLOD = mesh.getLOD(this.activeCamera);
  27405. if (meshLOD === undefined || meshLOD === null) {
  27406. continue;
  27407. }
  27408. mesh._preActivate();
  27409. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27410. this._activeMeshes.push(mesh);
  27411. this.activeCamera._activeMeshes.push(mesh);
  27412. mesh._activate(this._renderId);
  27413. if (meshLOD !== mesh) {
  27414. meshLOD._activate(this._renderId);
  27415. }
  27416. this._activeMesh(mesh, meshLOD);
  27417. }
  27418. }
  27419. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27420. // Particle systems
  27421. if (this.particlesEnabled) {
  27422. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27423. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27424. var particleSystem = this.particleSystems[particleIndex];
  27425. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27426. continue;
  27427. }
  27428. var emitter = particleSystem.emitter;
  27429. if (!emitter.position || emitter.isEnabled()) {
  27430. this._activeParticleSystems.push(particleSystem);
  27431. particleSystem.animate();
  27432. this._renderingManager.dispatchParticles(particleSystem);
  27433. }
  27434. }
  27435. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27436. }
  27437. };
  27438. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27439. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27440. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27441. mesh.skeleton.prepare();
  27442. }
  27443. if (!mesh.computeBonesUsingShaders) {
  27444. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27445. }
  27446. }
  27447. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27448. var step = _a[_i];
  27449. step.action(sourceMesh, mesh);
  27450. }
  27451. if (mesh !== undefined && mesh !== null
  27452. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27453. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27454. var len = subMeshes.length;
  27455. for (var i = 0; i < len; i++) {
  27456. var subMesh = subMeshes.data[i];
  27457. this._evaluateSubMesh(subMesh, mesh);
  27458. }
  27459. }
  27460. };
  27461. /**
  27462. * Update the transform matrix to update from the current active camera
  27463. * @param force defines a boolean used to force the update even if cache is up to date
  27464. */
  27465. Scene.prototype.updateTransformMatrix = function (force) {
  27466. if (!this.activeCamera) {
  27467. return;
  27468. }
  27469. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27470. };
  27471. /**
  27472. * 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)
  27473. * @param alternateCamera defines the camera to use
  27474. */
  27475. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27476. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27477. };
  27478. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27479. if (camera && camera._skipRendering) {
  27480. return;
  27481. }
  27482. var engine = this._engine;
  27483. this.activeCamera = camera;
  27484. if (!this.activeCamera)
  27485. throw new Error("Active camera not set");
  27486. // Viewport
  27487. engine.setViewport(this.activeCamera.viewport);
  27488. // Camera
  27489. this.resetCachedMaterial();
  27490. this._renderId++;
  27491. this.updateTransformMatrix();
  27492. if (camera._alternateCamera) {
  27493. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27494. this._alternateRendering = true;
  27495. }
  27496. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27497. // Meshes
  27498. this._evaluateActiveMeshes();
  27499. // Software skinning
  27500. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27501. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27502. mesh.applySkeleton(mesh.skeleton);
  27503. }
  27504. // Render targets
  27505. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27506. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27507. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27508. }
  27509. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27510. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27511. }
  27512. // Collects render targets from external components.
  27513. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27514. var step = _a[_i];
  27515. step.action(this._renderTargets);
  27516. }
  27517. if (this.renderTargetsEnabled) {
  27518. this._intermediateRendering = true;
  27519. if (this._renderTargets.length > 0) {
  27520. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27521. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27522. var renderTarget = this._renderTargets.data[renderIndex];
  27523. if (renderTarget._shouldRender()) {
  27524. this._renderId++;
  27525. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27526. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27527. }
  27528. }
  27529. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27530. this._renderId++;
  27531. }
  27532. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27533. var step = _c[_b];
  27534. step.action(this.activeCamera);
  27535. }
  27536. this._intermediateRendering = false;
  27537. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27538. }
  27539. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27540. // Prepare Frame
  27541. if (this.postProcessManager) {
  27542. this.postProcessManager._prepareFrame();
  27543. }
  27544. // Before Camera Draw
  27545. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27546. var step = _e[_d];
  27547. step.action(this.activeCamera);
  27548. }
  27549. // Render
  27550. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27551. this._renderingManager.render(null, null, true, true);
  27552. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27553. // After Camera Draw
  27554. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27555. var step = _g[_f];
  27556. step.action(this.activeCamera);
  27557. }
  27558. // Finalize frame
  27559. if (this.postProcessManager) {
  27560. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27561. }
  27562. // Reset some special arrays
  27563. this._renderTargets.reset();
  27564. this._alternateRendering = false;
  27565. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27566. };
  27567. Scene.prototype._processSubCameras = function (camera) {
  27568. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27569. this._renderForCamera(camera);
  27570. return;
  27571. }
  27572. // rig cameras
  27573. for (var index = 0; index < camera._rigCameras.length; index++) {
  27574. this._renderForCamera(camera._rigCameras[index], camera);
  27575. }
  27576. this.activeCamera = camera;
  27577. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27578. };
  27579. Scene.prototype._checkIntersections = function () {
  27580. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27581. var sourceMesh = this._meshesForIntersections.data[index];
  27582. if (!sourceMesh.actionManager) {
  27583. continue;
  27584. }
  27585. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27586. var action = sourceMesh.actionManager.actions[actionIndex];
  27587. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27588. var parameters = action.getTriggerParameter();
  27589. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27590. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27591. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27592. if (areIntersecting && currentIntersectionInProgress === -1) {
  27593. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27594. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27595. sourceMesh._intersectionsInProgress.push(otherMesh);
  27596. }
  27597. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27598. sourceMesh._intersectionsInProgress.push(otherMesh);
  27599. }
  27600. }
  27601. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27602. //They intersected, and now they don't.
  27603. //is this trigger an exit trigger? execute an event.
  27604. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27605. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27606. }
  27607. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27608. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27609. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27610. return otherMesh === parameterMesh;
  27611. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27612. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27613. }
  27614. }
  27615. }
  27616. }
  27617. }
  27618. };
  27619. /** @hidden */
  27620. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27621. // Do nothing. Code will be replaced if physics engine component is referenced
  27622. };
  27623. /**
  27624. * Render the scene
  27625. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27626. */
  27627. Scene.prototype.render = function (updateCameras) {
  27628. if (updateCameras === void 0) { updateCameras = true; }
  27629. if (this.isDisposed) {
  27630. return;
  27631. }
  27632. this._frameId++;
  27633. // Register components that have been associated lately to the scene.
  27634. this._registerTransientComponents();
  27635. this._activeParticles.fetchNewFrame();
  27636. this._totalVertices.fetchNewFrame();
  27637. this._activeIndices.fetchNewFrame();
  27638. this._activeBones.fetchNewFrame();
  27639. this._meshesForIntersections.reset();
  27640. this.resetCachedMaterial();
  27641. this.onBeforeAnimationsObservable.notifyObservers(this);
  27642. // Actions
  27643. if (this.actionManager) {
  27644. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27645. }
  27646. if (this._engine.isDeterministicLockStep()) {
  27647. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27648. var defaultFPS = (60.0 / 1000.0);
  27649. var defaultFrameTime = this.getDeterministicFrameTime();
  27650. var stepsTaken = 0;
  27651. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27652. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27653. internalSteps = Math.min(internalSteps, maxSubSteps);
  27654. do {
  27655. this.onBeforeStepObservable.notifyObservers(this);
  27656. // Animations
  27657. this._animationRatio = defaultFrameTime * defaultFPS;
  27658. this._animate();
  27659. this.onAfterAnimationsObservable.notifyObservers(this);
  27660. // Physics
  27661. this._advancePhysicsEngineStep(defaultFrameTime);
  27662. this.onAfterStepObservable.notifyObservers(this);
  27663. this._currentStepId++;
  27664. stepsTaken++;
  27665. deltaTime -= defaultFrameTime;
  27666. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27667. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27668. }
  27669. else {
  27670. // Animations
  27671. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27672. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27673. this._animate();
  27674. this.onAfterAnimationsObservable.notifyObservers(this);
  27675. // Physics
  27676. this._advancePhysicsEngineStep(deltaTime);
  27677. }
  27678. // Before camera update steps
  27679. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27680. var step = _a[_i];
  27681. step.action();
  27682. }
  27683. // Update Cameras
  27684. if (updateCameras) {
  27685. if (this.activeCameras.length > 0) {
  27686. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27687. var camera = this.activeCameras[cameraIndex];
  27688. camera.update();
  27689. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27690. // rig cameras
  27691. for (var index = 0; index < camera._rigCameras.length; index++) {
  27692. camera._rigCameras[index].update();
  27693. }
  27694. }
  27695. }
  27696. }
  27697. else if (this.activeCamera) {
  27698. this.activeCamera.update();
  27699. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27700. // rig cameras
  27701. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27702. this.activeCamera._rigCameras[index].update();
  27703. }
  27704. }
  27705. }
  27706. }
  27707. // Before render
  27708. this.onBeforeRenderObservable.notifyObservers(this);
  27709. // Customs render targets
  27710. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27711. var engine = this.getEngine();
  27712. var currentActiveCamera = this.activeCamera;
  27713. if (this.renderTargetsEnabled) {
  27714. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27715. this._intermediateRendering = true;
  27716. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27717. var renderTarget = this.customRenderTargets[customIndex];
  27718. if (renderTarget._shouldRender()) {
  27719. this._renderId++;
  27720. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27721. if (!this.activeCamera)
  27722. throw new Error("Active camera not set");
  27723. // Viewport
  27724. engine.setViewport(this.activeCamera.viewport);
  27725. // Camera
  27726. this.updateTransformMatrix();
  27727. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27728. }
  27729. }
  27730. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27731. this._intermediateRendering = false;
  27732. this._renderId++;
  27733. }
  27734. // Restore back buffer
  27735. if (this.customRenderTargets.length > 0) {
  27736. engine.restoreDefaultFramebuffer();
  27737. }
  27738. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27739. this.activeCamera = currentActiveCamera;
  27740. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27741. var step = _c[_b];
  27742. step.action();
  27743. }
  27744. // Clear
  27745. if (this.autoClearDepthAndStencil || this.autoClear) {
  27746. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27747. }
  27748. // Collects render targets from external components.
  27749. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27750. var step = _e[_d];
  27751. step.action(this._renderTargets);
  27752. }
  27753. // Multi-cameras?
  27754. if (this.activeCameras.length > 0) {
  27755. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27756. if (cameraIndex > 0) {
  27757. this._engine.clear(null, false, true, true);
  27758. }
  27759. this._processSubCameras(this.activeCameras[cameraIndex]);
  27760. }
  27761. }
  27762. else {
  27763. if (!this.activeCamera) {
  27764. throw new Error("No camera defined");
  27765. }
  27766. this._processSubCameras(this.activeCamera);
  27767. }
  27768. // Intersection checks
  27769. this._checkIntersections();
  27770. // Executes the after render stage actions.
  27771. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27772. var step = _g[_f];
  27773. step.action();
  27774. }
  27775. // After render
  27776. if (this.afterRender) {
  27777. this.afterRender();
  27778. }
  27779. this.onAfterRenderObservable.notifyObservers(this);
  27780. // Cleaning
  27781. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27782. var data = this._toBeDisposed.data[index];
  27783. if (data) {
  27784. data.dispose();
  27785. }
  27786. }
  27787. this._toBeDisposed.reset();
  27788. if (this.dumpNextRenderTargets) {
  27789. this.dumpNextRenderTargets = false;
  27790. }
  27791. this._activeBones.addCount(0, true);
  27792. this._activeIndices.addCount(0, true);
  27793. this._activeParticles.addCount(0, true);
  27794. };
  27795. /**
  27796. * Freeze all materials
  27797. * A frozen material will not be updatable but should be faster to render
  27798. */
  27799. Scene.prototype.freezeMaterials = function () {
  27800. for (var i = 0; i < this.materials.length; i++) {
  27801. this.materials[i].freeze();
  27802. }
  27803. };
  27804. /**
  27805. * Unfreeze all materials
  27806. * A frozen material will not be updatable but should be faster to render
  27807. */
  27808. Scene.prototype.unfreezeMaterials = function () {
  27809. for (var i = 0; i < this.materials.length; i++) {
  27810. this.materials[i].unfreeze();
  27811. }
  27812. };
  27813. /**
  27814. * Releases all held ressources
  27815. */
  27816. Scene.prototype.dispose = function () {
  27817. this.beforeRender = null;
  27818. this.afterRender = null;
  27819. this.skeletons = [];
  27820. this.morphTargetManagers = [];
  27821. this._transientComponents = [];
  27822. this._isReadyForMeshStage.clear();
  27823. this._beforeEvaluateActiveMeshStage.clear();
  27824. this._evaluateSubMeshStage.clear();
  27825. this._activeMeshStage.clear();
  27826. this._cameraDrawRenderTargetStage.clear();
  27827. this._beforeCameraDrawStage.clear();
  27828. this._beforeRenderingGroupDrawStage.clear();
  27829. this._beforeRenderingMeshStage.clear();
  27830. this._afterRenderingMeshStage.clear();
  27831. this._afterRenderingGroupDrawStage.clear();
  27832. this._afterCameraDrawStage.clear();
  27833. this._afterRenderStage.clear();
  27834. this._beforeCameraUpdateStage.clear();
  27835. this._beforeClearStage.clear();
  27836. this._gatherRenderTargetsStage.clear();
  27837. this._gatherActiveCameraRenderTargetsStage.clear();
  27838. this._pointerMoveStage.clear();
  27839. this._pointerDownStage.clear();
  27840. this._pointerUpStage.clear();
  27841. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27842. var component = _a[_i];
  27843. component.dispose();
  27844. }
  27845. this.importedMeshesFiles = new Array();
  27846. this.stopAllAnimations();
  27847. this.resetCachedMaterial();
  27848. // Smart arrays
  27849. if (this.activeCamera) {
  27850. this.activeCamera._activeMeshes.dispose();
  27851. this.activeCamera = null;
  27852. }
  27853. this._activeMeshes.dispose();
  27854. this._renderingManager.dispose();
  27855. this._processedMaterials.dispose();
  27856. this._activeParticleSystems.dispose();
  27857. this._activeSkeletons.dispose();
  27858. this._softwareSkinnedMeshes.dispose();
  27859. this._renderTargets.dispose();
  27860. this._registeredForLateAnimationBindings.dispose();
  27861. this._meshesForIntersections.dispose();
  27862. this._toBeDisposed.dispose();
  27863. // Abort active requests
  27864. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27865. var request = _c[_b];
  27866. request.abort();
  27867. }
  27868. // Events
  27869. this.onDisposeObservable.notifyObservers(this);
  27870. this.onDisposeObservable.clear();
  27871. this.onBeforeRenderObservable.clear();
  27872. this.onAfterRenderObservable.clear();
  27873. this.onBeforeRenderTargetsRenderObservable.clear();
  27874. this.onAfterRenderTargetsRenderObservable.clear();
  27875. this.onAfterStepObservable.clear();
  27876. this.onBeforeStepObservable.clear();
  27877. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27878. this.onAfterActiveMeshesEvaluationObservable.clear();
  27879. this.onBeforeParticlesRenderingObservable.clear();
  27880. this.onAfterParticlesRenderingObservable.clear();
  27881. this.onBeforeDrawPhaseObservable.clear();
  27882. this.onAfterDrawPhaseObservable.clear();
  27883. this.onBeforeAnimationsObservable.clear();
  27884. this.onAfterAnimationsObservable.clear();
  27885. this.onDataLoadedObservable.clear();
  27886. this.onBeforeRenderingGroupObservable.clear();
  27887. this.onAfterRenderingGroupObservable.clear();
  27888. this.onMeshImportedObservable.clear();
  27889. this.detachControl();
  27890. // Detach cameras
  27891. var canvas = this._engine.getRenderingCanvas();
  27892. if (canvas) {
  27893. var index;
  27894. for (index = 0; index < this.cameras.length; index++) {
  27895. this.cameras[index].detachControl(canvas);
  27896. }
  27897. }
  27898. // Release animation groups
  27899. while (this.animationGroups.length) {
  27900. this.animationGroups[0].dispose();
  27901. }
  27902. // Release lights
  27903. while (this.lights.length) {
  27904. this.lights[0].dispose();
  27905. }
  27906. // Release meshes
  27907. while (this.meshes.length) {
  27908. this.meshes[0].dispose(true);
  27909. }
  27910. while (this.transformNodes.length) {
  27911. this.removeTransformNode(this.transformNodes[0]);
  27912. }
  27913. // Release cameras
  27914. while (this.cameras.length) {
  27915. this.cameras[0].dispose();
  27916. }
  27917. // Release materials
  27918. if (this.defaultMaterial) {
  27919. this.defaultMaterial.dispose();
  27920. }
  27921. while (this.multiMaterials.length) {
  27922. this.multiMaterials[0].dispose();
  27923. }
  27924. while (this.materials.length) {
  27925. this.materials[0].dispose();
  27926. }
  27927. // Release particles
  27928. while (this.particleSystems.length) {
  27929. this.particleSystems[0].dispose();
  27930. }
  27931. // Release postProcesses
  27932. while (this.postProcesses.length) {
  27933. this.postProcesses[0].dispose();
  27934. }
  27935. // Release textures
  27936. while (this.textures.length) {
  27937. this.textures[0].dispose();
  27938. }
  27939. // Release UBO
  27940. this._sceneUbo.dispose();
  27941. if (this._alternateSceneUbo) {
  27942. this._alternateSceneUbo.dispose();
  27943. }
  27944. // Post-processes
  27945. this.postProcessManager.dispose();
  27946. // Remove from engine
  27947. index = this._engine.scenes.indexOf(this);
  27948. if (index > -1) {
  27949. this._engine.scenes.splice(index, 1);
  27950. }
  27951. this._engine.wipeCaches(true);
  27952. this._isDisposed = true;
  27953. };
  27954. Object.defineProperty(Scene.prototype, "isDisposed", {
  27955. /**
  27956. * Gets if the scene is already disposed
  27957. */
  27958. get: function () {
  27959. return this._isDisposed;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. /**
  27965. * Call this function to reduce memory footprint of the scene.
  27966. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27967. */
  27968. Scene.prototype.clearCachedVertexData = function () {
  27969. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27970. var mesh = this.meshes[meshIndex];
  27971. var geometry = mesh.geometry;
  27972. if (geometry) {
  27973. geometry._indices = [];
  27974. for (var vbName in geometry._vertexBuffers) {
  27975. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27976. continue;
  27977. }
  27978. geometry._vertexBuffers[vbName]._buffer._data = null;
  27979. }
  27980. }
  27981. }
  27982. };
  27983. /**
  27984. * This function will remove the local cached buffer data from texture.
  27985. * It will save memory but will prevent the texture from being rebuilt
  27986. */
  27987. Scene.prototype.cleanCachedTextureBuffer = function () {
  27988. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27989. var baseTexture = _a[_i];
  27990. var buffer = baseTexture._buffer;
  27991. if (buffer) {
  27992. baseTexture._buffer = null;
  27993. }
  27994. }
  27995. };
  27996. /**
  27997. * Get the world extend vectors with an optional filter
  27998. *
  27999. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28000. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28001. */
  28002. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28003. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28004. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28005. filterPredicate = filterPredicate || (function () { return true; });
  28006. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28007. mesh.computeWorldMatrix(true);
  28008. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28009. return;
  28010. }
  28011. var boundingInfo = mesh.getBoundingInfo();
  28012. var minBox = boundingInfo.boundingBox.minimumWorld;
  28013. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28014. BABYLON.Tools.CheckExtends(minBox, min, max);
  28015. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28016. });
  28017. return {
  28018. min: min,
  28019. max: max
  28020. };
  28021. };
  28022. // Picking
  28023. /**
  28024. * Creates a ray that can be used to pick in the scene
  28025. * @param x defines the x coordinate of the origin (on-screen)
  28026. * @param y defines the y coordinate of the origin (on-screen)
  28027. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28028. * @param camera defines the camera to use for the picking
  28029. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28030. * @returns a Ray
  28031. */
  28032. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28033. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28034. var result = BABYLON.Ray.Zero();
  28035. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28036. return result;
  28037. };
  28038. /**
  28039. * Creates a ray that can be used to pick in the scene
  28040. * @param x defines the x coordinate of the origin (on-screen)
  28041. * @param y defines the y coordinate of the origin (on-screen)
  28042. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28043. * @param result defines the ray where to store the picking ray
  28044. * @param camera defines the camera to use for the picking
  28045. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28046. * @returns the current scene
  28047. */
  28048. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28049. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28050. var engine = this._engine;
  28051. if (!camera) {
  28052. if (!this.activeCamera)
  28053. throw new Error("Active camera not set");
  28054. camera = this.activeCamera;
  28055. }
  28056. var cameraViewport = camera.viewport;
  28057. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28058. // Moving coordinates to local viewport world
  28059. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28060. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28061. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28062. return this;
  28063. };
  28064. /**
  28065. * Creates a ray that can be used to pick in the scene
  28066. * @param x defines the x coordinate of the origin (on-screen)
  28067. * @param y defines the y coordinate of the origin (on-screen)
  28068. * @param camera defines the camera to use for the picking
  28069. * @returns a Ray
  28070. */
  28071. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28072. var result = BABYLON.Ray.Zero();
  28073. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28074. return result;
  28075. };
  28076. /**
  28077. * Creates a ray that can be used to pick in the scene
  28078. * @param x defines the x coordinate of the origin (on-screen)
  28079. * @param y defines the y coordinate of the origin (on-screen)
  28080. * @param result defines the ray where to store the picking ray
  28081. * @param camera defines the camera to use for the picking
  28082. * @returns the current scene
  28083. */
  28084. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28085. if (!BABYLON.PickingInfo) {
  28086. return this;
  28087. }
  28088. var engine = this._engine;
  28089. if (!camera) {
  28090. if (!this.activeCamera)
  28091. throw new Error("Active camera not set");
  28092. camera = this.activeCamera;
  28093. }
  28094. var cameraViewport = camera.viewport;
  28095. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28096. var identity = BABYLON.Matrix.Identity();
  28097. // Moving coordinates to local viewport world
  28098. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28099. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28100. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28101. return this;
  28102. };
  28103. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28104. if (!BABYLON.PickingInfo) {
  28105. return null;
  28106. }
  28107. var pickingInfo = null;
  28108. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28109. var mesh = this.meshes[meshIndex];
  28110. if (predicate) {
  28111. if (!predicate(mesh)) {
  28112. continue;
  28113. }
  28114. }
  28115. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28116. continue;
  28117. }
  28118. var world = mesh.getWorldMatrix();
  28119. var ray = rayFunction(world);
  28120. var result = mesh.intersects(ray, fastCheck);
  28121. if (!result || !result.hit)
  28122. continue;
  28123. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28124. continue;
  28125. pickingInfo = result;
  28126. if (fastCheck) {
  28127. break;
  28128. }
  28129. }
  28130. return pickingInfo || new BABYLON.PickingInfo();
  28131. };
  28132. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28133. if (!BABYLON.PickingInfo) {
  28134. return null;
  28135. }
  28136. var pickingInfos = new Array();
  28137. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28138. var mesh = this.meshes[meshIndex];
  28139. if (predicate) {
  28140. if (!predicate(mesh)) {
  28141. continue;
  28142. }
  28143. }
  28144. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28145. continue;
  28146. }
  28147. var world = mesh.getWorldMatrix();
  28148. var ray = rayFunction(world);
  28149. var result = mesh.intersects(ray, false);
  28150. if (!result || !result.hit)
  28151. continue;
  28152. pickingInfos.push(result);
  28153. }
  28154. return pickingInfos;
  28155. };
  28156. /** Launch a ray to try to pick a mesh in the scene
  28157. * @param x position on screen
  28158. * @param y position on screen
  28159. * @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
  28160. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28161. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28162. * @returns a PickingInfo
  28163. */
  28164. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28165. var _this = this;
  28166. if (!BABYLON.PickingInfo) {
  28167. return null;
  28168. }
  28169. var result = this._internalPick(function (world) {
  28170. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28171. return _this._tempPickingRay;
  28172. }, predicate, fastCheck);
  28173. if (result) {
  28174. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28175. }
  28176. return result;
  28177. };
  28178. /** Use the given ray to pick a mesh in the scene
  28179. * @param ray The ray to use to pick meshes
  28180. * @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
  28181. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28182. * @returns a PickingInfo
  28183. */
  28184. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28185. var _this = this;
  28186. var result = this._internalPick(function (world) {
  28187. if (!_this._pickWithRayInverseMatrix) {
  28188. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28189. }
  28190. world.invertToRef(_this._pickWithRayInverseMatrix);
  28191. if (!_this._cachedRayForTransform) {
  28192. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28193. }
  28194. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28195. return _this._cachedRayForTransform;
  28196. }, predicate, fastCheck);
  28197. if (result) {
  28198. result.ray = ray;
  28199. }
  28200. return result;
  28201. };
  28202. /**
  28203. * Launch a ray to try to pick a mesh in the scene
  28204. * @param x X position on screen
  28205. * @param y Y position on screen
  28206. * @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
  28207. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28208. * @returns an array of PickingInfo
  28209. */
  28210. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28211. var _this = this;
  28212. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28213. };
  28214. /**
  28215. * Launch a ray to try to pick a mesh in the scene
  28216. * @param ray Ray to use
  28217. * @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
  28218. * @returns an array of PickingInfo
  28219. */
  28220. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28221. var _this = this;
  28222. return this._internalMultiPick(function (world) {
  28223. if (!_this._pickWithRayInverseMatrix) {
  28224. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28225. }
  28226. world.invertToRef(_this._pickWithRayInverseMatrix);
  28227. if (!_this._cachedRayForTransform) {
  28228. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28229. }
  28230. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28231. return _this._cachedRayForTransform;
  28232. }, predicate);
  28233. };
  28234. /**
  28235. * Force the value of meshUnderPointer
  28236. * @param mesh defines the mesh to use
  28237. */
  28238. Scene.prototype.setPointerOverMesh = function (mesh) {
  28239. if (this._pointerOverMesh === mesh) {
  28240. return;
  28241. }
  28242. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28243. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28244. }
  28245. this._pointerOverMesh = mesh;
  28246. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28247. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28248. }
  28249. };
  28250. /**
  28251. * Gets the mesh under the pointer
  28252. * @returns a Mesh or null if no mesh is under the pointer
  28253. */
  28254. Scene.prototype.getPointerOverMesh = function () {
  28255. return this._pointerOverMesh;
  28256. };
  28257. // Misc.
  28258. /** @hidden */
  28259. Scene.prototype._rebuildGeometries = function () {
  28260. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28261. var geometry = _a[_i];
  28262. geometry._rebuild();
  28263. }
  28264. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28265. var mesh = _c[_b];
  28266. mesh._rebuild();
  28267. }
  28268. if (this.postProcessManager) {
  28269. this.postProcessManager._rebuild();
  28270. }
  28271. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28272. var component = _e[_d];
  28273. component.rebuild();
  28274. }
  28275. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28276. var system = _g[_f];
  28277. system.rebuild();
  28278. }
  28279. };
  28280. /** @hidden */
  28281. Scene.prototype._rebuildTextures = function () {
  28282. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28283. var texture = _a[_i];
  28284. texture._rebuild();
  28285. }
  28286. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28287. };
  28288. // Tags
  28289. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28290. if (tagsQuery === undefined) {
  28291. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28292. return list;
  28293. }
  28294. var listByTags = [];
  28295. forEach = forEach || (function (item) { return; });
  28296. for (var i in list) {
  28297. var item = list[i];
  28298. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28299. listByTags.push(item);
  28300. forEach(item);
  28301. }
  28302. }
  28303. return listByTags;
  28304. };
  28305. /**
  28306. * Get a list of meshes by tags
  28307. * @param tagsQuery defines the tags query to use
  28308. * @param forEach defines a predicate used to filter results
  28309. * @returns an array of Mesh
  28310. */
  28311. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28312. return this._getByTags(this.meshes, tagsQuery, forEach);
  28313. };
  28314. /**
  28315. * Get a list of cameras by tags
  28316. * @param tagsQuery defines the tags query to use
  28317. * @param forEach defines a predicate used to filter results
  28318. * @returns an array of Camera
  28319. */
  28320. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28321. return this._getByTags(this.cameras, tagsQuery, forEach);
  28322. };
  28323. /**
  28324. * Get a list of lights by tags
  28325. * @param tagsQuery defines the tags query to use
  28326. * @param forEach defines a predicate used to filter results
  28327. * @returns an array of Light
  28328. */
  28329. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28330. return this._getByTags(this.lights, tagsQuery, forEach);
  28331. };
  28332. /**
  28333. * Get a list of materials by tags
  28334. * @param tagsQuery defines the tags query to use
  28335. * @param forEach defines a predicate used to filter results
  28336. * @returns an array of Material
  28337. */
  28338. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28339. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28340. };
  28341. /**
  28342. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28343. * This allowed control for front to back rendering or reversly depending of the special needs.
  28344. *
  28345. * @param renderingGroupId The rendering group id corresponding to its index
  28346. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28347. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28348. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28349. */
  28350. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28351. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28352. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28353. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28354. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28355. };
  28356. /**
  28357. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28358. *
  28359. * @param renderingGroupId The rendering group id corresponding to its index
  28360. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28361. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28362. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28363. */
  28364. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28365. if (depth === void 0) { depth = true; }
  28366. if (stencil === void 0) { stencil = true; }
  28367. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28368. };
  28369. /**
  28370. * Gets the current auto clear configuration for one rendering group of the rendering
  28371. * manager.
  28372. * @param index the rendering group index to get the information for
  28373. * @returns The auto clear setup for the requested rendering group
  28374. */
  28375. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28376. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28377. };
  28378. /**
  28379. * Will flag all materials as dirty to trigger new shader compilation
  28380. * @param flag defines the flag used to specify which material part must be marked as dirty
  28381. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28382. */
  28383. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28384. if (this.blockMaterialDirtyMechanism) {
  28385. return;
  28386. }
  28387. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28388. var material = _a[_i];
  28389. if (predicate && !predicate(material)) {
  28390. continue;
  28391. }
  28392. material.markAsDirty(flag);
  28393. }
  28394. };
  28395. /** @hidden */
  28396. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28397. var _this = this;
  28398. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28399. this._activeRequests.push(request);
  28400. request.onCompleteObservable.add(function (request) {
  28401. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28402. });
  28403. return request;
  28404. };
  28405. /** @hidden */
  28406. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28407. var _this = this;
  28408. return new Promise(function (resolve, reject) {
  28409. _this._loadFile(url, function (data) {
  28410. resolve(data);
  28411. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28412. reject(exception);
  28413. });
  28414. });
  28415. };
  28416. // Statics
  28417. Scene._uniqueIdCounter = 0;
  28418. /** The fog is deactivated */
  28419. Scene.FOGMODE_NONE = 0;
  28420. /** The fog density is following an exponential function */
  28421. Scene.FOGMODE_EXP = 1;
  28422. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28423. Scene.FOGMODE_EXP2 = 2;
  28424. /** The fog density is following a linear function. */
  28425. Scene.FOGMODE_LINEAR = 3;
  28426. /**
  28427. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28428. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28429. */
  28430. Scene.MinDeltaTime = 1.0;
  28431. /**
  28432. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28433. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28434. */
  28435. Scene.MaxDeltaTime = 1000.0;
  28436. /** The distance in pixel that you have to move to prevent some events */
  28437. Scene.DragMovementThreshold = 10; // in pixels
  28438. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28439. Scene.LongPressDelay = 500; // in milliseconds
  28440. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28441. Scene.DoubleClickDelay = 300; // in milliseconds
  28442. /** If you need to check double click without raising a single click at first click, enable this flag */
  28443. Scene.ExclusiveDoubleClickMode = false;
  28444. return Scene;
  28445. }(BABYLON.AbstractScene));
  28446. BABYLON.Scene = Scene;
  28447. })(BABYLON || (BABYLON = {}));
  28448. //# sourceMappingURL=babylon.scene.js.map
  28449. var BABYLON;
  28450. (function (BABYLON) {
  28451. /**
  28452. * Set of assets to keep when moving a scene into an asset container.
  28453. */
  28454. var KeepAssets = /** @class */ (function (_super) {
  28455. __extends(KeepAssets, _super);
  28456. function KeepAssets() {
  28457. return _super !== null && _super.apply(this, arguments) || this;
  28458. }
  28459. return KeepAssets;
  28460. }(BABYLON.AbstractScene));
  28461. BABYLON.KeepAssets = KeepAssets;
  28462. /**
  28463. * Container with a set of assets that can be added or removed from a scene.
  28464. */
  28465. var AssetContainer = /** @class */ (function (_super) {
  28466. __extends(AssetContainer, _super);
  28467. /**
  28468. * Instantiates an AssetContainer.
  28469. * @param scene The scene the AssetContainer belongs to.
  28470. */
  28471. function AssetContainer(scene) {
  28472. var _this = _super.call(this) || this;
  28473. _this.scene = scene;
  28474. return _this;
  28475. }
  28476. /**
  28477. * Adds all the assets from the container to the scene.
  28478. */
  28479. AssetContainer.prototype.addAllToScene = function () {
  28480. var _this = this;
  28481. this.cameras.forEach(function (o) {
  28482. _this.scene.addCamera(o);
  28483. });
  28484. this.lights.forEach(function (o) {
  28485. _this.scene.addLight(o);
  28486. });
  28487. this.meshes.forEach(function (o) {
  28488. _this.scene.addMesh(o);
  28489. });
  28490. this.skeletons.forEach(function (o) {
  28491. _this.scene.addSkeleton(o);
  28492. });
  28493. this.animations.forEach(function (o) {
  28494. _this.scene.addAnimation(o);
  28495. });
  28496. this.animationGroups.forEach(function (o) {
  28497. _this.scene.addAnimationGroup(o);
  28498. });
  28499. this.multiMaterials.forEach(function (o) {
  28500. _this.scene.addMultiMaterial(o);
  28501. });
  28502. this.materials.forEach(function (o) {
  28503. _this.scene.addMaterial(o);
  28504. });
  28505. this.morphTargetManagers.forEach(function (o) {
  28506. _this.scene.addMorphTargetManager(o);
  28507. });
  28508. this.geometries.forEach(function (o) {
  28509. _this.scene.addGeometry(o);
  28510. });
  28511. this.transformNodes.forEach(function (o) {
  28512. _this.scene.addTransformNode(o);
  28513. });
  28514. this.actionManagers.forEach(function (o) {
  28515. _this.scene.addActionManager(o);
  28516. });
  28517. this.textures.forEach(function (o) {
  28518. _this.scene.addTexture(o);
  28519. });
  28520. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28521. var component = _a[_i];
  28522. component.addFromContainer(this.scene);
  28523. }
  28524. };
  28525. /**
  28526. * Removes all the assets in the container from the scene
  28527. */
  28528. AssetContainer.prototype.removeAllFromScene = function () {
  28529. var _this = this;
  28530. this.cameras.forEach(function (o) {
  28531. _this.scene.removeCamera(o);
  28532. });
  28533. this.lights.forEach(function (o) {
  28534. _this.scene.removeLight(o);
  28535. });
  28536. this.meshes.forEach(function (o) {
  28537. _this.scene.removeMesh(o);
  28538. });
  28539. this.skeletons.forEach(function (o) {
  28540. _this.scene.removeSkeleton(o);
  28541. });
  28542. this.animations.forEach(function (o) {
  28543. _this.scene.removeAnimation(o);
  28544. });
  28545. this.animationGroups.forEach(function (o) {
  28546. _this.scene.removeAnimationGroup(o);
  28547. });
  28548. this.multiMaterials.forEach(function (o) {
  28549. _this.scene.removeMultiMaterial(o);
  28550. });
  28551. this.materials.forEach(function (o) {
  28552. _this.scene.removeMaterial(o);
  28553. });
  28554. this.morphTargetManagers.forEach(function (o) {
  28555. _this.scene.removeMorphTargetManager(o);
  28556. });
  28557. this.geometries.forEach(function (o) {
  28558. _this.scene.removeGeometry(o);
  28559. });
  28560. this.transformNodes.forEach(function (o) {
  28561. _this.scene.removeTransformNode(o);
  28562. });
  28563. this.actionManagers.forEach(function (o) {
  28564. _this.scene.removeActionManager(o);
  28565. });
  28566. this.textures.forEach(function (o) {
  28567. _this.scene.removeTexture(o);
  28568. });
  28569. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28570. var component = _a[_i];
  28571. component.removeFromContainer(this.scene);
  28572. }
  28573. };
  28574. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28575. if (!sourceAssets) {
  28576. return;
  28577. }
  28578. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28579. var asset = sourceAssets_1[_i];
  28580. var move = true;
  28581. if (keepAssets) {
  28582. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28583. var keepAsset = keepAssets_1[_a];
  28584. if (asset === keepAsset) {
  28585. move = false;
  28586. break;
  28587. }
  28588. }
  28589. }
  28590. if (move) {
  28591. targetAssets.push(asset);
  28592. }
  28593. }
  28594. };
  28595. /**
  28596. * Removes all the assets contained in the scene and adds them to the container.
  28597. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28598. */
  28599. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28600. if (keepAssets === undefined) {
  28601. keepAssets = new KeepAssets();
  28602. }
  28603. for (var key in this) {
  28604. if (this.hasOwnProperty(key)) {
  28605. this[key] = this[key] || [];
  28606. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28607. }
  28608. }
  28609. this.removeAllFromScene();
  28610. };
  28611. /**
  28612. * 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.
  28613. * @returns the root mesh
  28614. */
  28615. AssetContainer.prototype.createRootMesh = function () {
  28616. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28617. this.meshes.forEach(function (m) {
  28618. if (!m.parent) {
  28619. rootMesh.addChild(m);
  28620. }
  28621. });
  28622. this.meshes.unshift(rootMesh);
  28623. return rootMesh;
  28624. };
  28625. return AssetContainer;
  28626. }(BABYLON.AbstractScene));
  28627. BABYLON.AssetContainer = AssetContainer;
  28628. })(BABYLON || (BABYLON = {}));
  28629. //# sourceMappingURL=babylon.assetContainer.js.map
  28630. var BABYLON;
  28631. (function (BABYLON) {
  28632. var Buffer = /** @class */ (function () {
  28633. /**
  28634. * Constructor
  28635. * @param engine the engine
  28636. * @param data the data to use for this buffer
  28637. * @param updatable whether the data is updatable
  28638. * @param stride the stride (optional)
  28639. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28640. * @param instanced whether the buffer is instanced (optional)
  28641. * @param useBytes set to true if the stride in in bytes (optional)
  28642. */
  28643. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28644. if (stride === void 0) { stride = 0; }
  28645. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28646. if (instanced === void 0) { instanced = false; }
  28647. if (useBytes === void 0) { useBytes = false; }
  28648. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28649. this._engine = engine.getScene().getEngine();
  28650. }
  28651. else {
  28652. this._engine = engine;
  28653. }
  28654. this._updatable = updatable;
  28655. this._instanced = instanced;
  28656. this._data = data;
  28657. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28658. if (!postponeInternalCreation) { // by default
  28659. this.create();
  28660. }
  28661. }
  28662. /**
  28663. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28664. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28665. * @param offset defines offset in the buffer (0 by default)
  28666. * @param size defines the size in floats of attributes (position is 3 for instance)
  28667. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28668. * @param instanced defines if the vertex buffer contains indexed data
  28669. * @param useBytes defines if the offset and stride are in bytes
  28670. * @returns the new vertex buffer
  28671. */
  28672. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28673. if (useBytes === void 0) { useBytes = false; }
  28674. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28675. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28676. // a lot of these parameters are ignored as they are overriden by the buffer
  28677. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28678. };
  28679. // Properties
  28680. Buffer.prototype.isUpdatable = function () {
  28681. return this._updatable;
  28682. };
  28683. Buffer.prototype.getData = function () {
  28684. return this._data;
  28685. };
  28686. Buffer.prototype.getBuffer = function () {
  28687. return this._buffer;
  28688. };
  28689. /**
  28690. * Gets the stride in float32 units (i.e. byte stride / 4).
  28691. * May not be an integer if the byte stride is not divisible by 4.
  28692. * DEPRECATED. Use byteStride instead.
  28693. * @returns the stride in float32 units
  28694. */
  28695. Buffer.prototype.getStrideSize = function () {
  28696. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28697. };
  28698. // Methods
  28699. Buffer.prototype.create = function (data) {
  28700. if (data === void 0) { data = null; }
  28701. if (!data && this._buffer) {
  28702. return; // nothing to do
  28703. }
  28704. data = data || this._data;
  28705. if (!data) {
  28706. return;
  28707. }
  28708. if (!this._buffer) { // create buffer
  28709. if (this._updatable) {
  28710. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28711. this._data = data;
  28712. }
  28713. else {
  28714. this._buffer = this._engine.createVertexBuffer(data);
  28715. }
  28716. }
  28717. else if (this._updatable) { // update buffer
  28718. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28719. this._data = data;
  28720. }
  28721. };
  28722. /** @hidden */
  28723. Buffer.prototype._rebuild = function () {
  28724. this._buffer = null;
  28725. this.create(this._data);
  28726. };
  28727. Buffer.prototype.update = function (data) {
  28728. this.create(data);
  28729. };
  28730. /**
  28731. * Updates the data directly.
  28732. * @param data the new data
  28733. * @param offset the new offset
  28734. * @param vertexCount the vertex count (optional)
  28735. * @param useBytes set to true if the offset is in bytes
  28736. */
  28737. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28738. if (useBytes === void 0) { useBytes = false; }
  28739. if (!this._buffer) {
  28740. return;
  28741. }
  28742. if (this._updatable) { // update buffer
  28743. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28744. this._data = null;
  28745. }
  28746. };
  28747. Buffer.prototype.dispose = function () {
  28748. if (!this._buffer) {
  28749. return;
  28750. }
  28751. if (this._engine._releaseBuffer(this._buffer)) {
  28752. this._buffer = null;
  28753. }
  28754. };
  28755. return Buffer;
  28756. }());
  28757. BABYLON.Buffer = Buffer;
  28758. })(BABYLON || (BABYLON = {}));
  28759. //# sourceMappingURL=babylon.buffer.js.map
  28760. var BABYLON;
  28761. (function (BABYLON) {
  28762. var VertexBuffer = /** @class */ (function () {
  28763. /**
  28764. * Constructor
  28765. * @param engine the engine
  28766. * @param data the data to use for this vertex buffer
  28767. * @param kind the vertex buffer kind
  28768. * @param updatable whether the data is updatable
  28769. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28770. * @param stride the stride (optional)
  28771. * @param instanced whether the buffer is instanced (optional)
  28772. * @param offset the offset of the data (optional)
  28773. * @param size the number of components (optional)
  28774. * @param type the type of the component (optional)
  28775. * @param normalized whether the data contains normalized data (optional)
  28776. * @param useBytes set to true if stride and offset are in bytes (optional)
  28777. */
  28778. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28779. if (normalized === void 0) { normalized = false; }
  28780. if (useBytes === void 0) { useBytes = false; }
  28781. if (data instanceof BABYLON.Buffer) {
  28782. this._buffer = data;
  28783. this._ownsBuffer = false;
  28784. }
  28785. else {
  28786. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28787. this._ownsBuffer = true;
  28788. }
  28789. this._kind = kind;
  28790. if (type == undefined) {
  28791. var data_1 = this.getData();
  28792. this.type = VertexBuffer.FLOAT;
  28793. if (data_1 instanceof Int8Array)
  28794. this.type = VertexBuffer.BYTE;
  28795. else if (data_1 instanceof Uint8Array)
  28796. this.type = VertexBuffer.UNSIGNED_BYTE;
  28797. else if (data_1 instanceof Int16Array)
  28798. this.type = VertexBuffer.SHORT;
  28799. else if (data_1 instanceof Uint16Array)
  28800. this.type = VertexBuffer.UNSIGNED_SHORT;
  28801. else if (data_1 instanceof Int32Array)
  28802. this.type = VertexBuffer.INT;
  28803. else if (data_1 instanceof Uint32Array)
  28804. this.type = VertexBuffer.UNSIGNED_INT;
  28805. }
  28806. else {
  28807. this.type = type;
  28808. }
  28809. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28810. if (useBytes) {
  28811. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28812. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28813. this.byteOffset = offset || 0;
  28814. }
  28815. else {
  28816. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28817. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28818. this.byteOffset = (offset || 0) * typeByteLength;
  28819. }
  28820. this.normalized = normalized;
  28821. this._instanced = instanced !== undefined ? instanced : false;
  28822. this._instanceDivisor = instanced ? 1 : 0;
  28823. }
  28824. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28825. /**
  28826. * Gets or sets the instance divisor when in instanced mode
  28827. */
  28828. get: function () {
  28829. return this._instanceDivisor;
  28830. },
  28831. set: function (value) {
  28832. this._instanceDivisor = value;
  28833. if (value == 0) {
  28834. this._instanced = false;
  28835. }
  28836. else {
  28837. this._instanced = true;
  28838. }
  28839. },
  28840. enumerable: true,
  28841. configurable: true
  28842. });
  28843. /** @hidden */
  28844. VertexBuffer.prototype._rebuild = function () {
  28845. if (!this._buffer) {
  28846. return;
  28847. }
  28848. this._buffer._rebuild();
  28849. };
  28850. /**
  28851. * Returns the kind of the VertexBuffer (string).
  28852. */
  28853. VertexBuffer.prototype.getKind = function () {
  28854. return this._kind;
  28855. };
  28856. // Properties
  28857. /**
  28858. * Boolean : is the VertexBuffer updatable ?
  28859. */
  28860. VertexBuffer.prototype.isUpdatable = function () {
  28861. return this._buffer.isUpdatable();
  28862. };
  28863. /**
  28864. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28865. */
  28866. VertexBuffer.prototype.getData = function () {
  28867. return this._buffer.getData();
  28868. };
  28869. /**
  28870. * Returns the WebGLBuffer associated to the VertexBuffer.
  28871. */
  28872. VertexBuffer.prototype.getBuffer = function () {
  28873. return this._buffer.getBuffer();
  28874. };
  28875. /**
  28876. * Returns the stride as a multiple of the type byte length.
  28877. * DEPRECATED. Use byteStride instead.
  28878. */
  28879. VertexBuffer.prototype.getStrideSize = function () {
  28880. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28881. };
  28882. /**
  28883. * Returns the offset as a multiple of the type byte length.
  28884. * DEPRECATED. Use byteOffset instead.
  28885. */
  28886. VertexBuffer.prototype.getOffset = function () {
  28887. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28888. };
  28889. /**
  28890. * Returns the number of components per vertex attribute (integer).
  28891. */
  28892. VertexBuffer.prototype.getSize = function () {
  28893. return this._size;
  28894. };
  28895. /**
  28896. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28897. */
  28898. VertexBuffer.prototype.getIsInstanced = function () {
  28899. return this._instanced;
  28900. };
  28901. /**
  28902. * Returns the instancing divisor, zero for non-instanced (integer).
  28903. */
  28904. VertexBuffer.prototype.getInstanceDivisor = function () {
  28905. return this._instanceDivisor;
  28906. };
  28907. // Methods
  28908. /**
  28909. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28910. * Returns the created WebGLBuffer.
  28911. */
  28912. VertexBuffer.prototype.create = function (data) {
  28913. return this._buffer.create(data);
  28914. };
  28915. /**
  28916. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28917. * This function will create a new buffer if the current one is not updatable
  28918. * Returns the updated WebGLBuffer.
  28919. */
  28920. VertexBuffer.prototype.update = function (data) {
  28921. return this._buffer.update(data);
  28922. };
  28923. /**
  28924. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28925. * Returns the directly updated WebGLBuffer.
  28926. * @param data the new data
  28927. * @param offset the new offset
  28928. * @param useBytes set to true if the offset is in bytes
  28929. */
  28930. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28931. if (useBytes === void 0) { useBytes = false; }
  28932. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28933. };
  28934. /**
  28935. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28936. */
  28937. VertexBuffer.prototype.dispose = function () {
  28938. if (this._ownsBuffer) {
  28939. this._buffer.dispose();
  28940. }
  28941. };
  28942. /**
  28943. * Enumerates each value of this vertex buffer as numbers.
  28944. * @param count the number of values to enumerate
  28945. * @param callback the callback function called for each value
  28946. */
  28947. VertexBuffer.prototype.forEach = function (count, callback) {
  28948. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28949. };
  28950. Object.defineProperty(VertexBuffer, "PositionKind", {
  28951. get: function () {
  28952. return VertexBuffer._PositionKind;
  28953. },
  28954. enumerable: true,
  28955. configurable: true
  28956. });
  28957. Object.defineProperty(VertexBuffer, "NormalKind", {
  28958. get: function () {
  28959. return VertexBuffer._NormalKind;
  28960. },
  28961. enumerable: true,
  28962. configurable: true
  28963. });
  28964. Object.defineProperty(VertexBuffer, "TangentKind", {
  28965. get: function () {
  28966. return VertexBuffer._TangentKind;
  28967. },
  28968. enumerable: true,
  28969. configurable: true
  28970. });
  28971. Object.defineProperty(VertexBuffer, "UVKind", {
  28972. get: function () {
  28973. return VertexBuffer._UVKind;
  28974. },
  28975. enumerable: true,
  28976. configurable: true
  28977. });
  28978. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28979. get: function () {
  28980. return VertexBuffer._UV2Kind;
  28981. },
  28982. enumerable: true,
  28983. configurable: true
  28984. });
  28985. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28986. get: function () {
  28987. return VertexBuffer._UV3Kind;
  28988. },
  28989. enumerable: true,
  28990. configurable: true
  28991. });
  28992. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28993. get: function () {
  28994. return VertexBuffer._UV4Kind;
  28995. },
  28996. enumerable: true,
  28997. configurable: true
  28998. });
  28999. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29000. get: function () {
  29001. return VertexBuffer._UV5Kind;
  29002. },
  29003. enumerable: true,
  29004. configurable: true
  29005. });
  29006. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29007. get: function () {
  29008. return VertexBuffer._UV6Kind;
  29009. },
  29010. enumerable: true,
  29011. configurable: true
  29012. });
  29013. Object.defineProperty(VertexBuffer, "ColorKind", {
  29014. get: function () {
  29015. return VertexBuffer._ColorKind;
  29016. },
  29017. enumerable: true,
  29018. configurable: true
  29019. });
  29020. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29021. get: function () {
  29022. return VertexBuffer._MatricesIndicesKind;
  29023. },
  29024. enumerable: true,
  29025. configurable: true
  29026. });
  29027. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29028. get: function () {
  29029. return VertexBuffer._MatricesWeightsKind;
  29030. },
  29031. enumerable: true,
  29032. configurable: true
  29033. });
  29034. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29035. get: function () {
  29036. return VertexBuffer._MatricesIndicesExtraKind;
  29037. },
  29038. enumerable: true,
  29039. configurable: true
  29040. });
  29041. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29042. get: function () {
  29043. return VertexBuffer._MatricesWeightsExtraKind;
  29044. },
  29045. enumerable: true,
  29046. configurable: true
  29047. });
  29048. /**
  29049. * Deduces the stride given a kind.
  29050. * @param kind The kind string to deduce
  29051. * @returns The deduced stride
  29052. */
  29053. VertexBuffer.DeduceStride = function (kind) {
  29054. switch (kind) {
  29055. case VertexBuffer.UVKind:
  29056. case VertexBuffer.UV2Kind:
  29057. case VertexBuffer.UV3Kind:
  29058. case VertexBuffer.UV4Kind:
  29059. case VertexBuffer.UV5Kind:
  29060. case VertexBuffer.UV6Kind:
  29061. return 2;
  29062. case VertexBuffer.NormalKind:
  29063. case VertexBuffer.PositionKind:
  29064. return 3;
  29065. case VertexBuffer.ColorKind:
  29066. case VertexBuffer.MatricesIndicesKind:
  29067. case VertexBuffer.MatricesIndicesExtraKind:
  29068. case VertexBuffer.MatricesWeightsKind:
  29069. case VertexBuffer.MatricesWeightsExtraKind:
  29070. case VertexBuffer.TangentKind:
  29071. return 4;
  29072. default:
  29073. throw new Error("Invalid kind '" + kind + "'");
  29074. }
  29075. };
  29076. /**
  29077. * Gets the byte length of the given type.
  29078. * @param type the type
  29079. * @returns the number of bytes
  29080. */
  29081. VertexBuffer.GetTypeByteLength = function (type) {
  29082. switch (type) {
  29083. case VertexBuffer.BYTE:
  29084. case VertexBuffer.UNSIGNED_BYTE:
  29085. return 1;
  29086. case VertexBuffer.SHORT:
  29087. case VertexBuffer.UNSIGNED_SHORT:
  29088. return 2;
  29089. case VertexBuffer.INT:
  29090. case VertexBuffer.FLOAT:
  29091. return 4;
  29092. default:
  29093. throw new Error("Invalid type '" + type + "'");
  29094. }
  29095. };
  29096. /**
  29097. * Enumerates each value of the given parameters as numbers.
  29098. * @param data the data to enumerate
  29099. * @param byteOffset the byte offset of the data
  29100. * @param byteStride the byte stride of the data
  29101. * @param componentCount the number of components per element
  29102. * @param componentType the type of the component
  29103. * @param count the total number of components
  29104. * @param normalized whether the data is normalized
  29105. * @param callback the callback function called for each value
  29106. */
  29107. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29108. if (data instanceof Array) {
  29109. var offset = byteOffset / 4;
  29110. var stride = byteStride / 4;
  29111. for (var index = 0; index < count; index += componentCount) {
  29112. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29113. callback(data[offset + componentIndex], index + componentIndex);
  29114. }
  29115. offset += stride;
  29116. }
  29117. }
  29118. else {
  29119. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29120. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29121. for (var index = 0; index < count; index += componentCount) {
  29122. var componentByteOffset = byteOffset;
  29123. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29124. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29125. callback(value, index + componentIndex);
  29126. componentByteOffset += componentByteLength;
  29127. }
  29128. byteOffset += byteStride;
  29129. }
  29130. }
  29131. };
  29132. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29133. switch (type) {
  29134. case VertexBuffer.BYTE: {
  29135. var value = dataView.getInt8(byteOffset);
  29136. if (normalized) {
  29137. value = Math.max(value / 127, -1);
  29138. }
  29139. return value;
  29140. }
  29141. case VertexBuffer.UNSIGNED_BYTE: {
  29142. var value = dataView.getUint8(byteOffset);
  29143. if (normalized) {
  29144. value = value / 255;
  29145. }
  29146. return value;
  29147. }
  29148. case VertexBuffer.SHORT: {
  29149. var value = dataView.getInt16(byteOffset, true);
  29150. if (normalized) {
  29151. value = Math.max(value / 16383, -1);
  29152. }
  29153. return value;
  29154. }
  29155. case VertexBuffer.UNSIGNED_SHORT: {
  29156. var value = dataView.getUint16(byteOffset, true);
  29157. if (normalized) {
  29158. value = value / 65535;
  29159. }
  29160. return value;
  29161. }
  29162. case VertexBuffer.FLOAT: {
  29163. return dataView.getFloat32(byteOffset, true);
  29164. }
  29165. default: {
  29166. throw new Error("Invalid component type " + type);
  29167. }
  29168. }
  29169. };
  29170. /**
  29171. * The byte type.
  29172. */
  29173. VertexBuffer.BYTE = 5120;
  29174. /**
  29175. * The unsigned byte type.
  29176. */
  29177. VertexBuffer.UNSIGNED_BYTE = 5121;
  29178. /**
  29179. * The short type.
  29180. */
  29181. VertexBuffer.SHORT = 5122;
  29182. /**
  29183. * The unsigned short type.
  29184. */
  29185. VertexBuffer.UNSIGNED_SHORT = 5123;
  29186. /**
  29187. * The integer type.
  29188. */
  29189. VertexBuffer.INT = 5124;
  29190. /**
  29191. * The unsigned integer type.
  29192. */
  29193. VertexBuffer.UNSIGNED_INT = 5125;
  29194. /**
  29195. * The float type.
  29196. */
  29197. VertexBuffer.FLOAT = 5126;
  29198. // Enums
  29199. VertexBuffer._PositionKind = "position";
  29200. VertexBuffer._NormalKind = "normal";
  29201. VertexBuffer._TangentKind = "tangent";
  29202. VertexBuffer._UVKind = "uv";
  29203. VertexBuffer._UV2Kind = "uv2";
  29204. VertexBuffer._UV3Kind = "uv3";
  29205. VertexBuffer._UV4Kind = "uv4";
  29206. VertexBuffer._UV5Kind = "uv5";
  29207. VertexBuffer._UV6Kind = "uv6";
  29208. VertexBuffer._ColorKind = "color";
  29209. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29210. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29211. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29212. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29213. return VertexBuffer;
  29214. }());
  29215. BABYLON.VertexBuffer = VertexBuffer;
  29216. })(BABYLON || (BABYLON = {}));
  29217. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29218. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29219. var BABYLON;
  29220. (function (BABYLON) {
  29221. /**
  29222. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29223. */
  29224. var DummyInternalTextureTracker = /** @class */ (function () {
  29225. function DummyInternalTextureTracker() {
  29226. /**
  29227. * Gets or set the previous tracker in the list
  29228. */
  29229. this.previous = null;
  29230. /**
  29231. * Gets or set the next tracker in the list
  29232. */
  29233. this.next = null;
  29234. }
  29235. return DummyInternalTextureTracker;
  29236. }());
  29237. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29238. })(BABYLON || (BABYLON = {}));
  29239. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29240. var BABYLON;
  29241. (function (BABYLON) {
  29242. /**
  29243. * Class used to store data associated with WebGL texture data for the engine
  29244. * This class should not be used directly
  29245. */
  29246. var InternalTexture = /** @class */ (function () {
  29247. /**
  29248. * Creates a new InternalTexture
  29249. * @param engine defines the engine to use
  29250. * @param dataSource defines the type of data that will be used
  29251. */
  29252. function InternalTexture(engine, dataSource) {
  29253. /**
  29254. * Observable called when the texture is loaded
  29255. */
  29256. this.onLoadedObservable = new BABYLON.Observable();
  29257. /**
  29258. * Gets or set the previous tracker in the list
  29259. */
  29260. this.previous = null;
  29261. /**
  29262. * Gets or set the next tracker in the list
  29263. */
  29264. this.next = null;
  29265. // Private
  29266. /** @hidden */
  29267. this._initialSlot = -1;
  29268. /** @hidden */
  29269. this._designatedSlot = -1;
  29270. /** @hidden */
  29271. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29272. /** @hidden */
  29273. this._comparisonFunction = 0;
  29274. /** @hidden */
  29275. this._sphericalPolynomial = null;
  29276. /** @hidden */
  29277. this._lodGenerationScale = 0;
  29278. /** @hidden */
  29279. this._lodGenerationOffset = 0;
  29280. /** @hidden */
  29281. this._isRGBD = false;
  29282. /** @hidden */
  29283. this._references = 1;
  29284. this._engine = engine;
  29285. this._dataSource = dataSource;
  29286. this._webGLTexture = engine._createTexture();
  29287. }
  29288. /**
  29289. * Gets the Engine the texture belongs to.
  29290. * @returns The babylon engine
  29291. */
  29292. InternalTexture.prototype.getEngine = function () {
  29293. return this._engine;
  29294. };
  29295. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29296. /**
  29297. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29298. */
  29299. get: function () {
  29300. return this._dataSource;
  29301. },
  29302. enumerable: true,
  29303. configurable: true
  29304. });
  29305. /**
  29306. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29307. */
  29308. InternalTexture.prototype.incrementReferences = function () {
  29309. this._references++;
  29310. };
  29311. /**
  29312. * Change the size of the texture (not the size of the content)
  29313. * @param width defines the new width
  29314. * @param height defines the new height
  29315. * @param depth defines the new depth (1 by default)
  29316. */
  29317. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29318. if (depth === void 0) { depth = 1; }
  29319. this.width = width;
  29320. this.height = height;
  29321. this.depth = depth;
  29322. this.baseWidth = width;
  29323. this.baseHeight = height;
  29324. this.baseDepth = depth;
  29325. this._size = width * height * depth;
  29326. };
  29327. /** @hidden */
  29328. InternalTexture.prototype._rebuild = function () {
  29329. var _this = this;
  29330. var proxy;
  29331. this.isReady = false;
  29332. this._cachedCoordinatesMode = null;
  29333. this._cachedWrapU = null;
  29334. this._cachedWrapV = null;
  29335. this._cachedAnisotropicFilteringLevel = null;
  29336. switch (this._dataSource) {
  29337. case InternalTexture.DATASOURCE_TEMP:
  29338. return;
  29339. case InternalTexture.DATASOURCE_URL:
  29340. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29341. _this.isReady = true;
  29342. }, null, this._buffer, undefined, this.format);
  29343. proxy._swapAndDie(this);
  29344. return;
  29345. case InternalTexture.DATASOURCE_RAW:
  29346. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29347. proxy._swapAndDie(this);
  29348. this.isReady = true;
  29349. return;
  29350. case InternalTexture.DATASOURCE_RAW3D:
  29351. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29352. proxy._swapAndDie(this);
  29353. this.isReady = true;
  29354. return;
  29355. case InternalTexture.DATASOURCE_DYNAMIC:
  29356. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29357. proxy._swapAndDie(this);
  29358. // The engine will make sure to update content so no need to flag it as isReady = true
  29359. return;
  29360. case InternalTexture.DATASOURCE_RENDERTARGET:
  29361. var options = new BABYLON.RenderTargetCreationOptions();
  29362. options.generateDepthBuffer = this._generateDepthBuffer;
  29363. options.generateMipMaps = this.generateMipMaps;
  29364. options.generateStencilBuffer = this._generateStencilBuffer;
  29365. options.samplingMode = this.samplingMode;
  29366. options.type = this.type;
  29367. if (this.isCube) {
  29368. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29369. }
  29370. else {
  29371. var size = {
  29372. width: this.width,
  29373. height: this.height
  29374. };
  29375. proxy = this._engine.createRenderTargetTexture(size, options);
  29376. }
  29377. proxy._swapAndDie(this);
  29378. this.isReady = true;
  29379. return;
  29380. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29381. var depthTextureOptions = {
  29382. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29383. comparisonFunction: this._comparisonFunction,
  29384. generateStencil: this._generateStencilBuffer,
  29385. isCube: this.isCube
  29386. };
  29387. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29388. proxy._swapAndDie(this);
  29389. this.isReady = true;
  29390. return;
  29391. case InternalTexture.DATASOURCE_CUBE:
  29392. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29393. _this.isReady = true;
  29394. }, null, this.format, this._extension);
  29395. proxy._swapAndDie(this);
  29396. return;
  29397. case InternalTexture.DATASOURCE_CUBERAW:
  29398. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29399. proxy._swapAndDie(this);
  29400. this.isReady = true;
  29401. return;
  29402. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29403. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29404. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29405. _this.isReady = true;
  29406. });
  29407. proxy._swapAndDie(this);
  29408. return;
  29409. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29410. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29411. if (proxy) {
  29412. proxy._swapAndDie(_this);
  29413. }
  29414. _this.isReady = true;
  29415. }, null, this.format, this._extension);
  29416. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29417. return;
  29418. }
  29419. };
  29420. /** @hidden */
  29421. InternalTexture.prototype._swapAndDie = function (target) {
  29422. target._webGLTexture = this._webGLTexture;
  29423. if (this._framebuffer) {
  29424. target._framebuffer = this._framebuffer;
  29425. }
  29426. if (this._depthStencilBuffer) {
  29427. target._depthStencilBuffer = this._depthStencilBuffer;
  29428. }
  29429. if (this._lodTextureHigh) {
  29430. if (target._lodTextureHigh) {
  29431. target._lodTextureHigh.dispose();
  29432. }
  29433. target._lodTextureHigh = this._lodTextureHigh;
  29434. }
  29435. if (this._lodTextureMid) {
  29436. if (target._lodTextureMid) {
  29437. target._lodTextureMid.dispose();
  29438. }
  29439. target._lodTextureMid = this._lodTextureMid;
  29440. }
  29441. if (this._lodTextureLow) {
  29442. if (target._lodTextureLow) {
  29443. target._lodTextureLow.dispose();
  29444. }
  29445. target._lodTextureLow = this._lodTextureLow;
  29446. }
  29447. var cache = this._engine.getLoadedTexturesCache();
  29448. var index = cache.indexOf(this);
  29449. if (index !== -1) {
  29450. cache.splice(index, 1);
  29451. }
  29452. };
  29453. /**
  29454. * Dispose the current allocated resources
  29455. */
  29456. InternalTexture.prototype.dispose = function () {
  29457. if (!this._webGLTexture) {
  29458. return;
  29459. }
  29460. this._references--;
  29461. if (this._references === 0) {
  29462. this._engine._releaseTexture(this);
  29463. this._webGLTexture = null;
  29464. this.previous = null;
  29465. this.next = null;
  29466. }
  29467. };
  29468. /**
  29469. * The source of the texture data is unknown
  29470. */
  29471. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29472. /**
  29473. * Texture data comes from an URL
  29474. */
  29475. InternalTexture.DATASOURCE_URL = 1;
  29476. /**
  29477. * Texture data is only used for temporary storage
  29478. */
  29479. InternalTexture.DATASOURCE_TEMP = 2;
  29480. /**
  29481. * Texture data comes from raw data (ArrayBuffer)
  29482. */
  29483. InternalTexture.DATASOURCE_RAW = 3;
  29484. /**
  29485. * Texture content is dynamic (video or dynamic texture)
  29486. */
  29487. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29488. /**
  29489. * Texture content is generated by rendering to it
  29490. */
  29491. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29492. /**
  29493. * Texture content is part of a multi render target process
  29494. */
  29495. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29496. /**
  29497. * Texture data comes from a cube data file
  29498. */
  29499. InternalTexture.DATASOURCE_CUBE = 7;
  29500. /**
  29501. * Texture data comes from a raw cube data
  29502. */
  29503. InternalTexture.DATASOURCE_CUBERAW = 8;
  29504. /**
  29505. * Texture data come from a prefiltered cube data file
  29506. */
  29507. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29508. /**
  29509. * Texture content is raw 3D data
  29510. */
  29511. InternalTexture.DATASOURCE_RAW3D = 10;
  29512. /**
  29513. * Texture content is a depth texture
  29514. */
  29515. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29516. /**
  29517. * Texture data comes from a raw cube data encoded with RGBD
  29518. */
  29519. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29520. return InternalTexture;
  29521. }());
  29522. BABYLON.InternalTexture = InternalTexture;
  29523. })(BABYLON || (BABYLON = {}));
  29524. //# sourceMappingURL=babylon.internalTexture.js.map
  29525. var BABYLON;
  29526. (function (BABYLON) {
  29527. var BaseTexture = /** @class */ (function () {
  29528. function BaseTexture(scene) {
  29529. this._hasAlpha = false;
  29530. this.getAlphaFromRGB = false;
  29531. this.level = 1;
  29532. this.coordinatesIndex = 0;
  29533. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29534. /**
  29535. * | Value | Type | Description |
  29536. * | ----- | ------------------ | ----------- |
  29537. * | 0 | CLAMP_ADDRESSMODE | |
  29538. * | 1 | WRAP_ADDRESSMODE | |
  29539. * | 2 | MIRROR_ADDRESSMODE | |
  29540. */
  29541. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29542. /**
  29543. * | Value | Type | Description |
  29544. * | ----- | ------------------ | ----------- |
  29545. * | 0 | CLAMP_ADDRESSMODE | |
  29546. * | 1 | WRAP_ADDRESSMODE | |
  29547. * | 2 | MIRROR_ADDRESSMODE | |
  29548. */
  29549. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29550. /**
  29551. * | Value | Type | Description |
  29552. * | ----- | ------------------ | ----------- |
  29553. * | 0 | CLAMP_ADDRESSMODE | |
  29554. * | 1 | WRAP_ADDRESSMODE | |
  29555. * | 2 | MIRROR_ADDRESSMODE | |
  29556. */
  29557. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29558. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29559. this.isCube = false;
  29560. this.is3D = false;
  29561. this.gammaSpace = true;
  29562. this.invertZ = false;
  29563. this.lodLevelInAlpha = false;
  29564. this.isRenderTarget = false;
  29565. this.animations = new Array();
  29566. /**
  29567. * An event triggered when the texture is disposed.
  29568. */
  29569. this.onDisposeObservable = new BABYLON.Observable();
  29570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29571. this._cachedSize = BABYLON.Size.Zero();
  29572. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29573. if (this._scene) {
  29574. this._scene.textures.push(this);
  29575. }
  29576. this._uid = null;
  29577. }
  29578. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29579. get: function () {
  29580. return this._hasAlpha;
  29581. },
  29582. set: function (value) {
  29583. if (this._hasAlpha === value) {
  29584. return;
  29585. }
  29586. this._hasAlpha = value;
  29587. if (this._scene) {
  29588. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29589. }
  29590. },
  29591. enumerable: true,
  29592. configurable: true
  29593. });
  29594. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29595. get: function () {
  29596. return this._coordinatesMode;
  29597. },
  29598. /**
  29599. * How a texture is mapped.
  29600. *
  29601. * | Value | Type | Description |
  29602. * | ----- | ----------------------------------- | ----------- |
  29603. * | 0 | EXPLICIT_MODE | |
  29604. * | 1 | SPHERICAL_MODE | |
  29605. * | 2 | PLANAR_MODE | |
  29606. * | 3 | CUBIC_MODE | |
  29607. * | 4 | PROJECTION_MODE | |
  29608. * | 5 | SKYBOX_MODE | |
  29609. * | 6 | INVCUBIC_MODE | |
  29610. * | 7 | EQUIRECTANGULAR_MODE | |
  29611. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29612. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29613. */
  29614. set: function (value) {
  29615. if (this._coordinatesMode === value) {
  29616. return;
  29617. }
  29618. this._coordinatesMode = value;
  29619. if (this._scene) {
  29620. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29621. }
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29627. /**
  29628. * Gets whether or not the texture contains RGBD data.
  29629. */
  29630. get: function () {
  29631. return this._texture != null && this._texture._isRGBD;
  29632. },
  29633. enumerable: true,
  29634. configurable: true
  29635. });
  29636. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29637. get: function () {
  29638. if (this._texture)
  29639. return this._texture._lodGenerationOffset;
  29640. return 0.0;
  29641. },
  29642. set: function (value) {
  29643. if (this._texture)
  29644. this._texture._lodGenerationOffset = value;
  29645. },
  29646. enumerable: true,
  29647. configurable: true
  29648. });
  29649. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29650. get: function () {
  29651. if (this._texture)
  29652. return this._texture._lodGenerationScale;
  29653. return 0.0;
  29654. },
  29655. set: function (value) {
  29656. if (this._texture)
  29657. this._texture._lodGenerationScale = value;
  29658. },
  29659. enumerable: true,
  29660. configurable: true
  29661. });
  29662. Object.defineProperty(BaseTexture.prototype, "uid", {
  29663. get: function () {
  29664. if (!this._uid) {
  29665. this._uid = BABYLON.Tools.RandomId();
  29666. }
  29667. return this._uid;
  29668. },
  29669. enumerable: true,
  29670. configurable: true
  29671. });
  29672. BaseTexture.prototype.toString = function () {
  29673. return this.name;
  29674. };
  29675. BaseTexture.prototype.getClassName = function () {
  29676. return "BaseTexture";
  29677. };
  29678. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29679. set: function (callback) {
  29680. if (this._onDisposeObserver) {
  29681. this.onDisposeObservable.remove(this._onDisposeObserver);
  29682. }
  29683. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29684. },
  29685. enumerable: true,
  29686. configurable: true
  29687. });
  29688. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29689. get: function () {
  29690. return true;
  29691. },
  29692. enumerable: true,
  29693. configurable: true
  29694. });
  29695. BaseTexture.prototype.getScene = function () {
  29696. return this._scene;
  29697. };
  29698. BaseTexture.prototype.getTextureMatrix = function () {
  29699. return BABYLON.Matrix.IdentityReadOnly;
  29700. };
  29701. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29702. return BABYLON.Matrix.IdentityReadOnly;
  29703. };
  29704. BaseTexture.prototype.getInternalTexture = function () {
  29705. return this._texture;
  29706. };
  29707. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29708. return !this.isBlocking || this.isReady();
  29709. };
  29710. BaseTexture.prototype.isReady = function () {
  29711. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29712. this.delayLoad();
  29713. return false;
  29714. }
  29715. if (this._texture) {
  29716. return this._texture.isReady;
  29717. }
  29718. return false;
  29719. };
  29720. BaseTexture.prototype.getSize = function () {
  29721. if (this._texture) {
  29722. if (this._texture.width) {
  29723. this._cachedSize.width = this._texture.width;
  29724. this._cachedSize.height = this._texture.height;
  29725. return this._cachedSize;
  29726. }
  29727. if (this._texture._size) {
  29728. this._cachedSize.width = this._texture._size;
  29729. this._cachedSize.height = this._texture._size;
  29730. return this._cachedSize;
  29731. }
  29732. }
  29733. return this._cachedSize;
  29734. };
  29735. BaseTexture.prototype.getBaseSize = function () {
  29736. if (!this.isReady() || !this._texture)
  29737. return BABYLON.Size.Zero();
  29738. if (this._texture._size) {
  29739. return new BABYLON.Size(this._texture._size, this._texture._size);
  29740. }
  29741. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29742. };
  29743. BaseTexture.prototype.scale = function (ratio) {
  29744. };
  29745. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29746. get: function () {
  29747. return false;
  29748. },
  29749. enumerable: true,
  29750. configurable: true
  29751. });
  29752. /** @hidden */
  29753. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29754. if (!this._scene) {
  29755. return null;
  29756. }
  29757. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29758. for (var index = 0; index < texturesCache.length; index++) {
  29759. var texturesCacheEntry = texturesCache[index];
  29760. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29761. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29762. texturesCacheEntry.incrementReferences();
  29763. return texturesCacheEntry;
  29764. }
  29765. }
  29766. }
  29767. return null;
  29768. };
  29769. /** @hidden */
  29770. BaseTexture.prototype._rebuild = function () {
  29771. };
  29772. BaseTexture.prototype.delayLoad = function () {
  29773. };
  29774. BaseTexture.prototype.clone = function () {
  29775. return null;
  29776. };
  29777. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29778. get: function () {
  29779. if (!this._texture) {
  29780. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29781. }
  29782. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29783. },
  29784. enumerable: true,
  29785. configurable: true
  29786. });
  29787. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29788. get: function () {
  29789. if (!this._texture) {
  29790. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29791. }
  29792. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29793. },
  29794. enumerable: true,
  29795. configurable: true
  29796. });
  29797. /**
  29798. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29799. * This will returns an RGBA array buffer containing either in values (0-255) or
  29800. * float values (0-1) depending of the underlying buffer type.
  29801. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29802. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29803. * @param buffer defines a user defined buffer to fill with data (can be null)
  29804. * @returns The Array buffer containing the pixels data.
  29805. */
  29806. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29807. if (faceIndex === void 0) { faceIndex = 0; }
  29808. if (level === void 0) { level = 0; }
  29809. if (buffer === void 0) { buffer = null; }
  29810. if (!this._texture) {
  29811. return null;
  29812. }
  29813. var size = this.getSize();
  29814. var width = size.width;
  29815. var height = size.height;
  29816. var scene = this.getScene();
  29817. if (!scene) {
  29818. return null;
  29819. }
  29820. var engine = scene.getEngine();
  29821. if (level != 0) {
  29822. width = width / Math.pow(2, level);
  29823. height = height / Math.pow(2, level);
  29824. width = Math.round(width);
  29825. height = Math.round(height);
  29826. }
  29827. if (this._texture.isCube) {
  29828. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29829. }
  29830. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  29831. };
  29832. BaseTexture.prototype.releaseInternalTexture = function () {
  29833. if (this._texture) {
  29834. this._texture.dispose();
  29835. this._texture = null;
  29836. }
  29837. };
  29838. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29839. get: function () {
  29840. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29841. return null;
  29842. }
  29843. if (!this._texture._sphericalPolynomial) {
  29844. this._texture._sphericalPolynomial =
  29845. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29846. }
  29847. return this._texture._sphericalPolynomial;
  29848. },
  29849. set: function (value) {
  29850. if (this._texture) {
  29851. this._texture._sphericalPolynomial = value;
  29852. }
  29853. },
  29854. enumerable: true,
  29855. configurable: true
  29856. });
  29857. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29858. get: function () {
  29859. if (this._texture) {
  29860. return this._texture._lodTextureHigh;
  29861. }
  29862. return null;
  29863. },
  29864. enumerable: true,
  29865. configurable: true
  29866. });
  29867. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29868. get: function () {
  29869. if (this._texture) {
  29870. return this._texture._lodTextureMid;
  29871. }
  29872. return null;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29878. get: function () {
  29879. if (this._texture) {
  29880. return this._texture._lodTextureLow;
  29881. }
  29882. return null;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. BaseTexture.prototype.dispose = function () {
  29888. if (!this._scene) {
  29889. return;
  29890. }
  29891. // Animations
  29892. this._scene.stopAnimation(this);
  29893. // Remove from scene
  29894. this._scene._removePendingData(this);
  29895. var index = this._scene.textures.indexOf(this);
  29896. if (index >= 0) {
  29897. this._scene.textures.splice(index, 1);
  29898. }
  29899. if (this._texture === undefined) {
  29900. return;
  29901. }
  29902. // Release
  29903. this.releaseInternalTexture();
  29904. // Callback
  29905. this.onDisposeObservable.notifyObservers(this);
  29906. this.onDisposeObservable.clear();
  29907. };
  29908. BaseTexture.prototype.serialize = function () {
  29909. if (!this.name) {
  29910. return null;
  29911. }
  29912. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29913. // Animations
  29914. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29915. return serializationObject;
  29916. };
  29917. BaseTexture.WhenAllReady = function (textures, callback) {
  29918. var numRemaining = textures.length;
  29919. if (numRemaining === 0) {
  29920. callback();
  29921. return;
  29922. }
  29923. var _loop_1 = function () {
  29924. texture = textures[i];
  29925. if (texture.isReady()) {
  29926. if (--numRemaining === 0) {
  29927. callback();
  29928. }
  29929. }
  29930. else {
  29931. onLoadObservable = texture.onLoadObservable;
  29932. var onLoadCallback_1 = function () {
  29933. onLoadObservable.removeCallback(onLoadCallback_1);
  29934. if (--numRemaining === 0) {
  29935. callback();
  29936. }
  29937. };
  29938. onLoadObservable.add(onLoadCallback_1);
  29939. }
  29940. };
  29941. var texture, onLoadObservable;
  29942. for (var i = 0; i < textures.length; i++) {
  29943. _loop_1();
  29944. }
  29945. };
  29946. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29947. __decorate([
  29948. BABYLON.serialize()
  29949. ], BaseTexture.prototype, "name", void 0);
  29950. __decorate([
  29951. BABYLON.serialize("hasAlpha")
  29952. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29953. __decorate([
  29954. BABYLON.serialize()
  29955. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29956. __decorate([
  29957. BABYLON.serialize()
  29958. ], BaseTexture.prototype, "level", void 0);
  29959. __decorate([
  29960. BABYLON.serialize()
  29961. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29962. __decorate([
  29963. BABYLON.serialize("coordinatesMode")
  29964. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29965. __decorate([
  29966. BABYLON.serialize()
  29967. ], BaseTexture.prototype, "wrapU", void 0);
  29968. __decorate([
  29969. BABYLON.serialize()
  29970. ], BaseTexture.prototype, "wrapV", void 0);
  29971. __decorate([
  29972. BABYLON.serialize()
  29973. ], BaseTexture.prototype, "wrapR", void 0);
  29974. __decorate([
  29975. BABYLON.serialize()
  29976. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29977. __decorate([
  29978. BABYLON.serialize()
  29979. ], BaseTexture.prototype, "isCube", void 0);
  29980. __decorate([
  29981. BABYLON.serialize()
  29982. ], BaseTexture.prototype, "is3D", void 0);
  29983. __decorate([
  29984. BABYLON.serialize()
  29985. ], BaseTexture.prototype, "gammaSpace", void 0);
  29986. __decorate([
  29987. BABYLON.serialize()
  29988. ], BaseTexture.prototype, "invertZ", void 0);
  29989. __decorate([
  29990. BABYLON.serialize()
  29991. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29992. __decorate([
  29993. BABYLON.serialize()
  29994. ], BaseTexture.prototype, "lodGenerationOffset", null);
  29995. __decorate([
  29996. BABYLON.serialize()
  29997. ], BaseTexture.prototype, "lodGenerationScale", null);
  29998. __decorate([
  29999. BABYLON.serialize()
  30000. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30001. return BaseTexture;
  30002. }());
  30003. BABYLON.BaseTexture = BaseTexture;
  30004. })(BABYLON || (BABYLON = {}));
  30005. //# sourceMappingURL=babylon.baseTexture.js.map
  30006. var BABYLON;
  30007. (function (BABYLON) {
  30008. var Texture = /** @class */ (function (_super) {
  30009. __extends(Texture, _super);
  30010. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30011. if (noMipmap === void 0) { noMipmap = false; }
  30012. if (invertY === void 0) { invertY = true; }
  30013. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30014. if (onLoad === void 0) { onLoad = null; }
  30015. if (onError === void 0) { onError = null; }
  30016. if (buffer === void 0) { buffer = null; }
  30017. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30018. var _this = _super.call(this, scene) || this;
  30019. _this.uOffset = 0;
  30020. _this.vOffset = 0;
  30021. _this.uScale = 1.0;
  30022. _this.vScale = 1.0;
  30023. _this.uAng = 0;
  30024. _this.vAng = 0;
  30025. _this.wAng = 0;
  30026. /**
  30027. * Defines the center of rotation (U)
  30028. */
  30029. _this.uRotationCenter = 0.5;
  30030. /**
  30031. * Defines the center of rotation (V)
  30032. */
  30033. _this.vRotationCenter = 0.5;
  30034. /**
  30035. * Defines the center of rotation (W)
  30036. */
  30037. _this.wRotationCenter = 0.5;
  30038. _this._isBlocking = true;
  30039. _this.name = url || "";
  30040. _this.url = url;
  30041. _this._noMipmap = noMipmap;
  30042. _this._invertY = invertY;
  30043. _this._samplingMode = samplingMode;
  30044. _this._buffer = buffer;
  30045. _this._deleteBuffer = deleteBuffer;
  30046. if (format) {
  30047. _this._format = format;
  30048. }
  30049. scene = _this.getScene();
  30050. if (!scene) {
  30051. return _this;
  30052. }
  30053. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30054. var load = function () {
  30055. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30056. _this.onLoadObservable.notifyObservers(_this);
  30057. }
  30058. if (onLoad) {
  30059. onLoad();
  30060. }
  30061. if (!_this.isBlocking && scene) {
  30062. scene.resetCachedMaterial();
  30063. }
  30064. };
  30065. if (!_this.url) {
  30066. _this._delayedOnLoad = load;
  30067. _this._delayedOnError = onError;
  30068. return _this;
  30069. }
  30070. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30071. if (!_this._texture) {
  30072. if (!scene.useDelayedTextureLoading) {
  30073. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30074. if (deleteBuffer) {
  30075. delete _this._buffer;
  30076. }
  30077. }
  30078. else {
  30079. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30080. _this._delayedOnLoad = load;
  30081. _this._delayedOnError = onError;
  30082. }
  30083. }
  30084. else {
  30085. if (_this._texture.isReady) {
  30086. BABYLON.Tools.SetImmediate(function () { return load(); });
  30087. }
  30088. else {
  30089. _this._texture.onLoadedObservable.add(load);
  30090. }
  30091. }
  30092. return _this;
  30093. }
  30094. Object.defineProperty(Texture.prototype, "noMipmap", {
  30095. get: function () {
  30096. return this._noMipmap;
  30097. },
  30098. enumerable: true,
  30099. configurable: true
  30100. });
  30101. Object.defineProperty(Texture.prototype, "isBlocking", {
  30102. get: function () {
  30103. return this._isBlocking;
  30104. },
  30105. set: function (value) {
  30106. this._isBlocking = value;
  30107. },
  30108. enumerable: true,
  30109. configurable: true
  30110. });
  30111. Object.defineProperty(Texture.prototype, "samplingMode", {
  30112. get: function () {
  30113. return this._samplingMode;
  30114. },
  30115. enumerable: true,
  30116. configurable: true
  30117. });
  30118. /**
  30119. * Update the url (and optional buffer) of this texture if url was null during construction.
  30120. * @param url the url of the texture
  30121. * @param buffer the buffer of the texture (defaults to null)
  30122. */
  30123. Texture.prototype.updateURL = function (url, buffer) {
  30124. if (buffer === void 0) { buffer = null; }
  30125. if (this.url) {
  30126. throw new Error("URL is already set");
  30127. }
  30128. this.url = url;
  30129. this._buffer = buffer;
  30130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30131. this.delayLoad();
  30132. };
  30133. Texture.prototype.delayLoad = function () {
  30134. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30135. return;
  30136. }
  30137. var scene = this.getScene();
  30138. if (!scene) {
  30139. return;
  30140. }
  30141. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30142. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30143. if (!this._texture) {
  30144. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30145. if (this._deleteBuffer) {
  30146. delete this._buffer;
  30147. }
  30148. }
  30149. else {
  30150. if (this._delayedOnLoad) {
  30151. if (this._texture.isReady) {
  30152. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30153. }
  30154. else {
  30155. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30156. }
  30157. }
  30158. }
  30159. this._delayedOnLoad = null;
  30160. this._delayedOnError = null;
  30161. };
  30162. /**
  30163. * Default is Trilinear mode.
  30164. *
  30165. * | Value | Type | Description |
  30166. * | ----- | ------------------ | ----------- |
  30167. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30168. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30169. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30170. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30171. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30172. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30173. * | 7 | NEAREST_LINEAR | |
  30174. * | 8 | NEAREST_NEAREST | |
  30175. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30176. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30177. * | 11 | LINEAR_LINEAR | |
  30178. * | 12 | LINEAR_NEAREST | |
  30179. *
  30180. * > _mag_: magnification filter (close to the viewer)
  30181. * > _min_: minification filter (far from the viewer)
  30182. * > _mip_: filter used between mip map levels
  30183. *
  30184. */
  30185. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30186. if (!this._texture) {
  30187. return;
  30188. }
  30189. var scene = this.getScene();
  30190. if (!scene) {
  30191. return;
  30192. }
  30193. this._samplingMode = samplingMode;
  30194. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30195. };
  30196. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30197. x *= this.uScale;
  30198. y *= this.vScale;
  30199. x -= this.uRotationCenter * this.uScale;
  30200. y -= this.vRotationCenter * this.vScale;
  30201. z -= this.wRotationCenter;
  30202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30203. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30204. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30205. t.z += this.wRotationCenter;
  30206. };
  30207. Texture.prototype.getTextureMatrix = function () {
  30208. var _this = this;
  30209. if (this.uOffset === this._cachedUOffset &&
  30210. this.vOffset === this._cachedVOffset &&
  30211. this.uScale === this._cachedUScale &&
  30212. this.vScale === this._cachedVScale &&
  30213. this.uAng === this._cachedUAng &&
  30214. this.vAng === this._cachedVAng &&
  30215. this.wAng === this._cachedWAng) {
  30216. return this._cachedTextureMatrix;
  30217. }
  30218. this._cachedUOffset = this.uOffset;
  30219. this._cachedVOffset = this.vOffset;
  30220. this._cachedUScale = this.uScale;
  30221. this._cachedVScale = this.vScale;
  30222. this._cachedUAng = this.uAng;
  30223. this._cachedVAng = this.vAng;
  30224. this._cachedWAng = this.wAng;
  30225. if (!this._cachedTextureMatrix) {
  30226. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30227. this._rowGenerationMatrix = new BABYLON.Matrix();
  30228. this._t0 = BABYLON.Vector3.Zero();
  30229. this._t1 = BABYLON.Vector3.Zero();
  30230. this._t2 = BABYLON.Vector3.Zero();
  30231. }
  30232. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30233. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30234. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30235. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30236. this._t1.subtractInPlace(this._t0);
  30237. this._t2.subtractInPlace(this._t0);
  30238. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30239. this._cachedTextureMatrix.m[0] = this._t1.x;
  30240. this._cachedTextureMatrix.m[1] = this._t1.y;
  30241. this._cachedTextureMatrix.m[2] = this._t1.z;
  30242. this._cachedTextureMatrix.m[4] = this._t2.x;
  30243. this._cachedTextureMatrix.m[5] = this._t2.y;
  30244. this._cachedTextureMatrix.m[6] = this._t2.z;
  30245. this._cachedTextureMatrix.m[8] = this._t0.x;
  30246. this._cachedTextureMatrix.m[9] = this._t0.y;
  30247. this._cachedTextureMatrix.m[10] = this._t0.z;
  30248. var scene = this.getScene();
  30249. if (!scene) {
  30250. return this._cachedTextureMatrix;
  30251. }
  30252. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30253. return mat.hasTexture(_this);
  30254. });
  30255. return this._cachedTextureMatrix;
  30256. };
  30257. Texture.prototype.getReflectionTextureMatrix = function () {
  30258. var _this = this;
  30259. var scene = this.getScene();
  30260. if (!scene) {
  30261. return this._cachedTextureMatrix;
  30262. }
  30263. if (this.uOffset === this._cachedUOffset &&
  30264. this.vOffset === this._cachedVOffset &&
  30265. this.uScale === this._cachedUScale &&
  30266. this.vScale === this._cachedVScale &&
  30267. this.coordinatesMode === this._cachedCoordinatesMode) {
  30268. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30269. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30270. return this._cachedTextureMatrix;
  30271. }
  30272. }
  30273. else {
  30274. return this._cachedTextureMatrix;
  30275. }
  30276. }
  30277. if (!this._cachedTextureMatrix) {
  30278. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30279. }
  30280. if (!this._projectionModeMatrix) {
  30281. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30282. }
  30283. this._cachedUOffset = this.uOffset;
  30284. this._cachedVOffset = this.vOffset;
  30285. this._cachedUScale = this.uScale;
  30286. this._cachedVScale = this.vScale;
  30287. this._cachedCoordinatesMode = this.coordinatesMode;
  30288. switch (this.coordinatesMode) {
  30289. case Texture.PLANAR_MODE:
  30290. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30291. this._cachedTextureMatrix[0] = this.uScale;
  30292. this._cachedTextureMatrix[5] = this.vScale;
  30293. this._cachedTextureMatrix[12] = this.uOffset;
  30294. this._cachedTextureMatrix[13] = this.vOffset;
  30295. break;
  30296. case Texture.PROJECTION_MODE:
  30297. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30298. this._projectionModeMatrix.m[0] = 0.5;
  30299. this._projectionModeMatrix.m[5] = -0.5;
  30300. this._projectionModeMatrix.m[10] = 0.0;
  30301. this._projectionModeMatrix.m[12] = 0.5;
  30302. this._projectionModeMatrix.m[13] = 0.5;
  30303. this._projectionModeMatrix.m[14] = 1.0;
  30304. this._projectionModeMatrix.m[15] = 1.0;
  30305. var projectionMatrix = scene.getProjectionMatrix();
  30306. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30307. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30308. break;
  30309. default:
  30310. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30311. break;
  30312. }
  30313. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30314. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30315. });
  30316. return this._cachedTextureMatrix;
  30317. };
  30318. Texture.prototype.clone = function () {
  30319. var _this = this;
  30320. return BABYLON.SerializationHelper.Clone(function () {
  30321. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30322. }, this);
  30323. };
  30324. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30325. get: function () {
  30326. if (!this._onLoadObservable) {
  30327. this._onLoadObservable = new BABYLON.Observable();
  30328. }
  30329. return this._onLoadObservable;
  30330. },
  30331. enumerable: true,
  30332. configurable: true
  30333. });
  30334. Texture.prototype.serialize = function () {
  30335. var serializationObject = _super.prototype.serialize.call(this);
  30336. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30337. serializationObject.base64String = this._buffer;
  30338. serializationObject.name = serializationObject.name.replace("data:", "");
  30339. }
  30340. serializationObject.invertY = this._invertY;
  30341. serializationObject.samplingMode = this.samplingMode;
  30342. return serializationObject;
  30343. };
  30344. Texture.prototype.getClassName = function () {
  30345. return "Texture";
  30346. };
  30347. Texture.prototype.dispose = function () {
  30348. _super.prototype.dispose.call(this);
  30349. if (this._onLoadObservable) {
  30350. this._onLoadObservable.clear();
  30351. this._onLoadObservable = null;
  30352. }
  30353. this._delayedOnLoad = null;
  30354. this._delayedOnError = null;
  30355. };
  30356. // Statics
  30357. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30358. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30359. if (onLoad === void 0) { onLoad = null; }
  30360. if (onError === void 0) { onError = null; }
  30361. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30362. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30363. };
  30364. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30365. if (parsedTexture.customType) {
  30366. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30367. // Update Sampling Mode
  30368. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30369. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30370. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30371. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30372. }
  30373. }
  30374. return parsedCustomTexture;
  30375. }
  30376. if (parsedTexture.isCube) {
  30377. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30378. }
  30379. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30380. return null;
  30381. }
  30382. var texture = BABYLON.SerializationHelper.Parse(function () {
  30383. var generateMipMaps = true;
  30384. if (parsedTexture.noMipmap) {
  30385. generateMipMaps = false;
  30386. }
  30387. if (parsedTexture.mirrorPlane) {
  30388. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30389. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30390. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30391. return mirrorTexture;
  30392. }
  30393. else if (parsedTexture.isRenderTarget) {
  30394. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30395. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30396. return renderTargetTexture;
  30397. }
  30398. else {
  30399. var texture;
  30400. if (parsedTexture.base64String) {
  30401. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30402. }
  30403. else {
  30404. var url = rootUrl + parsedTexture.name;
  30405. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30406. url = parsedTexture.url;
  30407. }
  30408. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30409. }
  30410. return texture;
  30411. }
  30412. }, parsedTexture, scene);
  30413. // Update Sampling Mode
  30414. if (parsedTexture.samplingMode) {
  30415. var sampling = parsedTexture.samplingMode;
  30416. if (texture._samplingMode !== sampling) {
  30417. texture.updateSamplingMode(sampling);
  30418. }
  30419. }
  30420. // Animations
  30421. if (parsedTexture.animations) {
  30422. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30423. var parsedAnimation = parsedTexture.animations[animationIndex];
  30424. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30425. }
  30426. }
  30427. return texture;
  30428. };
  30429. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30430. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30431. if (noMipmap === void 0) { noMipmap = false; }
  30432. if (invertY === void 0) { invertY = true; }
  30433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30434. if (onLoad === void 0) { onLoad = null; }
  30435. if (onError === void 0) { onError = null; }
  30436. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30437. if (name.substr(0, 5) !== "data:") {
  30438. name = "data:" + name;
  30439. }
  30440. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30441. };
  30442. // Constants
  30443. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30444. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30445. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30446. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30447. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30448. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30449. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30450. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30451. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30452. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30453. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30454. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30455. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30456. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30457. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30458. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30459. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30460. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30461. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30462. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30463. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30464. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30465. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30466. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30467. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30468. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30469. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30470. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30471. /**
  30472. * 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
  30473. */
  30474. Texture.UseSerializedUrlIfAny = false;
  30475. __decorate([
  30476. BABYLON.serialize()
  30477. ], Texture.prototype, "url", void 0);
  30478. __decorate([
  30479. BABYLON.serialize()
  30480. ], Texture.prototype, "uOffset", void 0);
  30481. __decorate([
  30482. BABYLON.serialize()
  30483. ], Texture.prototype, "vOffset", void 0);
  30484. __decorate([
  30485. BABYLON.serialize()
  30486. ], Texture.prototype, "uScale", void 0);
  30487. __decorate([
  30488. BABYLON.serialize()
  30489. ], Texture.prototype, "vScale", void 0);
  30490. __decorate([
  30491. BABYLON.serialize()
  30492. ], Texture.prototype, "uAng", void 0);
  30493. __decorate([
  30494. BABYLON.serialize()
  30495. ], Texture.prototype, "vAng", void 0);
  30496. __decorate([
  30497. BABYLON.serialize()
  30498. ], Texture.prototype, "wAng", void 0);
  30499. __decorate([
  30500. BABYLON.serialize()
  30501. ], Texture.prototype, "uRotationCenter", void 0);
  30502. __decorate([
  30503. BABYLON.serialize()
  30504. ], Texture.prototype, "vRotationCenter", void 0);
  30505. __decorate([
  30506. BABYLON.serialize()
  30507. ], Texture.prototype, "wRotationCenter", void 0);
  30508. __decorate([
  30509. BABYLON.serialize()
  30510. ], Texture.prototype, "isBlocking", null);
  30511. return Texture;
  30512. }(BABYLON.BaseTexture));
  30513. BABYLON.Texture = Texture;
  30514. })(BABYLON || (BABYLON = {}));
  30515. //# sourceMappingURL=babylon.texture.js.map
  30516. var BABYLON;
  30517. (function (BABYLON) {
  30518. /**
  30519. * @hidden
  30520. **/
  30521. var _InstancesBatch = /** @class */ (function () {
  30522. function _InstancesBatch() {
  30523. this.mustReturn = false;
  30524. this.visibleInstances = new Array();
  30525. this.renderSelf = new Array();
  30526. }
  30527. return _InstancesBatch;
  30528. }());
  30529. BABYLON._InstancesBatch = _InstancesBatch;
  30530. var Mesh = /** @class */ (function (_super) {
  30531. __extends(Mesh, _super);
  30532. /**
  30533. * @constructor
  30534. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30535. * @param {Scene} scene The scene to add this mesh to.
  30536. * @param {Node} parent The parent of this mesh, if it has one
  30537. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30538. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30539. * When false, achieved by calling a clone(), also passing False.
  30540. * This will make creation of children, recursive.
  30541. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30542. */
  30543. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30544. if (scene === void 0) { scene = null; }
  30545. if (parent === void 0) { parent = null; }
  30546. if (source === void 0) { source = null; }
  30547. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30548. var _this = _super.call(this, name, scene) || this;
  30549. // Members
  30550. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30551. _this.instances = new Array();
  30552. _this._LODLevels = new Array();
  30553. /** @hidden */
  30554. _this._visibleInstances = {};
  30555. _this._renderIdForInstances = new Array();
  30556. _this._batchCache = new _InstancesBatch();
  30557. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30558. // Use by builder only to know what orientation were the mesh build in.
  30559. /** @hidden */
  30560. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30561. _this.overrideMaterialSideOrientation = null;
  30562. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30563. // Will be used to save a source mesh reference, If any
  30564. _this._source = null;
  30565. scene = _this.getScene();
  30566. if (source) {
  30567. // Geometry
  30568. if (source._geometry) {
  30569. source._geometry.applyToMesh(_this);
  30570. }
  30571. // Deep copy
  30572. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30573. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30574. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30575. ], ["_poseMatrix"]);
  30576. // Source mesh
  30577. _this._source = source;
  30578. // Construction Params
  30579. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30580. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30581. var myAnyThis = _this;
  30582. var myAnySource = source;
  30583. myAnyThis._closePath = myAnySource._closePath;
  30584. myAnyThis._idx = myAnySource._idx;
  30585. myAnyThis.dashSize = myAnySource.dashSize;
  30586. myAnyThis.gapSize = myAnySource.gapSize;
  30587. myAnyThis.path3D = myAnySource.path3D;
  30588. myAnyThis.pathArray = myAnySource.pathArray;
  30589. myAnyThis.arc = myAnySource.arc;
  30590. myAnyThis.radius = myAnySource.radius;
  30591. // Animation ranges
  30592. if (_this._source._ranges) {
  30593. var ranges = _this._source._ranges;
  30594. for (var name in ranges) {
  30595. if (!ranges.hasOwnProperty(name)) {
  30596. continue;
  30597. }
  30598. if (!ranges[name]) {
  30599. continue;
  30600. }
  30601. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30602. }
  30603. }
  30604. // Metadata
  30605. if (source.metadata && source.metadata.clone) {
  30606. _this.metadata = source.metadata.clone();
  30607. }
  30608. else {
  30609. _this.metadata = source.metadata;
  30610. }
  30611. // Tags
  30612. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30613. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30614. }
  30615. // Parent
  30616. _this.parent = source.parent;
  30617. // Pivot
  30618. _this.setPivotMatrix(source.getPivotMatrix());
  30619. _this.id = name + "." + source.id;
  30620. // Material
  30621. _this.material = source.material;
  30622. var index;
  30623. if (!doNotCloneChildren) {
  30624. // Children
  30625. var directDescendants = source.getDescendants(true);
  30626. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30627. var child = directDescendants[index_1];
  30628. if (child.clone) {
  30629. child.clone(name + "." + child.name, _this);
  30630. }
  30631. }
  30632. }
  30633. // Physics clone
  30634. var physicsEngine = _this.getScene().getPhysicsEngine();
  30635. if (clonePhysicsImpostor && physicsEngine) {
  30636. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30637. if (impostor) {
  30638. _this.physicsImpostor = impostor.clone(_this);
  30639. }
  30640. }
  30641. // Particles
  30642. for (index = 0; index < scene.particleSystems.length; index++) {
  30643. var system = scene.particleSystems[index];
  30644. if (system.emitter === source) {
  30645. system.clone(system.name, _this);
  30646. }
  30647. }
  30648. _this.refreshBoundingInfo();
  30649. _this.computeWorldMatrix(true);
  30650. }
  30651. // Parent
  30652. if (parent !== null) {
  30653. _this.parent = parent;
  30654. }
  30655. return _this;
  30656. }
  30657. Object.defineProperty(Mesh, "FRONTSIDE", {
  30658. /**
  30659. * Mesh side orientation : usually the external or front surface
  30660. */
  30661. get: function () {
  30662. return Mesh._FRONTSIDE;
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(Mesh, "BACKSIDE", {
  30668. /**
  30669. * Mesh side orientation : usually the internal or back surface
  30670. */
  30671. get: function () {
  30672. return Mesh._BACKSIDE;
  30673. },
  30674. enumerable: true,
  30675. configurable: true
  30676. });
  30677. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30678. /**
  30679. * Mesh side orientation : both internal and external or front and back surfaces
  30680. */
  30681. get: function () {
  30682. return Mesh._DOUBLESIDE;
  30683. },
  30684. enumerable: true,
  30685. configurable: true
  30686. });
  30687. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30688. /**
  30689. * Mesh side orientation : by default, `FRONTSIDE`
  30690. */
  30691. get: function () {
  30692. return Mesh._DEFAULTSIDE;
  30693. },
  30694. enumerable: true,
  30695. configurable: true
  30696. });
  30697. Object.defineProperty(Mesh, "NO_CAP", {
  30698. /**
  30699. * Mesh cap setting : no cap
  30700. */
  30701. get: function () {
  30702. return Mesh._NO_CAP;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. Object.defineProperty(Mesh, "CAP_START", {
  30708. /**
  30709. * Mesh cap setting : one cap at the beginning of the mesh
  30710. */
  30711. get: function () {
  30712. return Mesh._CAP_START;
  30713. },
  30714. enumerable: true,
  30715. configurable: true
  30716. });
  30717. Object.defineProperty(Mesh, "CAP_END", {
  30718. /**
  30719. * Mesh cap setting : one cap at the end of the mesh
  30720. */
  30721. get: function () {
  30722. return Mesh._CAP_END;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. Object.defineProperty(Mesh, "CAP_ALL", {
  30728. /**
  30729. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30730. */
  30731. get: function () {
  30732. return Mesh._CAP_ALL;
  30733. },
  30734. enumerable: true,
  30735. configurable: true
  30736. });
  30737. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30738. /**
  30739. * An event triggered before rendering the mesh
  30740. */
  30741. get: function () {
  30742. if (!this._onBeforeRenderObservable) {
  30743. this._onBeforeRenderObservable = new BABYLON.Observable();
  30744. }
  30745. return this._onBeforeRenderObservable;
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30751. /**
  30752. * An event triggered after rendering the mesh
  30753. */
  30754. get: function () {
  30755. if (!this._onAfterRenderObservable) {
  30756. this._onAfterRenderObservable = new BABYLON.Observable();
  30757. }
  30758. return this._onAfterRenderObservable;
  30759. },
  30760. enumerable: true,
  30761. configurable: true
  30762. });
  30763. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30764. /**
  30765. * An event triggered before drawing the mesh
  30766. */
  30767. get: function () {
  30768. if (!this._onBeforeDrawObservable) {
  30769. this._onBeforeDrawObservable = new BABYLON.Observable();
  30770. }
  30771. return this._onBeforeDrawObservable;
  30772. },
  30773. enumerable: true,
  30774. configurable: true
  30775. });
  30776. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30777. set: function (callback) {
  30778. if (this._onBeforeDrawObserver) {
  30779. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30780. }
  30781. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30787. get: function () {
  30788. return this._morphTargetManager;
  30789. },
  30790. set: function (value) {
  30791. if (this._morphTargetManager === value) {
  30792. return;
  30793. }
  30794. this._morphTargetManager = value;
  30795. this._syncGeometryWithMorphTargetManager();
  30796. },
  30797. enumerable: true,
  30798. configurable: true
  30799. });
  30800. Object.defineProperty(Mesh.prototype, "source", {
  30801. get: function () {
  30802. return this._source;
  30803. },
  30804. enumerable: true,
  30805. configurable: true
  30806. });
  30807. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30808. get: function () {
  30809. return this._unIndexed;
  30810. },
  30811. set: function (value) {
  30812. if (this._unIndexed !== value) {
  30813. this._unIndexed = value;
  30814. this._markSubMeshesAsAttributesDirty();
  30815. }
  30816. },
  30817. enumerable: true,
  30818. configurable: true
  30819. });
  30820. // Methods
  30821. /**
  30822. * Returns the string "Mesh".
  30823. */
  30824. Mesh.prototype.getClassName = function () {
  30825. return "Mesh";
  30826. };
  30827. /**
  30828. * Returns a string.
  30829. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30830. */
  30831. Mesh.prototype.toString = function (fullDetails) {
  30832. var ret = _super.prototype.toString.call(this, fullDetails);
  30833. ret += ", n vertices: " + this.getTotalVertices();
  30834. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30835. if (this.animations) {
  30836. for (var i = 0; i < this.animations.length; i++) {
  30837. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30838. }
  30839. }
  30840. if (fullDetails) {
  30841. if (this._geometry) {
  30842. var ib = this.getIndices();
  30843. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30844. if (vb && ib) {
  30845. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30846. }
  30847. }
  30848. else {
  30849. ret += ", flat shading: UNKNOWN";
  30850. }
  30851. }
  30852. return ret;
  30853. };
  30854. /** @hidden */
  30855. Mesh.prototype._unBindEffect = function () {
  30856. _super.prototype._unBindEffect.call(this);
  30857. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30858. var instance = _a[_i];
  30859. instance._unBindEffect();
  30860. }
  30861. };
  30862. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30863. /**
  30864. * True if the mesh has some Levels Of Details (LOD).
  30865. * Returns a boolean.
  30866. */
  30867. get: function () {
  30868. return this._LODLevels.length > 0;
  30869. },
  30870. enumerable: true,
  30871. configurable: true
  30872. });
  30873. /**
  30874. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30875. * @returns an array of {BABYLON.MeshLODLevel}
  30876. */
  30877. Mesh.prototype.getLODLevels = function () {
  30878. return this._LODLevels;
  30879. };
  30880. Mesh.prototype._sortLODLevels = function () {
  30881. this._LODLevels.sort(function (a, b) {
  30882. if (a.distance < b.distance) {
  30883. return 1;
  30884. }
  30885. if (a.distance > b.distance) {
  30886. return -1;
  30887. }
  30888. return 0;
  30889. });
  30890. };
  30891. /**
  30892. * Add a mesh as LOD level triggered at the given distance.
  30893. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30894. * @param distance The distance from the center of the object to show this level
  30895. * @param mesh The mesh to be added as LOD level (can be null)
  30896. * @return This mesh (for chaining)
  30897. */
  30898. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30899. if (mesh && mesh._masterMesh) {
  30900. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30901. return this;
  30902. }
  30903. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30904. this._LODLevels.push(level);
  30905. if (mesh) {
  30906. mesh._masterMesh = this;
  30907. }
  30908. this._sortLODLevels();
  30909. return this;
  30910. };
  30911. /**
  30912. * Returns the LOD level mesh at the passed distance or null if not found.
  30913. * It is related to the method `addLODLevel(distance, mesh)`.
  30914. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30915. * Returns an object Mesh or `null`.
  30916. */
  30917. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30918. for (var index = 0; index < this._LODLevels.length; index++) {
  30919. var level = this._LODLevels[index];
  30920. if (level.distance === distance) {
  30921. return level.mesh;
  30922. }
  30923. }
  30924. return null;
  30925. };
  30926. /**
  30927. * Remove a mesh from the LOD array
  30928. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30929. * @param {Mesh} mesh The mesh to be removed.
  30930. * @return {Mesh} This mesh (for chaining)
  30931. */
  30932. Mesh.prototype.removeLODLevel = function (mesh) {
  30933. for (var index = 0; index < this._LODLevels.length; index++) {
  30934. if (this._LODLevels[index].mesh === mesh) {
  30935. this._LODLevels.splice(index, 1);
  30936. if (mesh) {
  30937. mesh._masterMesh = null;
  30938. }
  30939. }
  30940. }
  30941. this._sortLODLevels();
  30942. return this;
  30943. };
  30944. /**
  30945. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30946. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  30947. */
  30948. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30949. if (!this._LODLevels || this._LODLevels.length === 0) {
  30950. return this;
  30951. }
  30952. var bSphere;
  30953. if (boundingSphere) {
  30954. bSphere = boundingSphere;
  30955. }
  30956. else {
  30957. var boundingInfo = this.getBoundingInfo();
  30958. bSphere = boundingInfo.boundingSphere;
  30959. }
  30960. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30961. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30962. if (this.onLODLevelSelection) {
  30963. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30964. }
  30965. return this;
  30966. }
  30967. for (var index = 0; index < this._LODLevels.length; index++) {
  30968. var level = this._LODLevels[index];
  30969. if (level.distance < distanceToCamera) {
  30970. if (level.mesh) {
  30971. level.mesh._preActivate();
  30972. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30973. }
  30974. if (this.onLODLevelSelection) {
  30975. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30976. }
  30977. return level.mesh;
  30978. }
  30979. }
  30980. if (this.onLODLevelSelection) {
  30981. this.onLODLevelSelection(distanceToCamera, this, this);
  30982. }
  30983. return this;
  30984. };
  30985. Object.defineProperty(Mesh.prototype, "geometry", {
  30986. /**
  30987. * Returns the mesh internal Geometry object.
  30988. */
  30989. get: function () {
  30990. return this._geometry;
  30991. },
  30992. enumerable: true,
  30993. configurable: true
  30994. });
  30995. /**
  30996. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30997. */
  30998. Mesh.prototype.getTotalVertices = function () {
  30999. if (this._geometry === null || this._geometry === undefined) {
  31000. return 0;
  31001. }
  31002. return this._geometry.getTotalVertices();
  31003. };
  31004. /**
  31005. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31006. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31007. * You can force the copy with forceCopy === true
  31008. * Returns null if the mesh has no geometry or no vertex buffer.
  31009. * Possible `kind` values :
  31010. * - BABYLON.VertexBuffer.PositionKind
  31011. * - BABYLON.VertexBuffer.UVKind
  31012. * - BABYLON.VertexBuffer.UV2Kind
  31013. * - BABYLON.VertexBuffer.UV3Kind
  31014. * - BABYLON.VertexBuffer.UV4Kind
  31015. * - BABYLON.VertexBuffer.UV5Kind
  31016. * - BABYLON.VertexBuffer.UV6Kind
  31017. * - BABYLON.VertexBuffer.ColorKind
  31018. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31019. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31020. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31021. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31022. */
  31023. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31024. if (!this._geometry) {
  31025. return null;
  31026. }
  31027. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31028. };
  31029. /**
  31030. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31031. * Returns `null` if the mesh has no geometry.
  31032. * Possible `kind` values :
  31033. * - BABYLON.VertexBuffer.PositionKind
  31034. * - BABYLON.VertexBuffer.UVKind
  31035. * - BABYLON.VertexBuffer.UV2Kind
  31036. * - BABYLON.VertexBuffer.UV3Kind
  31037. * - BABYLON.VertexBuffer.UV4Kind
  31038. * - BABYLON.VertexBuffer.UV5Kind
  31039. * - BABYLON.VertexBuffer.UV6Kind
  31040. * - BABYLON.VertexBuffer.ColorKind
  31041. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31042. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31043. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31044. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31045. */
  31046. Mesh.prototype.getVertexBuffer = function (kind) {
  31047. if (!this._geometry) {
  31048. return null;
  31049. }
  31050. return this._geometry.getVertexBuffer(kind);
  31051. };
  31052. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31053. if (!this._geometry) {
  31054. if (this._delayInfo) {
  31055. return this._delayInfo.indexOf(kind) !== -1;
  31056. }
  31057. return false;
  31058. }
  31059. return this._geometry.isVerticesDataPresent(kind);
  31060. };
  31061. /**
  31062. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31063. * Possible `kind` values :
  31064. * - BABYLON.VertexBuffer.PositionKind
  31065. * - BABYLON.VertexBuffer.UVKind
  31066. * - BABYLON.VertexBuffer.UV2Kind
  31067. * - BABYLON.VertexBuffer.UV3Kind
  31068. * - BABYLON.VertexBuffer.UV4Kind
  31069. * - BABYLON.VertexBuffer.UV5Kind
  31070. * - BABYLON.VertexBuffer.UV6Kind
  31071. * - BABYLON.VertexBuffer.ColorKind
  31072. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31073. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31074. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31075. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31076. */
  31077. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31078. if (!this._geometry) {
  31079. if (this._delayInfo) {
  31080. return this._delayInfo.indexOf(kind) !== -1;
  31081. }
  31082. return false;
  31083. }
  31084. return this._geometry.isVertexBufferUpdatable(kind);
  31085. };
  31086. /**
  31087. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31088. * Possible `kind` values :
  31089. * - BABYLON.VertexBuffer.PositionKind
  31090. * - BABYLON.VertexBuffer.UVKind
  31091. * - BABYLON.VertexBuffer.UV2Kind
  31092. * - BABYLON.VertexBuffer.UV3Kind
  31093. * - BABYLON.VertexBuffer.UV4Kind
  31094. * - BABYLON.VertexBuffer.UV5Kind
  31095. * - BABYLON.VertexBuffer.UV6Kind
  31096. * - BABYLON.VertexBuffer.ColorKind
  31097. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31098. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31099. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31100. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31101. */
  31102. Mesh.prototype.getVerticesDataKinds = function () {
  31103. if (!this._geometry) {
  31104. var result = new Array();
  31105. if (this._delayInfo) {
  31106. this._delayInfo.forEach(function (kind, index, array) {
  31107. result.push(kind);
  31108. });
  31109. }
  31110. return result;
  31111. }
  31112. return this._geometry.getVerticesDataKinds();
  31113. };
  31114. /**
  31115. * Returns a positive integer : the total number of indices in this mesh geometry.
  31116. * Returns zero if the mesh has no geometry.
  31117. */
  31118. Mesh.prototype.getTotalIndices = function () {
  31119. if (!this._geometry) {
  31120. return 0;
  31121. }
  31122. return this._geometry.getTotalIndices();
  31123. };
  31124. /**
  31125. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31126. * @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.
  31127. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31128. * @returns the indices array or an empty array if the mesh has no geometry
  31129. */
  31130. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31131. if (!this._geometry) {
  31132. return [];
  31133. }
  31134. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31135. };
  31136. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31137. get: function () {
  31138. return this._masterMesh !== null && this._masterMesh !== undefined;
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. /**
  31144. * Determine if the current mesh is ready to be rendered
  31145. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31146. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31147. * @returns true if all associated assets are ready (material, textures, shaders)
  31148. */
  31149. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31150. if (completeCheck === void 0) { completeCheck = false; }
  31151. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31152. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31153. return false;
  31154. }
  31155. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31156. return false;
  31157. }
  31158. if (!this.subMeshes || this.subMeshes.length === 0) {
  31159. return true;
  31160. }
  31161. if (!completeCheck) {
  31162. return true;
  31163. }
  31164. var engine = this.getEngine();
  31165. var scene = this.getScene();
  31166. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31167. this.computeWorldMatrix();
  31168. var mat = this.material || scene.defaultMaterial;
  31169. if (mat) {
  31170. if (mat.storeEffectOnSubMeshes) {
  31171. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31172. var subMesh = _a[_i];
  31173. var effectiveMaterial = subMesh.getMaterial();
  31174. if (effectiveMaterial) {
  31175. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31176. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31177. return false;
  31178. }
  31179. }
  31180. else {
  31181. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31182. return false;
  31183. }
  31184. }
  31185. }
  31186. }
  31187. }
  31188. else {
  31189. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31190. return false;
  31191. }
  31192. }
  31193. }
  31194. // Shadows
  31195. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31196. var light = _c[_b];
  31197. var generator = light.getShadowGenerator();
  31198. if (generator) {
  31199. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31200. var subMesh = _e[_d];
  31201. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31202. return false;
  31203. }
  31204. }
  31205. }
  31206. }
  31207. // LOD
  31208. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31209. var lod = _g[_f];
  31210. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31211. return false;
  31212. }
  31213. }
  31214. return true;
  31215. };
  31216. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31217. /**
  31218. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31219. * This property is pertinent only for updatable parametric shapes.
  31220. */
  31221. get: function () {
  31222. return this._areNormalsFrozen;
  31223. },
  31224. enumerable: true,
  31225. configurable: true
  31226. });
  31227. /**
  31228. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31229. * It has no effect at all on other shapes.
  31230. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31231. * Returns the Mesh.
  31232. */
  31233. Mesh.prototype.freezeNormals = function () {
  31234. this._areNormalsFrozen = true;
  31235. return this;
  31236. };
  31237. /**
  31238. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31239. * It has no effect at all on other shapes.
  31240. * It reactivates the mesh normals computation if it was previously frozen.
  31241. * Returns the Mesh.
  31242. */
  31243. Mesh.prototype.unfreezeNormals = function () {
  31244. this._areNormalsFrozen = false;
  31245. return this;
  31246. };
  31247. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31248. /**
  31249. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31250. */
  31251. set: function (count) {
  31252. this._overridenInstanceCount = count;
  31253. },
  31254. enumerable: true,
  31255. configurable: true
  31256. });
  31257. // Methods
  31258. /** @hidden */
  31259. Mesh.prototype._preActivate = function () {
  31260. var sceneRenderId = this.getScene().getRenderId();
  31261. if (this._preActivateId === sceneRenderId) {
  31262. return this;
  31263. }
  31264. this._preActivateId = sceneRenderId;
  31265. this._visibleInstances = null;
  31266. return this;
  31267. };
  31268. /** @hidden */
  31269. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31270. if (this._visibleInstances) {
  31271. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31272. }
  31273. return this;
  31274. };
  31275. /** @hidden */
  31276. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31277. if (!this._visibleInstances) {
  31278. this._visibleInstances = {};
  31279. this._visibleInstances.defaultRenderId = renderId;
  31280. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31281. }
  31282. if (!this._visibleInstances[renderId]) {
  31283. this._visibleInstances[renderId] = new Array();
  31284. }
  31285. this._visibleInstances[renderId].push(instance);
  31286. return this;
  31287. };
  31288. /**
  31289. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31290. * This means the mesh underlying bounding box and sphere are recomputed.
  31291. * Returns the Mesh.
  31292. */
  31293. Mesh.prototype.refreshBoundingInfo = function () {
  31294. return this._refreshBoundingInfo(false);
  31295. };
  31296. /** @hidden */
  31297. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31298. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31299. return this;
  31300. }
  31301. var data = this._getPositionData(applySkeleton);
  31302. if (data) {
  31303. var bias = this.geometry ? this.geometry.boundingBias : null;
  31304. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31305. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31306. }
  31307. if (this.subMeshes) {
  31308. for (var index = 0; index < this.subMeshes.length; index++) {
  31309. this.subMeshes[index].refreshBoundingInfo();
  31310. }
  31311. }
  31312. this._updateBoundingInfo();
  31313. return this;
  31314. };
  31315. Mesh.prototype._getPositionData = function (applySkeleton) {
  31316. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31317. if (data && applySkeleton && this.skeleton) {
  31318. data = BABYLON.Tools.Slice(data);
  31319. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31320. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31321. if (matricesWeightsData && matricesIndicesData) {
  31322. var needExtras = this.numBoneInfluencers > 4;
  31323. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31324. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31325. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31326. var tempVector = BABYLON.Tmp.Vector3[0];
  31327. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31328. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31329. var matWeightIdx = 0;
  31330. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31331. finalMatrix.reset();
  31332. var inf;
  31333. var weight;
  31334. for (inf = 0; inf < 4; inf++) {
  31335. weight = matricesWeightsData[matWeightIdx + inf];
  31336. if (weight > 0) {
  31337. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31338. finalMatrix.addToSelf(tempMatrix);
  31339. }
  31340. }
  31341. if (needExtras) {
  31342. for (inf = 0; inf < 4; inf++) {
  31343. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31344. if (weight > 0) {
  31345. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31346. finalMatrix.addToSelf(tempMatrix);
  31347. }
  31348. }
  31349. }
  31350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31351. tempVector.toArray(data, index);
  31352. }
  31353. }
  31354. }
  31355. return data;
  31356. };
  31357. /** @hidden */
  31358. Mesh.prototype._createGlobalSubMesh = function (force) {
  31359. var totalVertices = this.getTotalVertices();
  31360. if (!totalVertices || !this.getIndices()) {
  31361. return null;
  31362. }
  31363. // Check if we need to recreate the submeshes
  31364. if (this.subMeshes && this.subMeshes.length > 0) {
  31365. var ib = this.getIndices();
  31366. if (!ib) {
  31367. return null;
  31368. }
  31369. var totalIndices = ib.length;
  31370. var needToRecreate = false;
  31371. if (force) {
  31372. needToRecreate = true;
  31373. }
  31374. else {
  31375. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31376. var submesh = _a[_i];
  31377. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31378. needToRecreate = true;
  31379. break;
  31380. }
  31381. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31382. needToRecreate = true;
  31383. break;
  31384. }
  31385. }
  31386. }
  31387. if (!needToRecreate) {
  31388. return this.subMeshes[0];
  31389. }
  31390. }
  31391. this.releaseSubMeshes();
  31392. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31393. };
  31394. Mesh.prototype.subdivide = function (count) {
  31395. if (count < 1) {
  31396. return;
  31397. }
  31398. var totalIndices = this.getTotalIndices();
  31399. var subdivisionSize = (totalIndices / count) | 0;
  31400. var offset = 0;
  31401. // Ensure that subdivisionSize is a multiple of 3
  31402. while (subdivisionSize % 3 !== 0) {
  31403. subdivisionSize++;
  31404. }
  31405. this.releaseSubMeshes();
  31406. for (var index = 0; index < count; index++) {
  31407. if (offset >= totalIndices) {
  31408. break;
  31409. }
  31410. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31411. offset += subdivisionSize;
  31412. }
  31413. this.synchronizeInstances();
  31414. };
  31415. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31416. if (updatable === void 0) { updatable = false; }
  31417. if (!this._geometry) {
  31418. var vertexData = new BABYLON.VertexData();
  31419. vertexData.set(data, kind);
  31420. var scene = this.getScene();
  31421. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31422. }
  31423. else {
  31424. this._geometry.setVerticesData(kind, data, updatable, stride);
  31425. }
  31426. return this;
  31427. };
  31428. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31429. if (updatable === void 0) { updatable = true; }
  31430. var vb = this.getVertexBuffer(kind);
  31431. if (!vb || vb.isUpdatable() === updatable) {
  31432. return;
  31433. }
  31434. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31435. };
  31436. /**
  31437. * Sets the mesh VertexBuffer.
  31438. * Returns the Mesh.
  31439. */
  31440. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31441. if (!this._geometry) {
  31442. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31443. }
  31444. this._geometry.setVerticesBuffer(buffer);
  31445. return this;
  31446. };
  31447. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31448. if (!this._geometry) {
  31449. return this;
  31450. }
  31451. if (!makeItUnique) {
  31452. this._geometry.updateVerticesData(kind, data, updateExtends);
  31453. }
  31454. else {
  31455. this.makeGeometryUnique();
  31456. this.updateVerticesData(kind, data, updateExtends, false);
  31457. }
  31458. return this;
  31459. };
  31460. /**
  31461. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31462. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31463. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31464. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31465. * Returns the Mesh.
  31466. */
  31467. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31468. if (computeNormals === void 0) { computeNormals = true; }
  31469. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31470. if (!positions) {
  31471. return this;
  31472. }
  31473. positionFunction(positions);
  31474. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31475. if (computeNormals) {
  31476. var indices = this.getIndices();
  31477. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31478. if (!normals) {
  31479. return this;
  31480. }
  31481. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31482. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31483. }
  31484. return this;
  31485. };
  31486. /**
  31487. * Creates a un-shared specific occurence of the geometry for the mesh.
  31488. * Returns the Mesh.
  31489. */
  31490. Mesh.prototype.makeGeometryUnique = function () {
  31491. if (!this._geometry) {
  31492. return this;
  31493. }
  31494. var oldGeometry = this._geometry;
  31495. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31496. oldGeometry.releaseForMesh(this, true);
  31497. geometry.applyToMesh(this);
  31498. return this;
  31499. };
  31500. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31501. if (totalVertices === void 0) { totalVertices = null; }
  31502. if (updatable === void 0) { updatable = false; }
  31503. if (!this._geometry) {
  31504. var vertexData = new BABYLON.VertexData();
  31505. vertexData.indices = indices;
  31506. var scene = this.getScene();
  31507. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31508. }
  31509. else {
  31510. this._geometry.setIndices(indices, totalVertices, updatable);
  31511. }
  31512. return this;
  31513. };
  31514. /**
  31515. * Update the current index buffer
  31516. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31517. * Returns the Mesh.
  31518. */
  31519. Mesh.prototype.updateIndices = function (indices, offset) {
  31520. if (!this._geometry) {
  31521. return this;
  31522. }
  31523. this._geometry.updateIndices(indices, offset);
  31524. return this;
  31525. };
  31526. /**
  31527. * Invert the geometry to move from a right handed system to a left handed one.
  31528. * Returns the Mesh.
  31529. */
  31530. Mesh.prototype.toLeftHanded = function () {
  31531. if (!this._geometry) {
  31532. return this;
  31533. }
  31534. this._geometry.toLeftHanded();
  31535. return this;
  31536. };
  31537. /** @hidden */
  31538. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31539. if (!this._geometry) {
  31540. return this;
  31541. }
  31542. var engine = this.getScene().getEngine();
  31543. // Wireframe
  31544. var indexToBind;
  31545. if (this._unIndexed) {
  31546. indexToBind = null;
  31547. }
  31548. else {
  31549. switch (fillMode) {
  31550. case BABYLON.Material.PointFillMode:
  31551. indexToBind = null;
  31552. break;
  31553. case BABYLON.Material.WireFrameFillMode:
  31554. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31555. break;
  31556. default:
  31557. case BABYLON.Material.TriangleFillMode:
  31558. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31559. break;
  31560. }
  31561. }
  31562. // VBOs
  31563. this._geometry._bind(effect, indexToBind);
  31564. return this;
  31565. };
  31566. /** @hidden */
  31567. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31568. if (alternate === void 0) { alternate = false; }
  31569. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31570. return this;
  31571. }
  31572. if (this._onBeforeDrawObservable) {
  31573. this._onBeforeDrawObservable.notifyObservers(this);
  31574. }
  31575. var scene = this.getScene();
  31576. var engine = scene.getEngine();
  31577. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31578. // or triangles as points
  31579. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31580. }
  31581. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31582. // Triangles as wireframe
  31583. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31584. }
  31585. else {
  31586. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31587. }
  31588. if (scene._isAlternateRenderingEnabled && !alternate) {
  31589. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31590. if (!effect || !scene.activeCamera) {
  31591. return this;
  31592. }
  31593. scene._switchToAlternateCameraConfiguration(true);
  31594. this._effectiveMaterial.bindView(effect);
  31595. this._effectiveMaterial.bindViewProjection(effect);
  31596. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31597. this._draw(subMesh, fillMode, instancesCount, true);
  31598. engine.setViewport(scene.activeCamera.viewport);
  31599. scene._switchToAlternateCameraConfiguration(false);
  31600. this._effectiveMaterial.bindView(effect);
  31601. this._effectiveMaterial.bindViewProjection(effect);
  31602. }
  31603. return this;
  31604. };
  31605. /**
  31606. * Registers for this mesh a javascript function called just before the rendering process.
  31607. * This function is passed the current mesh.
  31608. * Return the Mesh.
  31609. */
  31610. Mesh.prototype.registerBeforeRender = function (func) {
  31611. this.onBeforeRenderObservable.add(func);
  31612. return this;
  31613. };
  31614. /**
  31615. * Disposes a previously registered javascript function called before the rendering.
  31616. * This function is passed the current mesh.
  31617. * Returns the Mesh.
  31618. */
  31619. Mesh.prototype.unregisterBeforeRender = function (func) {
  31620. this.onBeforeRenderObservable.removeCallback(func);
  31621. return this;
  31622. };
  31623. /**
  31624. * Registers for this mesh a javascript function called just after the rendering is complete.
  31625. * This function is passed the current mesh.
  31626. * Returns the Mesh.
  31627. */
  31628. Mesh.prototype.registerAfterRender = function (func) {
  31629. this.onAfterRenderObservable.add(func);
  31630. return this;
  31631. };
  31632. /**
  31633. * Disposes a previously registered javascript function called after the rendering.
  31634. * This function is passed the current mesh.
  31635. * Return the Mesh.
  31636. */
  31637. Mesh.prototype.unregisterAfterRender = function (func) {
  31638. this.onAfterRenderObservable.removeCallback(func);
  31639. return this;
  31640. };
  31641. /** @hidden */
  31642. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31643. var scene = this.getScene();
  31644. this._batchCache.mustReturn = false;
  31645. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31646. this._batchCache.visibleInstances[subMeshId] = null;
  31647. if (this._visibleInstances) {
  31648. var currentRenderId = scene.getRenderId();
  31649. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31650. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31651. var selfRenderId = this._renderId;
  31652. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31653. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31654. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31655. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31656. }
  31657. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31658. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31659. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31660. this._batchCache.mustReturn = true;
  31661. return this._batchCache;
  31662. }
  31663. if (currentRenderId !== selfRenderId) {
  31664. this._batchCache.renderSelf[subMeshId] = false;
  31665. }
  31666. }
  31667. this._renderIdForInstances[subMeshId] = currentRenderId;
  31668. }
  31669. return this._batchCache;
  31670. };
  31671. /** @hidden */
  31672. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31673. var visibleInstances = batch.visibleInstances[subMesh._id];
  31674. if (!visibleInstances) {
  31675. return this;
  31676. }
  31677. var matricesCount = visibleInstances.length + 1;
  31678. var bufferSize = matricesCount * 16 * 4;
  31679. var currentInstancesBufferSize = this._instancesBufferSize;
  31680. var instancesBuffer = this._instancesBuffer;
  31681. while (this._instancesBufferSize < bufferSize) {
  31682. this._instancesBufferSize *= 2;
  31683. }
  31684. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31685. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31686. }
  31687. var offset = 0;
  31688. var instancesCount = 0;
  31689. var world = this.getWorldMatrix();
  31690. if (batch.renderSelf[subMesh._id]) {
  31691. world.copyToArray(this._instancesData, offset);
  31692. offset += 16;
  31693. instancesCount++;
  31694. }
  31695. if (visibleInstances) {
  31696. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31697. var instance = visibleInstances[instanceIndex];
  31698. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31699. offset += 16;
  31700. instancesCount++;
  31701. }
  31702. }
  31703. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31704. if (instancesBuffer) {
  31705. instancesBuffer.dispose();
  31706. }
  31707. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31708. this._instancesBuffer = instancesBuffer;
  31709. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31710. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31711. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31712. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31713. }
  31714. else {
  31715. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31716. }
  31717. this._bind(subMesh, effect, fillMode);
  31718. this._draw(subMesh, fillMode, instancesCount);
  31719. engine.unbindInstanceAttributes();
  31720. return this;
  31721. };
  31722. /** @hidden */
  31723. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31724. var scene = this.getScene();
  31725. var engine = scene.getEngine();
  31726. if (hardwareInstancedRendering) {
  31727. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31728. }
  31729. else {
  31730. if (batch.renderSelf[subMesh._id]) {
  31731. // Draw
  31732. if (onBeforeDraw) {
  31733. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31734. }
  31735. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31736. }
  31737. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31738. if (visibleInstancesForSubMesh) {
  31739. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31740. var instance = visibleInstancesForSubMesh[instanceIndex];
  31741. // World
  31742. var world = instance.getWorldMatrix();
  31743. if (onBeforeDraw) {
  31744. onBeforeDraw(true, world, effectiveMaterial);
  31745. }
  31746. // Draw
  31747. this._draw(subMesh, fillMode);
  31748. }
  31749. }
  31750. }
  31751. return this;
  31752. };
  31753. /**
  31754. * 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
  31755. * @param subMesh defines the subMesh to render
  31756. * @param enableAlphaMode defines if alpha mode can be changed
  31757. * @returns the current mesh
  31758. */
  31759. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31760. this._checkOcclusionQuery();
  31761. if (this._isOccluded) {
  31762. return this;
  31763. }
  31764. var scene = this.getScene();
  31765. // Managing instances
  31766. var batch = this._getInstancesRenderList(subMesh._id);
  31767. if (batch.mustReturn) {
  31768. return this;
  31769. }
  31770. // Checking geometry state
  31771. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31772. return this;
  31773. }
  31774. if (this._onBeforeRenderObservable) {
  31775. this._onBeforeRenderObservable.notifyObservers(this);
  31776. }
  31777. var engine = scene.getEngine();
  31778. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31779. // Material
  31780. var material = subMesh.getMaterial();
  31781. if (!material) {
  31782. return this;
  31783. }
  31784. this._effectiveMaterial = material;
  31785. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31786. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31787. return this;
  31788. }
  31789. }
  31790. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31791. return this;
  31792. }
  31793. // Alpha mode
  31794. if (enableAlphaMode) {
  31795. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31796. }
  31797. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  31798. var step = _a[_i];
  31799. step.action(this, subMesh, batch);
  31800. }
  31801. var effect;
  31802. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31803. effect = subMesh.effect;
  31804. }
  31805. else {
  31806. effect = this._effectiveMaterial.getEffect();
  31807. }
  31808. if (!effect) {
  31809. return this;
  31810. }
  31811. var sideOrientation = this.overrideMaterialSideOrientation;
  31812. if (sideOrientation == null) {
  31813. sideOrientation = this._effectiveMaterial.sideOrientation;
  31814. if (this._getWorldMatrixDeterminant() < 0) {
  31815. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31816. }
  31817. }
  31818. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31819. if (this._effectiveMaterial.forceDepthWrite) {
  31820. engine.setDepthWrite(true);
  31821. }
  31822. // Bind
  31823. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31824. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31825. this._bind(subMesh, effect, fillMode);
  31826. }
  31827. var world = this.getWorldMatrix();
  31828. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31829. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31830. }
  31831. else {
  31832. this._effectiveMaterial.bind(world, this);
  31833. }
  31834. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31835. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31836. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31837. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31838. }
  31839. // Draw
  31840. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31841. // Unbind
  31842. this._effectiveMaterial.unbind();
  31843. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  31844. var step = _c[_b];
  31845. step.action(this, subMesh, batch);
  31846. }
  31847. if (this._onAfterRenderObservable) {
  31848. this._onAfterRenderObservable.notifyObservers(this);
  31849. }
  31850. return this;
  31851. };
  31852. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31853. if (isInstance && effectiveMaterial) {
  31854. effectiveMaterial.bindOnlyWorldMatrix(world);
  31855. }
  31856. };
  31857. /**
  31858. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  31859. */
  31860. Mesh.prototype.getEmittedParticleSystems = function () {
  31861. var results = new Array();
  31862. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31863. var particleSystem = this.getScene().particleSystems[index];
  31864. if (particleSystem.emitter === this) {
  31865. results.push(particleSystem);
  31866. }
  31867. }
  31868. return results;
  31869. };
  31870. /**
  31871. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  31872. */
  31873. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31874. var results = new Array();
  31875. var descendants = this.getDescendants();
  31876. descendants.push(this);
  31877. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31878. var particleSystem = this.getScene().particleSystems[index];
  31879. var emitter = particleSystem.emitter;
  31880. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31881. results.push(particleSystem);
  31882. }
  31883. }
  31884. return results;
  31885. };
  31886. /**
  31887. * Normalize matrix weights so that all vertices have a total weight set to 1
  31888. */
  31889. Mesh.prototype.cleanMatrixWeights = function () {
  31890. var epsilon = 1e-3;
  31891. var noInfluenceBoneIndex = 0.0;
  31892. if (this.skeleton) {
  31893. noInfluenceBoneIndex = this.skeleton.bones.length;
  31894. }
  31895. else {
  31896. return;
  31897. }
  31898. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31899. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31900. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31901. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31902. var influencers = this.numBoneInfluencers;
  31903. var size = matricesWeights.length;
  31904. for (var i = 0; i < size; i += 4) {
  31905. var weight = 0.0;
  31906. var firstZeroWeight = -1;
  31907. for (var j = 0; j < 4; j++) {
  31908. var w = matricesWeights[i + j];
  31909. weight += w;
  31910. if (w < epsilon && firstZeroWeight < 0) {
  31911. firstZeroWeight = j;
  31912. }
  31913. }
  31914. if (matricesWeightsExtra) {
  31915. for (var j = 0; j < 4; j++) {
  31916. var w = matricesWeightsExtra[i + j];
  31917. weight += w;
  31918. if (w < epsilon && firstZeroWeight < 0) {
  31919. firstZeroWeight = j + 4;
  31920. }
  31921. }
  31922. }
  31923. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31924. firstZeroWeight = influencers - 1;
  31925. }
  31926. if (weight > epsilon) {
  31927. var mweight = 1.0 / weight;
  31928. for (var j = 0; j < 4; j++) {
  31929. matricesWeights[i + j] *= mweight;
  31930. }
  31931. if (matricesWeightsExtra) {
  31932. for (var j = 0; j < 4; j++) {
  31933. matricesWeightsExtra[i + j] *= mweight;
  31934. }
  31935. }
  31936. }
  31937. else {
  31938. if (firstZeroWeight >= 4) {
  31939. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31940. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31941. }
  31942. else {
  31943. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31944. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31945. }
  31946. }
  31947. }
  31948. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31949. if (matricesIndicesExtra) {
  31950. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31951. }
  31952. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  31953. if (matricesWeightsExtra) {
  31954. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  31955. }
  31956. };
  31957. /** @hidden */
  31958. Mesh.prototype._checkDelayState = function () {
  31959. var scene = this.getScene();
  31960. if (this._geometry) {
  31961. this._geometry.load(scene);
  31962. }
  31963. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31964. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31965. this._queueLoad(scene);
  31966. }
  31967. return this;
  31968. };
  31969. Mesh.prototype._queueLoad = function (scene) {
  31970. var _this = this;
  31971. scene._addPendingData(this);
  31972. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31973. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31974. if (data instanceof ArrayBuffer) {
  31975. _this._delayLoadingFunction(data, _this);
  31976. }
  31977. else {
  31978. _this._delayLoadingFunction(JSON.parse(data), _this);
  31979. }
  31980. _this.instances.forEach(function (instance) {
  31981. instance._syncSubMeshes();
  31982. });
  31983. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31984. scene._removePendingData(_this);
  31985. }, function () { }, scene.database, getBinaryData);
  31986. return this;
  31987. };
  31988. /**
  31989. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  31990. * A mesh is in the frustum if its bounding box intersects the frustum
  31991. * @param frustumPlanes defines the frustum to test
  31992. * @returns true if the mesh is in the frustum planes
  31993. */
  31994. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31995. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31996. return false;
  31997. }
  31998. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31999. return false;
  32000. }
  32001. this._checkDelayState();
  32002. return true;
  32003. };
  32004. /**
  32005. * Sets the mesh material by the material or multiMaterial `id` property.
  32006. * The material `id` is a string identifying the material or the multiMaterial.
  32007. * This method returns the Mesh.
  32008. */
  32009. Mesh.prototype.setMaterialByID = function (id) {
  32010. var materials = this.getScene().materials;
  32011. var index;
  32012. for (index = materials.length - 1; index > -1; index--) {
  32013. if (materials[index].id === id) {
  32014. this.material = materials[index];
  32015. return this;
  32016. }
  32017. }
  32018. // Multi
  32019. var multiMaterials = this.getScene().multiMaterials;
  32020. for (index = multiMaterials.length - 1; index > -1; index--) {
  32021. if (multiMaterials[index].id === id) {
  32022. this.material = multiMaterials[index];
  32023. return this;
  32024. }
  32025. }
  32026. return this;
  32027. };
  32028. /**
  32029. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32030. */
  32031. Mesh.prototype.getAnimatables = function () {
  32032. var results = new Array();
  32033. if (this.material) {
  32034. results.push(this.material);
  32035. }
  32036. if (this.skeleton) {
  32037. results.push(this.skeleton);
  32038. }
  32039. return results;
  32040. };
  32041. /**
  32042. * Modifies the mesh geometry according to the passed transformation matrix.
  32043. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32044. * The mesh normals are modified using the same transformation.
  32045. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32046. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32047. * Returns the Mesh.
  32048. */
  32049. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32050. // Position
  32051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32052. return this;
  32053. }
  32054. var submeshes = this.subMeshes.splice(0);
  32055. this._resetPointsArrayCache();
  32056. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32057. var temp = new Array();
  32058. var index;
  32059. for (index = 0; index < data.length; index += 3) {
  32060. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32061. }
  32062. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32063. // Normals
  32064. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32065. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32066. temp = [];
  32067. for (index = 0; index < data.length; index += 3) {
  32068. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32069. }
  32070. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32071. }
  32072. // flip faces?
  32073. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32074. this.flipFaces();
  32075. }
  32076. // Restore submeshes
  32077. this.releaseSubMeshes();
  32078. this.subMeshes = submeshes;
  32079. return this;
  32080. };
  32081. /**
  32082. * Modifies the mesh geometry according to its own current World Matrix.
  32083. * The mesh World Matrix is then reset.
  32084. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32085. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32086. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32087. * Returns the Mesh.
  32088. */
  32089. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32090. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32091. this.scaling.copyFromFloats(1, 1, 1);
  32092. this.position.copyFromFloats(0, 0, 0);
  32093. this.rotation.copyFromFloats(0, 0, 0);
  32094. //only if quaternion is already set
  32095. if (this.rotationQuaternion) {
  32096. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32097. }
  32098. this._worldMatrix = BABYLON.Matrix.Identity();
  32099. return this;
  32100. };
  32101. Object.defineProperty(Mesh.prototype, "_positions", {
  32102. // Cache
  32103. get: function () {
  32104. if (this._geometry) {
  32105. return this._geometry._positions;
  32106. }
  32107. return null;
  32108. },
  32109. enumerable: true,
  32110. configurable: true
  32111. });
  32112. /** @hidden */
  32113. Mesh.prototype._resetPointsArrayCache = function () {
  32114. if (this._geometry) {
  32115. this._geometry._resetPointsArrayCache();
  32116. }
  32117. return this;
  32118. };
  32119. /** @hidden */
  32120. Mesh.prototype._generatePointsArray = function () {
  32121. if (this._geometry) {
  32122. return this._geometry._generatePointsArray();
  32123. }
  32124. return false;
  32125. };
  32126. /**
  32127. * Returns a new Mesh object generated from the current mesh properties.
  32128. * This method must not get confused with createInstance().
  32129. * The parameter `name` is a string, the name given to the new mesh.
  32130. * The optional parameter `newParent` can be any Node object (default `null`).
  32131. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32132. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32133. */
  32134. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32135. if (name === void 0) { name = ""; }
  32136. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32137. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32138. };
  32139. /**
  32140. * Releases resources associated with this mesh.
  32141. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32142. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32143. */
  32144. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32145. var _this = this;
  32146. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32147. this.morphTargetManager = null;
  32148. if (this._geometry) {
  32149. this._geometry.releaseForMesh(this, true);
  32150. }
  32151. if (this._onBeforeDrawObservable) {
  32152. this._onBeforeDrawObservable.clear();
  32153. }
  32154. if (this._onBeforeRenderObservable) {
  32155. this._onBeforeRenderObservable.clear();
  32156. }
  32157. if (this._onAfterRenderObservable) {
  32158. this._onAfterRenderObservable.clear();
  32159. }
  32160. // Sources
  32161. var meshes = this.getScene().meshes;
  32162. meshes.forEach(function (abstractMesh) {
  32163. var mesh = abstractMesh;
  32164. if (mesh._source && mesh._source === _this) {
  32165. mesh._source = null;
  32166. }
  32167. });
  32168. this._source = null;
  32169. // Instances
  32170. if (this._instancesBuffer) {
  32171. this._instancesBuffer.dispose();
  32172. this._instancesBuffer = null;
  32173. }
  32174. while (this.instances.length) {
  32175. this.instances[0].dispose();
  32176. }
  32177. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32178. };
  32179. /**
  32180. * Modifies the mesh geometry according to a displacement map.
  32181. * 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.
  32182. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32183. * This method returns nothing.
  32184. * @param url is a string, the URL from the image file is to be downloaded.
  32185. * @param minHeight is the lower limit of the displacement.
  32186. * @param maxHeight is the upper limit of the displacement.
  32187. * @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.
  32188. * @param uvOffset is an optional vector2 used to offset UV.
  32189. * @param uvScale is an optional vector2 used to scale UV.
  32190. * @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.
  32191. * @returns the Mesh.
  32192. */
  32193. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32194. var _this = this;
  32195. if (forceUpdate === void 0) { forceUpdate = false; }
  32196. var scene = this.getScene();
  32197. var onload = function (img) {
  32198. // Getting height map data
  32199. var canvas = document.createElement("canvas");
  32200. var context = canvas.getContext("2d");
  32201. var heightMapWidth = img.width;
  32202. var heightMapHeight = img.height;
  32203. canvas.width = heightMapWidth;
  32204. canvas.height = heightMapHeight;
  32205. context.drawImage(img, 0, 0);
  32206. // Create VertexData from map data
  32207. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32208. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32209. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32210. //execute success callback, if set
  32211. if (onSuccess) {
  32212. onSuccess(_this);
  32213. }
  32214. };
  32215. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32216. return this;
  32217. };
  32218. /**
  32219. * Modifies the mesh geometry according to a displacementMap buffer.
  32220. * 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.
  32221. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32222. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32223. * @param heightMapWidth is the width of the buffer image.
  32224. * @param heightMapHeight is the height of the buffer image.
  32225. * @param minHeight is the lower limit of the displacement.
  32226. * @param maxHeight is the upper limit of the displacement.
  32227. * @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.
  32228. * @param uvOffset is an optional vector2 used to offset UV.
  32229. * @param uvScale is an optional vector2 used to scale UV.
  32230. * @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.
  32231. * @returns the Mesh.
  32232. */
  32233. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32234. if (forceUpdate === void 0) { forceUpdate = false; }
  32235. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32236. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32237. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32238. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32239. return this;
  32240. }
  32241. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32242. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32243. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32244. var position = BABYLON.Vector3.Zero();
  32245. var normal = BABYLON.Vector3.Zero();
  32246. var uv = BABYLON.Vector2.Zero();
  32247. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32248. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32249. for (var index = 0; index < positions.length; index += 3) {
  32250. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32251. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32252. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32253. // Compute height
  32254. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32255. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32256. var pos = (u + v * heightMapWidth) * 4;
  32257. var r = buffer[pos] / 255.0;
  32258. var g = buffer[pos + 1] / 255.0;
  32259. var b = buffer[pos + 2] / 255.0;
  32260. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32261. normal.normalize();
  32262. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32263. position = position.add(normal);
  32264. position.toArray(positions, index);
  32265. }
  32266. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32267. if (forceUpdate) {
  32268. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32269. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32270. }
  32271. else {
  32272. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32273. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32274. }
  32275. return this;
  32276. };
  32277. /**
  32278. * Modify the mesh to get a flat shading rendering.
  32279. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32280. * This method returns the Mesh.
  32281. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32282. */
  32283. Mesh.prototype.convertToFlatShadedMesh = function () {
  32284. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32285. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32286. var kinds = this.getVerticesDataKinds();
  32287. var vbs = {};
  32288. var data = {};
  32289. var newdata = {};
  32290. var updatableNormals = false;
  32291. var kindIndex;
  32292. var kind;
  32293. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32294. kind = kinds[kindIndex];
  32295. var vertexBuffer = this.getVertexBuffer(kind);
  32296. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32297. updatableNormals = vertexBuffer.isUpdatable();
  32298. kinds.splice(kindIndex, 1);
  32299. kindIndex--;
  32300. continue;
  32301. }
  32302. vbs[kind] = vertexBuffer;
  32303. data[kind] = vbs[kind].getData();
  32304. newdata[kind] = [];
  32305. }
  32306. // Save previous submeshes
  32307. var previousSubmeshes = this.subMeshes.slice(0);
  32308. var indices = this.getIndices();
  32309. var totalIndices = this.getTotalIndices();
  32310. // Generating unique vertices per face
  32311. var index;
  32312. for (index = 0; index < totalIndices; index++) {
  32313. var vertexIndex = indices[index];
  32314. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32315. kind = kinds[kindIndex];
  32316. var stride = vbs[kind].getStrideSize();
  32317. for (var offset = 0; offset < stride; offset++) {
  32318. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32319. }
  32320. }
  32321. }
  32322. // Updating faces & normal
  32323. var normals = [];
  32324. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32325. for (index = 0; index < totalIndices; index += 3) {
  32326. indices[index] = index;
  32327. indices[index + 1] = index + 1;
  32328. indices[index + 2] = index + 2;
  32329. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32330. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32331. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32332. var p1p2 = p1.subtract(p2);
  32333. var p3p2 = p3.subtract(p2);
  32334. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32335. // Store same normals for every vertex
  32336. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32337. normals.push(normal.x);
  32338. normals.push(normal.y);
  32339. normals.push(normal.z);
  32340. }
  32341. }
  32342. this.setIndices(indices);
  32343. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32344. // Updating vertex buffers
  32345. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32346. kind = kinds[kindIndex];
  32347. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32348. }
  32349. // Updating submeshes
  32350. this.releaseSubMeshes();
  32351. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32352. var previousOne = previousSubmeshes[submeshIndex];
  32353. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32354. }
  32355. this.synchronizeInstances();
  32356. return this;
  32357. };
  32358. /**
  32359. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32360. * In other words, more vertices, no more indices and a single bigger VBO.
  32361. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32362. * Returns the Mesh.
  32363. */
  32364. Mesh.prototype.convertToUnIndexedMesh = function () {
  32365. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32366. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32367. var kinds = this.getVerticesDataKinds();
  32368. var vbs = {};
  32369. var data = {};
  32370. var newdata = {};
  32371. var kindIndex;
  32372. var kind;
  32373. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32374. kind = kinds[kindIndex];
  32375. var vertexBuffer = this.getVertexBuffer(kind);
  32376. vbs[kind] = vertexBuffer;
  32377. data[kind] = vbs[kind].getData();
  32378. newdata[kind] = [];
  32379. }
  32380. // Save previous submeshes
  32381. var previousSubmeshes = this.subMeshes.slice(0);
  32382. var indices = this.getIndices();
  32383. var totalIndices = this.getTotalIndices();
  32384. // Generating unique vertices per face
  32385. var index;
  32386. for (index = 0; index < totalIndices; index++) {
  32387. var vertexIndex = indices[index];
  32388. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32389. kind = kinds[kindIndex];
  32390. var stride = vbs[kind].getStrideSize();
  32391. for (var offset = 0; offset < stride; offset++) {
  32392. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32393. }
  32394. }
  32395. }
  32396. // Updating indices
  32397. for (index = 0; index < totalIndices; index += 3) {
  32398. indices[index] = index;
  32399. indices[index + 1] = index + 1;
  32400. indices[index + 2] = index + 2;
  32401. }
  32402. this.setIndices(indices);
  32403. // Updating vertex buffers
  32404. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32405. kind = kinds[kindIndex];
  32406. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32407. }
  32408. // Updating submeshes
  32409. this.releaseSubMeshes();
  32410. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32411. var previousOne = previousSubmeshes[submeshIndex];
  32412. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32413. }
  32414. this._unIndexed = true;
  32415. this.synchronizeInstances();
  32416. return this;
  32417. };
  32418. /**
  32419. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32420. * This method returns the Mesh.
  32421. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32422. */
  32423. Mesh.prototype.flipFaces = function (flipNormals) {
  32424. if (flipNormals === void 0) { flipNormals = false; }
  32425. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32426. var i;
  32427. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32428. for (i = 0; i < vertex_data.normals.length; i++) {
  32429. vertex_data.normals[i] *= -1;
  32430. }
  32431. }
  32432. if (vertex_data.indices) {
  32433. var temp;
  32434. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32435. // reassign indices
  32436. temp = vertex_data.indices[i + 1];
  32437. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32438. vertex_data.indices[i + 2] = temp;
  32439. }
  32440. }
  32441. vertex_data.applyToMesh(this);
  32442. return this;
  32443. };
  32444. // Instances
  32445. /**
  32446. * Creates a new InstancedMesh object from the mesh model.
  32447. * An instance shares the same properties and the same material than its model.
  32448. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32449. * Only these properties of each instance can then be set individually :
  32450. * - position
  32451. * - rotation
  32452. * - rotationQuaternion
  32453. * - setPivotMatrix
  32454. * - scaling
  32455. *
  32456. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32457. * Warning : this method is not supported for Line mesh and LineSystem
  32458. */
  32459. Mesh.prototype.createInstance = function (name) {
  32460. return new BABYLON.InstancedMesh(name, this);
  32461. };
  32462. /**
  32463. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32464. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32465. * This method returns the Mesh.
  32466. */
  32467. Mesh.prototype.synchronizeInstances = function () {
  32468. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32469. var instance = this.instances[instanceIndex];
  32470. instance._syncSubMeshes();
  32471. }
  32472. return this;
  32473. };
  32474. /**
  32475. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32476. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32477. * This should be used together with the simplification to avoid disappearing triangles.
  32478. * Returns the Mesh.
  32479. * @param successCallback an optional success callback to be called after the optimization finished.
  32480. */
  32481. Mesh.prototype.optimizeIndices = function (successCallback) {
  32482. var _this = this;
  32483. var indices = this.getIndices();
  32484. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32485. if (!positions || !indices) {
  32486. return this;
  32487. }
  32488. var vectorPositions = new Array();
  32489. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32490. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32491. }
  32492. var dupes = new Array();
  32493. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32494. var realPos = vectorPositions.length - 1 - iteration;
  32495. var testedPosition = vectorPositions[realPos];
  32496. for (var j = 0; j < realPos; ++j) {
  32497. var againstPosition = vectorPositions[j];
  32498. if (testedPosition.equals(againstPosition)) {
  32499. dupes[realPos] = j;
  32500. break;
  32501. }
  32502. }
  32503. }, function () {
  32504. for (var i = 0; i < indices.length; ++i) {
  32505. indices[i] = dupes[indices[i]] || indices[i];
  32506. }
  32507. //indices are now reordered
  32508. var originalSubMeshes = _this.subMeshes.slice(0);
  32509. _this.setIndices(indices);
  32510. _this.subMeshes = originalSubMeshes;
  32511. if (successCallback) {
  32512. successCallback(_this);
  32513. }
  32514. });
  32515. return this;
  32516. };
  32517. Mesh.prototype.serialize = function (serializationObject) {
  32518. serializationObject.name = this.name;
  32519. serializationObject.id = this.id;
  32520. serializationObject.type = this.getClassName();
  32521. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32522. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32523. }
  32524. serializationObject.position = this.position.asArray();
  32525. if (this.rotationQuaternion) {
  32526. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32527. }
  32528. else if (this.rotation) {
  32529. serializationObject.rotation = this.rotation.asArray();
  32530. }
  32531. serializationObject.scaling = this.scaling.asArray();
  32532. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32533. serializationObject.isEnabled = this.isEnabled(false);
  32534. serializationObject.isVisible = this.isVisible;
  32535. serializationObject.infiniteDistance = this.infiniteDistance;
  32536. serializationObject.pickable = this.isPickable;
  32537. serializationObject.receiveShadows = this.receiveShadows;
  32538. serializationObject.billboardMode = this.billboardMode;
  32539. serializationObject.visibility = this.visibility;
  32540. serializationObject.checkCollisions = this.checkCollisions;
  32541. serializationObject.isBlocker = this.isBlocker;
  32542. // Parent
  32543. if (this.parent) {
  32544. serializationObject.parentId = this.parent.id;
  32545. }
  32546. // Geometry
  32547. serializationObject.isUnIndexed = this.isUnIndexed;
  32548. var geometry = this._geometry;
  32549. if (geometry) {
  32550. var geometryId = geometry.id;
  32551. serializationObject.geometryId = geometryId;
  32552. // SubMeshes
  32553. serializationObject.subMeshes = [];
  32554. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32555. var subMesh = this.subMeshes[subIndex];
  32556. serializationObject.subMeshes.push({
  32557. materialIndex: subMesh.materialIndex,
  32558. verticesStart: subMesh.verticesStart,
  32559. verticesCount: subMesh.verticesCount,
  32560. indexStart: subMesh.indexStart,
  32561. indexCount: subMesh.indexCount
  32562. });
  32563. }
  32564. }
  32565. // Material
  32566. if (this.material) {
  32567. serializationObject.materialId = this.material.id;
  32568. }
  32569. else {
  32570. this.material = null;
  32571. }
  32572. // Morph targets
  32573. if (this.morphTargetManager) {
  32574. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32575. }
  32576. // Skeleton
  32577. if (this.skeleton) {
  32578. serializationObject.skeletonId = this.skeleton.id;
  32579. }
  32580. // Physics
  32581. //TODO implement correct serialization for physics impostors.
  32582. var impostor = this.getPhysicsImpostor();
  32583. if (impostor) {
  32584. serializationObject.physicsMass = impostor.getParam("mass");
  32585. serializationObject.physicsFriction = impostor.getParam("friction");
  32586. serializationObject.physicsRestitution = impostor.getParam("mass");
  32587. serializationObject.physicsImpostor = impostor.type;
  32588. }
  32589. // Metadata
  32590. if (this.metadata) {
  32591. serializationObject.metadata = this.metadata;
  32592. }
  32593. // Instances
  32594. serializationObject.instances = [];
  32595. for (var index = 0; index < this.instances.length; index++) {
  32596. var instance = this.instances[index];
  32597. if (instance.doNotSerialize) {
  32598. continue;
  32599. }
  32600. var serializationInstance = {
  32601. name: instance.name,
  32602. id: instance.id,
  32603. position: instance.position.asArray(),
  32604. scaling: instance.scaling.asArray()
  32605. };
  32606. if (instance.parent) {
  32607. serializationInstance.parentId = instance.parent.id;
  32608. }
  32609. if (instance.rotationQuaternion) {
  32610. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32611. }
  32612. else if (instance.rotation) {
  32613. serializationInstance.rotation = instance.rotation.asArray();
  32614. }
  32615. serializationObject.instances.push(serializationInstance);
  32616. // Animations
  32617. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32618. serializationInstance.ranges = instance.serializeAnimationRanges();
  32619. }
  32620. //
  32621. // Animations
  32622. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32623. serializationObject.ranges = this.serializeAnimationRanges();
  32624. // Layer mask
  32625. serializationObject.layerMask = this.layerMask;
  32626. // Alpha
  32627. serializationObject.alphaIndex = this.alphaIndex;
  32628. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32629. // Overlay
  32630. serializationObject.overlayAlpha = this.overlayAlpha;
  32631. serializationObject.overlayColor = this.overlayColor.asArray();
  32632. serializationObject.renderOverlay = this.renderOverlay;
  32633. // Fog
  32634. serializationObject.applyFog = this.applyFog;
  32635. // Action Manager
  32636. if (this.actionManager) {
  32637. serializationObject.actions = this.actionManager.serialize(this.name);
  32638. }
  32639. };
  32640. /** @hidden */
  32641. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32642. if (!this.geometry) {
  32643. return;
  32644. }
  32645. this._markSubMeshesAsAttributesDirty();
  32646. var morphTargetManager = this._morphTargetManager;
  32647. if (morphTargetManager && morphTargetManager.vertexCount) {
  32648. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32649. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32650. this.morphTargetManager = null;
  32651. return;
  32652. }
  32653. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32654. var morphTarget = morphTargetManager.getActiveTarget(index);
  32655. var positions = morphTarget.getPositions();
  32656. if (!positions) {
  32657. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32658. return;
  32659. }
  32660. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32661. var normals = morphTarget.getNormals();
  32662. if (normals) {
  32663. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32664. }
  32665. var tangents = morphTarget.getTangents();
  32666. if (tangents) {
  32667. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32668. }
  32669. }
  32670. }
  32671. else {
  32672. var index = 0;
  32673. // Positions
  32674. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32675. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32676. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32677. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32678. }
  32679. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32680. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32681. }
  32682. index++;
  32683. }
  32684. }
  32685. };
  32686. // Statics
  32687. /**
  32688. * Returns a new Mesh object parsed from the source provided.
  32689. * The parameter `parsedMesh` is the source.
  32690. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32691. */
  32692. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32693. var mesh;
  32694. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32695. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32696. }
  32697. else {
  32698. mesh = new Mesh(parsedMesh.name, scene);
  32699. }
  32700. mesh.id = parsedMesh.id;
  32701. if (BABYLON.Tags) {
  32702. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32703. }
  32704. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32705. if (parsedMesh.metadata !== undefined) {
  32706. mesh.metadata = parsedMesh.metadata;
  32707. }
  32708. if (parsedMesh.rotationQuaternion) {
  32709. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32710. }
  32711. else if (parsedMesh.rotation) {
  32712. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32713. }
  32714. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32715. if (parsedMesh.localMatrix) {
  32716. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32717. }
  32718. else if (parsedMesh.pivotMatrix) {
  32719. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32720. }
  32721. mesh.setEnabled(parsedMesh.isEnabled);
  32722. mesh.isVisible = parsedMesh.isVisible;
  32723. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32724. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32725. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32726. if (parsedMesh.applyFog !== undefined) {
  32727. mesh.applyFog = parsedMesh.applyFog;
  32728. }
  32729. if (parsedMesh.pickable !== undefined) {
  32730. mesh.isPickable = parsedMesh.pickable;
  32731. }
  32732. if (parsedMesh.alphaIndex !== undefined) {
  32733. mesh.alphaIndex = parsedMesh.alphaIndex;
  32734. }
  32735. mesh.receiveShadows = parsedMesh.receiveShadows;
  32736. mesh.billboardMode = parsedMesh.billboardMode;
  32737. if (parsedMesh.visibility !== undefined) {
  32738. mesh.visibility = parsedMesh.visibility;
  32739. }
  32740. mesh.checkCollisions = parsedMesh.checkCollisions;
  32741. if (parsedMesh.isBlocker !== undefined) {
  32742. mesh.isBlocker = parsedMesh.isBlocker;
  32743. }
  32744. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32745. // freezeWorldMatrix
  32746. if (parsedMesh.freezeWorldMatrix) {
  32747. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32748. }
  32749. // Parent
  32750. if (parsedMesh.parentId) {
  32751. mesh._waitingParentId = parsedMesh.parentId;
  32752. }
  32753. // Actions
  32754. if (parsedMesh.actions !== undefined) {
  32755. mesh._waitingActions = parsedMesh.actions;
  32756. }
  32757. // Overlay
  32758. if (parsedMesh.overlayAlpha !== undefined) {
  32759. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32760. }
  32761. if (parsedMesh.overlayColor !== undefined) {
  32762. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32763. }
  32764. if (parsedMesh.renderOverlay !== undefined) {
  32765. mesh.renderOverlay = parsedMesh.renderOverlay;
  32766. }
  32767. // Geometry
  32768. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32769. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32770. if (parsedMesh.delayLoadingFile) {
  32771. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32772. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32773. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32774. if (parsedMesh._binaryInfo) {
  32775. mesh._binaryInfo = parsedMesh._binaryInfo;
  32776. }
  32777. mesh._delayInfo = [];
  32778. if (parsedMesh.hasUVs) {
  32779. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32780. }
  32781. if (parsedMesh.hasUVs2) {
  32782. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32783. }
  32784. if (parsedMesh.hasUVs3) {
  32785. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32786. }
  32787. if (parsedMesh.hasUVs4) {
  32788. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32789. }
  32790. if (parsedMesh.hasUVs5) {
  32791. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32792. }
  32793. if (parsedMesh.hasUVs6) {
  32794. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32795. }
  32796. if (parsedMesh.hasColors) {
  32797. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32798. }
  32799. if (parsedMesh.hasMatricesIndices) {
  32800. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32801. }
  32802. if (parsedMesh.hasMatricesWeights) {
  32803. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32804. }
  32805. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32806. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32807. mesh._checkDelayState();
  32808. }
  32809. }
  32810. else {
  32811. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32812. }
  32813. // Material
  32814. if (parsedMesh.materialId) {
  32815. mesh.setMaterialByID(parsedMesh.materialId);
  32816. }
  32817. else {
  32818. mesh.material = null;
  32819. }
  32820. // Morph targets
  32821. if (parsedMesh.morphTargetManagerId > -1) {
  32822. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32823. }
  32824. // Skeleton
  32825. if (parsedMesh.skeletonId > -1) {
  32826. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32827. if (parsedMesh.numBoneInfluencers) {
  32828. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32829. }
  32830. }
  32831. // Animations
  32832. if (parsedMesh.animations) {
  32833. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32834. var parsedAnimation = parsedMesh.animations[animationIndex];
  32835. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32836. }
  32837. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32838. }
  32839. if (parsedMesh.autoAnimate) {
  32840. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32841. }
  32842. // Layer Mask
  32843. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32844. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32845. }
  32846. else {
  32847. mesh.layerMask = 0x0FFFFFFF;
  32848. }
  32849. // Physics
  32850. if (parsedMesh.physicsImpostor) {
  32851. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32852. mass: parsedMesh.physicsMass,
  32853. friction: parsedMesh.physicsFriction,
  32854. restitution: parsedMesh.physicsRestitution
  32855. }, scene);
  32856. }
  32857. // Instances
  32858. if (parsedMesh.instances) {
  32859. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32860. var parsedInstance = parsedMesh.instances[index];
  32861. var instance = mesh.createInstance(parsedInstance.name);
  32862. if (parsedInstance.id) {
  32863. instance.id = parsedInstance.id;
  32864. }
  32865. if (BABYLON.Tags) {
  32866. if (parsedInstance.tags) {
  32867. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32868. }
  32869. else {
  32870. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  32871. }
  32872. }
  32873. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32874. if (parsedInstance.parentId) {
  32875. instance._waitingParentId = parsedInstance.parentId;
  32876. }
  32877. if (parsedInstance.rotationQuaternion) {
  32878. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32879. }
  32880. else if (parsedInstance.rotation) {
  32881. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32882. }
  32883. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32884. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  32885. instance.checkCollisions = parsedInstance.checkCollisions;
  32886. }
  32887. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  32888. instance.isPickable = parsedInstance.pickable;
  32889. }
  32890. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  32891. instance.showBoundingBox = parsedInstance.showBoundingBox;
  32892. }
  32893. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32894. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  32895. }
  32896. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32897. instance.alphaIndex = parsedInstance.alphaIndex;
  32898. }
  32899. // Physics
  32900. if (parsedInstance.physicsImpostor) {
  32901. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  32902. mass: parsedInstance.physicsMass,
  32903. friction: parsedInstance.physicsFriction,
  32904. restitution: parsedInstance.physicsRestitution
  32905. }, scene);
  32906. }
  32907. // Animation
  32908. if (parsedInstance.animations) {
  32909. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  32910. parsedAnimation = parsedInstance.animations[animationIndex];
  32911. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32912. }
  32913. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  32914. if (parsedInstance.autoAnimate) {
  32915. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  32916. }
  32917. }
  32918. }
  32919. }
  32920. return mesh;
  32921. };
  32922. /**
  32923. * Creates a ribbon mesh.
  32924. * Please consider using the same method from the MeshBuilder class instead.
  32925. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32926. *
  32927. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32928. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32929. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32930. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32931. * 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.
  32932. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  32933. * 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
  32934. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32935. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32937. */
  32938. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32939. if (closeArray === void 0) { closeArray = false; }
  32940. if (updatable === void 0) { updatable = false; }
  32941. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32942. pathArray: pathArray,
  32943. closeArray: closeArray,
  32944. closePath: closePath,
  32945. offset: offset,
  32946. updatable: updatable,
  32947. sideOrientation: sideOrientation,
  32948. instance: instance
  32949. }, scene);
  32950. };
  32951. /**
  32952. * Creates a plane polygonal mesh. By default, this is a disc.
  32953. * Please consider using the same method from the MeshBuilder class instead.
  32954. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32955. * 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.
  32956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32957. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32959. */
  32960. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32961. if (scene === void 0) { scene = null; }
  32962. var options = {
  32963. radius: radius,
  32964. tessellation: tessellation,
  32965. sideOrientation: sideOrientation,
  32966. updatable: updatable
  32967. };
  32968. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32969. };
  32970. /**
  32971. * Creates a box mesh.
  32972. * Please consider using the same method from the MeshBuilder class instead.
  32973. * The parameter `size` sets the size (float) of each box side (default 1).
  32974. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32975. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32977. */
  32978. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32979. if (scene === void 0) { scene = null; }
  32980. var options = {
  32981. size: size,
  32982. sideOrientation: sideOrientation,
  32983. updatable: updatable
  32984. };
  32985. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32986. };
  32987. /**
  32988. * Creates a sphere mesh.
  32989. * Please consider using the same method from the MeshBuilder class instead.
  32990. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32991. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32993. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32995. */
  32996. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32997. var options = {
  32998. segments: segments,
  32999. diameterX: diameter,
  33000. diameterY: diameter,
  33001. diameterZ: diameter,
  33002. sideOrientation: sideOrientation,
  33003. updatable: updatable
  33004. };
  33005. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33006. };
  33007. /**
  33008. * Creates a cylinder or a cone mesh.
  33009. * Please consider using the same method from the MeshBuilder class instead.
  33010. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33011. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33012. * 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.
  33013. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33014. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33016. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33018. */
  33019. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33020. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33021. if (scene !== undefined) {
  33022. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33023. updatable = scene;
  33024. }
  33025. scene = subdivisions;
  33026. subdivisions = 1;
  33027. }
  33028. var options = {
  33029. height: height,
  33030. diameterTop: diameterTop,
  33031. diameterBottom: diameterBottom,
  33032. tessellation: tessellation,
  33033. subdivisions: subdivisions,
  33034. sideOrientation: sideOrientation,
  33035. updatable: updatable
  33036. };
  33037. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33038. };
  33039. // Torus (Code from SharpDX.org)
  33040. /**
  33041. * Creates a torus mesh.
  33042. * Please consider using the same method from the MeshBuilder class instead.
  33043. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33044. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33045. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33047. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33049. */
  33050. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33051. var options = {
  33052. diameter: diameter,
  33053. thickness: thickness,
  33054. tessellation: tessellation,
  33055. sideOrientation: sideOrientation,
  33056. updatable: updatable
  33057. };
  33058. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33059. };
  33060. /**
  33061. * Creates a torus knot mesh.
  33062. * Please consider using the same method from the MeshBuilder class instead.
  33063. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33064. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33065. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33066. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33068. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33070. */
  33071. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33072. var options = {
  33073. radius: radius,
  33074. tube: tube,
  33075. radialSegments: radialSegments,
  33076. tubularSegments: tubularSegments,
  33077. p: p,
  33078. q: q,
  33079. sideOrientation: sideOrientation,
  33080. updatable: updatable
  33081. };
  33082. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33083. };
  33084. /**
  33085. * Creates a line mesh.
  33086. * Please consider using the same method from the MeshBuilder class instead.
  33087. * 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.
  33088. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33089. * The parameter `points` is an array successive Vector3.
  33090. * 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
  33091. * When updating an instance, remember that only point positions can change, not the number of points.
  33092. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33093. */
  33094. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33095. if (scene === void 0) { scene = null; }
  33096. if (updatable === void 0) { updatable = false; }
  33097. if (instance === void 0) { instance = null; }
  33098. var options = {
  33099. points: points,
  33100. updatable: updatable,
  33101. instance: instance
  33102. };
  33103. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33104. };
  33105. /**
  33106. * Creates a dashed line mesh.
  33107. * Please consider using the same method from the MeshBuilder class instead.
  33108. * 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.
  33109. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33110. * The parameter `points` is an array successive Vector3.
  33111. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33112. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33113. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33114. * 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
  33115. * When updating an instance, remember that only point positions can change, not the number of points.
  33116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33117. */
  33118. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33119. if (scene === void 0) { scene = null; }
  33120. var options = {
  33121. points: points,
  33122. dashSize: dashSize,
  33123. gapSize: gapSize,
  33124. dashNb: dashNb,
  33125. updatable: updatable,
  33126. instance: instance
  33127. };
  33128. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33129. };
  33130. /**
  33131. * Creates a polygon mesh.
  33132. * Please consider using the same method from the MeshBuilder class instead.
  33133. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33134. * 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.
  33135. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33136. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33137. * Remember you can only change the shape positions, not their number when updating a polygon.
  33138. */
  33139. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33140. var options = {
  33141. shape: shape,
  33142. holes: holes,
  33143. updatable: updatable,
  33144. sideOrientation: sideOrientation
  33145. };
  33146. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33147. };
  33148. /**
  33149. * Creates an extruded polygon mesh, with depth in the Y direction.
  33150. * Please consider using the same method from the MeshBuilder class instead.
  33151. */
  33152. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33153. var options = {
  33154. shape: shape,
  33155. holes: holes,
  33156. depth: depth,
  33157. updatable: updatable,
  33158. sideOrientation: sideOrientation
  33159. };
  33160. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33161. };
  33162. /**
  33163. * Creates an extruded shape mesh.
  33164. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33165. * Please consider using the same method from the MeshBuilder class instead.
  33166. *
  33167. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33168. * 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
  33169. * extruded along the Z axis.
  33170. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33171. * 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.
  33172. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33173. * 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
  33174. * 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
  33175. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33177. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33179. */
  33180. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33181. if (scene === void 0) { scene = null; }
  33182. var options = {
  33183. shape: shape,
  33184. path: path,
  33185. scale: scale,
  33186. rotation: rotation,
  33187. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33188. sideOrientation: sideOrientation,
  33189. instance: instance,
  33190. updatable: updatable
  33191. };
  33192. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33193. };
  33194. /**
  33195. * Creates an custom extruded shape mesh.
  33196. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33197. * Please consider using the same method from the MeshBuilder class instead.
  33198. *
  33199. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33200. * 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
  33201. * extruded along the Z axis.
  33202. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33203. * 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
  33204. * and the distance of this point from the begining of the path :
  33205. * ```javascript
  33206. * var rotationFunction = function(i, distance) {
  33207. * // do things
  33208. * return rotationValue; }
  33209. * ```
  33210. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33211. * 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
  33212. * and the distance of this point from the begining of the path :
  33213. * ```javascript
  33214. * var scaleFunction = function(i, distance) {
  33215. * // do things
  33216. * return scaleValue;}
  33217. * ```
  33218. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33219. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33220. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33221. * 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
  33222. * 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
  33223. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33224. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33225. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33227. */
  33228. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33229. var options = {
  33230. shape: shape,
  33231. path: path,
  33232. scaleFunction: scaleFunction,
  33233. rotationFunction: rotationFunction,
  33234. ribbonCloseArray: ribbonCloseArray,
  33235. ribbonClosePath: ribbonClosePath,
  33236. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33237. sideOrientation: sideOrientation,
  33238. instance: instance,
  33239. updatable: updatable
  33240. };
  33241. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33242. };
  33243. /**
  33244. * Creates lathe mesh.
  33245. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33246. * Please consider using the same method from the MeshBuilder class instead.
  33247. * 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
  33248. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33249. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33250. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33252. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33254. */
  33255. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33256. var options = {
  33257. shape: shape,
  33258. radius: radius,
  33259. tessellation: tessellation,
  33260. sideOrientation: sideOrientation,
  33261. updatable: updatable
  33262. };
  33263. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33264. };
  33265. /**
  33266. * Creates a plane mesh.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33270. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33272. */
  33273. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33274. var options = {
  33275. size: size,
  33276. width: size,
  33277. height: size,
  33278. sideOrientation: sideOrientation,
  33279. updatable: updatable
  33280. };
  33281. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33282. };
  33283. /**
  33284. * Creates a ground mesh.
  33285. * Please consider using the same method from the MeshBuilder class instead.
  33286. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33287. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33289. */
  33290. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33291. var options = {
  33292. width: width,
  33293. height: height,
  33294. subdivisions: subdivisions,
  33295. updatable: updatable
  33296. };
  33297. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33298. };
  33299. /**
  33300. * Creates a tiled ground mesh.
  33301. * Please consider using the same method from the MeshBuilder class instead.
  33302. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33303. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33304. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33305. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33306. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33307. * numbers of subdivisions on the ground width and height of each tile.
  33308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33309. */
  33310. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33311. var options = {
  33312. xmin: xmin,
  33313. zmin: zmin,
  33314. xmax: xmax,
  33315. zmax: zmax,
  33316. subdivisions: subdivisions,
  33317. precision: precision,
  33318. updatable: updatable
  33319. };
  33320. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33321. };
  33322. /**
  33323. * Creates a ground mesh from a height map.
  33324. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33325. * Please consider using the same method from the MeshBuilder class instead.
  33326. * @param url sets the URL of the height map image resource.
  33327. * @param width (positive float, default 10) set the ground width size.
  33328. * @param height (positive float, default 10) set the ground height size.
  33329. * @param subdivisions (positive integer, default 1) sets the number of subdivision per side.
  33330. * @param minHeight (float, default 0) is the minimum altitude on the ground.
  33331. * @param maxHeight (float, default 1) is the maximum altitude on the ground.
  33332. * @param onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33333. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible).
  33334. * This function is passed the newly built mesh :
  33335. * ```javascript
  33336. * function(mesh) { // do things
  33337. * return; }
  33338. * ```
  33339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33340. */
  33341. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33342. var options = {
  33343. width: width,
  33344. height: height,
  33345. subdivisions: subdivisions,
  33346. minHeight: minHeight,
  33347. maxHeight: maxHeight,
  33348. updatable: updatable,
  33349. onReady: onReady,
  33350. alphaFilter: alphaFilter
  33351. };
  33352. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33353. };
  33354. /**
  33355. * Creates a tube mesh.
  33356. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33359. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33360. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33361. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33362. * 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.
  33363. * It must return a radius value (positive float) :
  33364. * ```javascript
  33365. * var radiusFunction = function(i, distance) {
  33366. * // do things
  33367. * return radius; }
  33368. * ```
  33369. * 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
  33370. * 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
  33371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33372. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33374. */
  33375. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33376. var options = {
  33377. path: path,
  33378. radius: radius,
  33379. tessellation: tessellation,
  33380. radiusFunction: radiusFunction,
  33381. arc: 1,
  33382. cap: cap,
  33383. updatable: updatable,
  33384. sideOrientation: sideOrientation,
  33385. instance: instance
  33386. };
  33387. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33388. };
  33389. /**
  33390. * Creates a polyhedron mesh.
  33391. * Please consider using the same method from the MeshBuilder class instead.
  33392. * 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
  33393. * to choose the wanted type.
  33394. * The parameter `size` (positive float, default 1) sets the polygon size.
  33395. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33396. * 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`.
  33397. * 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
  33398. * 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)`).
  33399. * 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
  33400. * 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.
  33401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33402. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33404. */
  33405. Mesh.CreatePolyhedron = function (name, options, scene) {
  33406. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33407. };
  33408. /**
  33409. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33410. * Please consider using the same method from the MeshBuilder class instead.
  33411. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33412. * 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`).
  33413. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33414. * 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.
  33415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33416. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33418. */
  33419. Mesh.CreateIcoSphere = function (name, options, scene) {
  33420. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33421. };
  33422. /**
  33423. * Creates a decal mesh.
  33424. * Please consider using the same method from the MeshBuilder class instead.
  33425. * 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.
  33426. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33427. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33428. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33429. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33430. */
  33431. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33432. var options = {
  33433. position: position,
  33434. normal: normal,
  33435. size: size,
  33436. angle: angle
  33437. };
  33438. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33439. };
  33440. // Skeletons
  33441. /**
  33442. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33443. */
  33444. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33445. if (!this._sourcePositions) {
  33446. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33447. if (!source) {
  33448. return this._sourcePositions;
  33449. }
  33450. this._sourcePositions = new Float32Array(source);
  33451. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33452. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33453. }
  33454. }
  33455. return this._sourcePositions;
  33456. };
  33457. /**
  33458. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33459. */
  33460. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33461. if (!this._sourceNormals) {
  33462. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33463. if (!source) {
  33464. return this._sourceNormals;
  33465. }
  33466. this._sourceNormals = new Float32Array(source);
  33467. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33469. }
  33470. }
  33471. return this._sourceNormals;
  33472. };
  33473. /**
  33474. * Updates the vertex buffer by applying transformation from the bones.
  33475. * Returns the Mesh.
  33476. *
  33477. * @param {skeleton} skeleton to apply
  33478. */
  33479. Mesh.prototype.applySkeleton = function (skeleton) {
  33480. if (!this.geometry) {
  33481. return this;
  33482. }
  33483. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33484. return this;
  33485. }
  33486. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33487. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33488. return this;
  33489. }
  33490. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33491. return this;
  33492. }
  33493. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33494. return this;
  33495. }
  33496. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33497. return this;
  33498. }
  33499. if (!this._sourcePositions) {
  33500. var submeshes = this.subMeshes.slice();
  33501. this.setPositionsForCPUSkinning();
  33502. this.subMeshes = submeshes;
  33503. }
  33504. if (!this._sourceNormals) {
  33505. this.setNormalsForCPUSkinning();
  33506. }
  33507. // positionsData checks for not being Float32Array will only pass at most once
  33508. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33509. if (!positionsData) {
  33510. return this;
  33511. }
  33512. if (!(positionsData instanceof Float32Array)) {
  33513. positionsData = new Float32Array(positionsData);
  33514. }
  33515. // normalsData checks for not being Float32Array will only pass at most once
  33516. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33517. if (!normalsData) {
  33518. return this;
  33519. }
  33520. if (!(normalsData instanceof Float32Array)) {
  33521. normalsData = new Float32Array(normalsData);
  33522. }
  33523. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33524. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33525. if (!matricesWeightsData || !matricesIndicesData) {
  33526. return this;
  33527. }
  33528. var needExtras = this.numBoneInfluencers > 4;
  33529. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33530. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33531. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33532. var tempVector3 = BABYLON.Vector3.Zero();
  33533. var finalMatrix = new BABYLON.Matrix();
  33534. var tempMatrix = new BABYLON.Matrix();
  33535. var matWeightIdx = 0;
  33536. var inf;
  33537. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33538. var weight;
  33539. for (inf = 0; inf < 4; inf++) {
  33540. weight = matricesWeightsData[matWeightIdx + inf];
  33541. if (weight > 0) {
  33542. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33543. finalMatrix.addToSelf(tempMatrix);
  33544. }
  33545. }
  33546. if (needExtras) {
  33547. for (inf = 0; inf < 4; inf++) {
  33548. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33549. if (weight > 0) {
  33550. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33551. finalMatrix.addToSelf(tempMatrix);
  33552. }
  33553. }
  33554. }
  33555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33556. tempVector3.toArray(positionsData, index);
  33557. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33558. tempVector3.toArray(normalsData, index);
  33559. finalMatrix.reset();
  33560. }
  33561. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33562. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33563. return this;
  33564. };
  33565. // Tools
  33566. /**
  33567. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33568. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33569. */
  33570. Mesh.MinMax = function (meshes) {
  33571. var minVector = null;
  33572. var maxVector = null;
  33573. meshes.forEach(function (mesh, index, array) {
  33574. var boundingInfo = mesh.getBoundingInfo();
  33575. var boundingBox = boundingInfo.boundingBox;
  33576. if (!minVector || !maxVector) {
  33577. minVector = boundingBox.minimumWorld;
  33578. maxVector = boundingBox.maximumWorld;
  33579. }
  33580. else {
  33581. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33582. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33583. }
  33584. });
  33585. if (!minVector || !maxVector) {
  33586. return {
  33587. min: BABYLON.Vector3.Zero(),
  33588. max: BABYLON.Vector3.Zero()
  33589. };
  33590. }
  33591. return {
  33592. min: minVector,
  33593. max: maxVector
  33594. };
  33595. };
  33596. /**
  33597. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33598. */
  33599. Mesh.Center = function (meshesOrMinMaxVector) {
  33600. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33601. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33602. };
  33603. /**
  33604. * Merge the array of meshes into a single mesh for performance reasons.
  33605. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33606. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33607. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33608. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33609. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33610. */
  33611. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33612. if (disposeSource === void 0) { disposeSource = true; }
  33613. var index;
  33614. if (!allow32BitsIndices) {
  33615. var totalVertices = 0;
  33616. // Counting vertices
  33617. for (index = 0; index < meshes.length; index++) {
  33618. if (meshes[index]) {
  33619. totalVertices += meshes[index].getTotalVertices();
  33620. if (totalVertices > 65536) {
  33621. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33622. return null;
  33623. }
  33624. }
  33625. }
  33626. }
  33627. // Merge
  33628. var vertexData = null;
  33629. var otherVertexData;
  33630. var indiceArray = new Array();
  33631. var source = null;
  33632. for (index = 0; index < meshes.length; index++) {
  33633. if (meshes[index]) {
  33634. var wm = meshes[index].computeWorldMatrix(true);
  33635. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33636. otherVertexData.transform(wm);
  33637. if (vertexData) {
  33638. vertexData.merge(otherVertexData, allow32BitsIndices);
  33639. }
  33640. else {
  33641. vertexData = otherVertexData;
  33642. source = meshes[index];
  33643. }
  33644. if (subdivideWithSubMeshes) {
  33645. indiceArray.push(meshes[index].getTotalIndices());
  33646. }
  33647. }
  33648. }
  33649. source = source;
  33650. if (!meshSubclass) {
  33651. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33652. }
  33653. vertexData.applyToMesh(meshSubclass);
  33654. // Setting properties
  33655. meshSubclass.material = source.material;
  33656. meshSubclass.checkCollisions = source.checkCollisions;
  33657. // Cleaning
  33658. if (disposeSource) {
  33659. for (index = 0; index < meshes.length; index++) {
  33660. if (meshes[index]) {
  33661. meshes[index].dispose();
  33662. }
  33663. }
  33664. }
  33665. // Subdivide
  33666. if (subdivideWithSubMeshes) {
  33667. //-- removal of global submesh
  33668. meshSubclass.releaseSubMeshes();
  33669. index = 0;
  33670. var offset = 0;
  33671. //-- apply subdivision according to index table
  33672. while (index < indiceArray.length) {
  33673. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33674. offset += indiceArray[index];
  33675. index++;
  33676. }
  33677. }
  33678. return meshSubclass;
  33679. };
  33680. // Consts
  33681. Mesh._FRONTSIDE = 0;
  33682. Mesh._BACKSIDE = 1;
  33683. Mesh._DOUBLESIDE = 2;
  33684. Mesh._DEFAULTSIDE = 0;
  33685. Mesh._NO_CAP = 0;
  33686. Mesh._CAP_START = 1;
  33687. Mesh._CAP_END = 2;
  33688. Mesh._CAP_ALL = 3;
  33689. return Mesh;
  33690. }(BABYLON.AbstractMesh));
  33691. BABYLON.Mesh = Mesh;
  33692. })(BABYLON || (BABYLON = {}));
  33693. //# sourceMappingURL=babylon.mesh.js.map
  33694. var BABYLON;
  33695. (function (BABYLON) {
  33696. var BaseSubMesh = /** @class */ (function () {
  33697. function BaseSubMesh() {
  33698. }
  33699. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33700. get: function () {
  33701. return this._materialEffect;
  33702. },
  33703. enumerable: true,
  33704. configurable: true
  33705. });
  33706. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33707. if (defines === void 0) { defines = null; }
  33708. if (this._materialEffect === effect) {
  33709. if (!effect) {
  33710. this._materialDefines = null;
  33711. }
  33712. return;
  33713. }
  33714. this._materialDefines = defines;
  33715. this._materialEffect = effect;
  33716. };
  33717. return BaseSubMesh;
  33718. }());
  33719. BABYLON.BaseSubMesh = BaseSubMesh;
  33720. var SubMesh = /** @class */ (function (_super) {
  33721. __extends(SubMesh, _super);
  33722. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33723. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33724. var _this = _super.call(this) || this;
  33725. _this.materialIndex = materialIndex;
  33726. _this.verticesStart = verticesStart;
  33727. _this.verticesCount = verticesCount;
  33728. _this.indexStart = indexStart;
  33729. _this.indexCount = indexCount;
  33730. /** @hidden */
  33731. _this._renderId = 0;
  33732. _this._mesh = mesh;
  33733. _this._renderingMesh = renderingMesh || mesh;
  33734. mesh.subMeshes.push(_this);
  33735. _this._trianglePlanes = [];
  33736. _this._id = mesh.subMeshes.length - 1;
  33737. if (createBoundingBox) {
  33738. _this.refreshBoundingInfo();
  33739. mesh.computeWorldMatrix(true);
  33740. }
  33741. return _this;
  33742. }
  33743. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33744. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33745. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33746. };
  33747. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33748. get: function () {
  33749. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33750. },
  33751. enumerable: true,
  33752. configurable: true
  33753. });
  33754. /**
  33755. * Returns the submesh BoudingInfo object.
  33756. */
  33757. SubMesh.prototype.getBoundingInfo = function () {
  33758. if (this.IsGlobal) {
  33759. return this._mesh.getBoundingInfo();
  33760. }
  33761. return this._boundingInfo;
  33762. };
  33763. /**
  33764. * Sets the submesh BoundingInfo.
  33765. * Return the SubMesh.
  33766. */
  33767. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33768. this._boundingInfo = boundingInfo;
  33769. return this;
  33770. };
  33771. /**
  33772. * Returns the mesh of the current submesh.
  33773. */
  33774. SubMesh.prototype.getMesh = function () {
  33775. return this._mesh;
  33776. };
  33777. /**
  33778. * Returns the rendering mesh of the submesh.
  33779. */
  33780. SubMesh.prototype.getRenderingMesh = function () {
  33781. return this._renderingMesh;
  33782. };
  33783. /**
  33784. * Returns the submesh material.
  33785. */
  33786. SubMesh.prototype.getMaterial = function () {
  33787. var rootMaterial = this._renderingMesh.material;
  33788. if (rootMaterial === null || rootMaterial === undefined) {
  33789. return this._mesh.getScene().defaultMaterial;
  33790. }
  33791. else if (rootMaterial.getSubMaterial) {
  33792. var multiMaterial = rootMaterial;
  33793. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33794. if (this._currentMaterial !== effectiveMaterial) {
  33795. this._currentMaterial = effectiveMaterial;
  33796. this._materialDefines = null;
  33797. }
  33798. return effectiveMaterial;
  33799. }
  33800. return rootMaterial;
  33801. };
  33802. // Methods
  33803. /**
  33804. * Sets a new updated BoundingInfo object to the submesh.
  33805. * Returns the SubMesh.
  33806. */
  33807. SubMesh.prototype.refreshBoundingInfo = function () {
  33808. this._lastColliderWorldVertices = null;
  33809. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33810. return this;
  33811. }
  33812. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33813. if (!data) {
  33814. this._boundingInfo = this._mesh.getBoundingInfo();
  33815. return this;
  33816. }
  33817. var indices = this._renderingMesh.getIndices();
  33818. var extend;
  33819. //is this the only submesh?
  33820. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33821. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33822. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33823. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33824. }
  33825. else {
  33826. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33827. }
  33828. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33829. return this;
  33830. };
  33831. /** @hidden */
  33832. SubMesh.prototype._checkCollision = function (collider) {
  33833. var boundingInfo = this.getBoundingInfo();
  33834. return boundingInfo._checkCollision(collider);
  33835. };
  33836. /**
  33837. * Updates the submesh BoundingInfo.
  33838. * Returns the Submesh.
  33839. */
  33840. SubMesh.prototype.updateBoundingInfo = function (world) {
  33841. var boundingInfo = this.getBoundingInfo();
  33842. if (!boundingInfo) {
  33843. this.refreshBoundingInfo();
  33844. boundingInfo = this.getBoundingInfo();
  33845. }
  33846. boundingInfo.update(world);
  33847. return this;
  33848. };
  33849. /**
  33850. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33851. * Boolean returned.
  33852. */
  33853. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33854. var boundingInfo = this.getBoundingInfo();
  33855. if (!boundingInfo) {
  33856. return false;
  33857. }
  33858. return boundingInfo.isInFrustum(frustumPlanes);
  33859. };
  33860. /**
  33861. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33862. * Boolean returned.
  33863. */
  33864. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33865. var boundingInfo = this.getBoundingInfo();
  33866. if (!boundingInfo) {
  33867. return false;
  33868. }
  33869. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33870. };
  33871. /**
  33872. * Renders the submesh.
  33873. * Returns it.
  33874. */
  33875. SubMesh.prototype.render = function (enableAlphaMode) {
  33876. this._renderingMesh.render(this, enableAlphaMode);
  33877. return this;
  33878. };
  33879. /**
  33880. * Returns a new Index Buffer.
  33881. * Type returned : WebGLBuffer.
  33882. */
  33883. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33884. if (!this._linesIndexBuffer) {
  33885. var linesIndices = [];
  33886. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33887. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33888. }
  33889. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33890. this.linesIndexCount = linesIndices.length;
  33891. }
  33892. return this._linesIndexBuffer;
  33893. };
  33894. /**
  33895. * True is the passed Ray intersects the submesh bounding box.
  33896. * Boolean returned.
  33897. */
  33898. SubMesh.prototype.canIntersects = function (ray) {
  33899. var boundingInfo = this.getBoundingInfo();
  33900. if (!boundingInfo) {
  33901. return false;
  33902. }
  33903. return ray.intersectsBox(boundingInfo.boundingBox);
  33904. };
  33905. /**
  33906. * Returns an object IntersectionInfo.
  33907. */
  33908. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33909. var intersectInfo = null;
  33910. var material = this.getMaterial();
  33911. if (!material) {
  33912. return null;
  33913. }
  33914. switch (material.fillMode) {
  33915. case BABYLON.Material.PointListDrawMode:
  33916. case BABYLON.Material.LineListDrawMode:
  33917. case BABYLON.Material.LineLoopDrawMode:
  33918. case BABYLON.Material.LineStripDrawMode:
  33919. case BABYLON.Material.TriangleFanDrawMode:
  33920. case BABYLON.Material.TriangleStripDrawMode:
  33921. return null;
  33922. }
  33923. // LineMesh first as it's also a Mesh...
  33924. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33925. var lineMesh = this._mesh;
  33926. // Line test
  33927. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33928. var p0 = positions[indices[index]];
  33929. var p1 = positions[indices[index + 1]];
  33930. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33931. if (length < 0) {
  33932. continue;
  33933. }
  33934. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33935. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33936. if (fastCheck) {
  33937. break;
  33938. }
  33939. }
  33940. }
  33941. }
  33942. else {
  33943. // Triangles test
  33944. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33945. var p0 = positions[indices[index]];
  33946. var p1 = positions[indices[index + 1]];
  33947. var p2 = positions[indices[index + 2]];
  33948. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33949. if (currentIntersectInfo) {
  33950. if (currentIntersectInfo.distance < 0) {
  33951. continue;
  33952. }
  33953. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33954. intersectInfo = currentIntersectInfo;
  33955. intersectInfo.faceId = index / 3;
  33956. if (fastCheck) {
  33957. break;
  33958. }
  33959. }
  33960. }
  33961. }
  33962. }
  33963. return intersectInfo;
  33964. };
  33965. /** @hidden */
  33966. SubMesh.prototype._rebuild = function () {
  33967. if (this._linesIndexBuffer) {
  33968. this._linesIndexBuffer = null;
  33969. }
  33970. };
  33971. // Clone
  33972. /**
  33973. * Creates a new Submesh from the passed Mesh.
  33974. */
  33975. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33976. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33977. if (!this.IsGlobal) {
  33978. var boundingInfo = this.getBoundingInfo();
  33979. if (!boundingInfo) {
  33980. return result;
  33981. }
  33982. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33983. }
  33984. return result;
  33985. };
  33986. // Dispose
  33987. /**
  33988. * Disposes the Submesh.
  33989. * Returns nothing.
  33990. */
  33991. SubMesh.prototype.dispose = function () {
  33992. if (this._linesIndexBuffer) {
  33993. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33994. this._linesIndexBuffer = null;
  33995. }
  33996. // Remove from mesh
  33997. var index = this._mesh.subMeshes.indexOf(this);
  33998. this._mesh.subMeshes.splice(index, 1);
  33999. };
  34000. // Statics
  34001. /**
  34002. * Creates a new Submesh from the passed parameters :
  34003. * - materialIndex (integer) : the index of the main mesh material.
  34004. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34005. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34006. * - mesh (Mesh) : the main mesh to create the submesh from.
  34007. * - renderingMesh (optional Mesh) : rendering mesh.
  34008. */
  34009. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34010. var minVertexIndex = Number.MAX_VALUE;
  34011. var maxVertexIndex = -Number.MAX_VALUE;
  34012. renderingMesh = (renderingMesh || mesh);
  34013. var indices = renderingMesh.getIndices();
  34014. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34015. var vertexIndex = indices[index];
  34016. if (vertexIndex < minVertexIndex)
  34017. minVertexIndex = vertexIndex;
  34018. if (vertexIndex > maxVertexIndex)
  34019. maxVertexIndex = vertexIndex;
  34020. }
  34021. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34022. };
  34023. return SubMesh;
  34024. }(BaseSubMesh));
  34025. BABYLON.SubMesh = SubMesh;
  34026. })(BABYLON || (BABYLON = {}));
  34027. //# sourceMappingURL=babylon.subMesh.js.map
  34028. var __assign = (this && this.__assign) || function () {
  34029. __assign = Object.assign || function(t) {
  34030. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34031. s = arguments[i];
  34032. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34033. t[p] = s[p];
  34034. }
  34035. return t;
  34036. };
  34037. return __assign.apply(this, arguments);
  34038. };
  34039. var BABYLON;
  34040. (function (BABYLON) {
  34041. /**
  34042. * Manages the defines for the Material
  34043. */
  34044. var MaterialDefines = /** @class */ (function () {
  34045. function MaterialDefines() {
  34046. this._isDirty = true;
  34047. /** @hidden */
  34048. this._areLightsDirty = true;
  34049. /** @hidden */
  34050. this._areAttributesDirty = true;
  34051. /** @hidden */
  34052. this._areTexturesDirty = true;
  34053. /** @hidden */
  34054. this._areFresnelDirty = true;
  34055. /** @hidden */
  34056. this._areMiscDirty = true;
  34057. /** @hidden */
  34058. this._areImageProcessingDirty = true;
  34059. /** @hidden */
  34060. this._normals = false;
  34061. /** @hidden */
  34062. this._uvs = false;
  34063. /** @hidden */
  34064. this._needNormals = false;
  34065. /** @hidden */
  34066. this._needUVs = false;
  34067. }
  34068. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34069. /**
  34070. * Specifies if the material needs to be re-calculated
  34071. */
  34072. get: function () {
  34073. return this._isDirty;
  34074. },
  34075. enumerable: true,
  34076. configurable: true
  34077. });
  34078. /**
  34079. * Marks the material to indicate that it has been re-calculated
  34080. */
  34081. MaterialDefines.prototype.markAsProcessed = function () {
  34082. this._isDirty = false;
  34083. this._areAttributesDirty = false;
  34084. this._areTexturesDirty = false;
  34085. this._areFresnelDirty = false;
  34086. this._areLightsDirty = false;
  34087. this._areMiscDirty = false;
  34088. this._areImageProcessingDirty = false;
  34089. };
  34090. /**
  34091. * Marks the material to indicate that it needs to be re-calculated
  34092. */
  34093. MaterialDefines.prototype.markAsUnprocessed = function () {
  34094. this._isDirty = true;
  34095. };
  34096. /**
  34097. * Marks the material to indicate all of its defines need to be re-calculated
  34098. */
  34099. MaterialDefines.prototype.markAllAsDirty = function () {
  34100. this._areTexturesDirty = true;
  34101. this._areAttributesDirty = true;
  34102. this._areLightsDirty = true;
  34103. this._areFresnelDirty = true;
  34104. this._areMiscDirty = true;
  34105. this._areImageProcessingDirty = true;
  34106. this._isDirty = true;
  34107. };
  34108. /**
  34109. * Marks the material to indicate that image processing needs to be re-calculated
  34110. */
  34111. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34112. this._areImageProcessingDirty = true;
  34113. this._isDirty = true;
  34114. };
  34115. /**
  34116. * Marks the material to indicate the lights need to be re-calculated
  34117. */
  34118. MaterialDefines.prototype.markAsLightDirty = function () {
  34119. this._areLightsDirty = true;
  34120. this._isDirty = true;
  34121. };
  34122. /**
  34123. * Marks the attribute state as changed
  34124. */
  34125. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34126. this._areAttributesDirty = true;
  34127. this._isDirty = true;
  34128. };
  34129. /**
  34130. * Marks the texture state as changed
  34131. */
  34132. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34133. this._areTexturesDirty = true;
  34134. this._isDirty = true;
  34135. };
  34136. /**
  34137. * Marks the fresnel state as changed
  34138. */
  34139. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34140. this._areFresnelDirty = true;
  34141. this._isDirty = true;
  34142. };
  34143. /**
  34144. * Marks the misc state as changed
  34145. */
  34146. MaterialDefines.prototype.markAsMiscDirty = function () {
  34147. this._areMiscDirty = true;
  34148. this._isDirty = true;
  34149. };
  34150. /**
  34151. * Rebuilds the material defines
  34152. */
  34153. MaterialDefines.prototype.rebuild = function () {
  34154. if (this._keys) {
  34155. delete this._keys;
  34156. }
  34157. this._keys = [];
  34158. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34159. var key = _a[_i];
  34160. if (key[0] === "_") {
  34161. continue;
  34162. }
  34163. this._keys.push(key);
  34164. }
  34165. };
  34166. /**
  34167. * Specifies if two material defines are equal
  34168. * @param other - A material define instance to compare to
  34169. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34170. */
  34171. MaterialDefines.prototype.isEqual = function (other) {
  34172. if (this._keys.length !== other._keys.length) {
  34173. return false;
  34174. }
  34175. for (var index = 0; index < this._keys.length; index++) {
  34176. var prop = this._keys[index];
  34177. if (this[prop] !== other[prop]) {
  34178. return false;
  34179. }
  34180. }
  34181. return true;
  34182. };
  34183. /**
  34184. * Clones this instance's defines to another instance
  34185. * @param other - material defines to clone values to
  34186. */
  34187. MaterialDefines.prototype.cloneTo = function (other) {
  34188. if (this._keys.length !== other._keys.length) {
  34189. other._keys = this._keys.slice(0);
  34190. }
  34191. for (var index = 0; index < this._keys.length; index++) {
  34192. var prop = this._keys[index];
  34193. other[prop] = this[prop];
  34194. }
  34195. };
  34196. /**
  34197. * Resets the material define values
  34198. */
  34199. MaterialDefines.prototype.reset = function () {
  34200. for (var index = 0; index < this._keys.length; index++) {
  34201. var prop = this._keys[index];
  34202. var type = typeof this[prop];
  34203. switch (type) {
  34204. case "number":
  34205. this[prop] = 0;
  34206. break;
  34207. case "string":
  34208. this[prop] = "";
  34209. break;
  34210. default:
  34211. this[prop] = false;
  34212. break;
  34213. }
  34214. }
  34215. };
  34216. /**
  34217. * Converts the material define values to a string
  34218. * @returns - String of material define information
  34219. */
  34220. MaterialDefines.prototype.toString = function () {
  34221. var result = "";
  34222. for (var index = 0; index < this._keys.length; index++) {
  34223. var prop = this._keys[index];
  34224. var value = this[prop];
  34225. var type = typeof value;
  34226. switch (type) {
  34227. case "number":
  34228. case "string":
  34229. result += "#define " + prop + " " + value + "\n";
  34230. break;
  34231. default:
  34232. if (value) {
  34233. result += "#define " + prop + "\n";
  34234. }
  34235. break;
  34236. }
  34237. }
  34238. return result;
  34239. };
  34240. return MaterialDefines;
  34241. }());
  34242. BABYLON.MaterialDefines = MaterialDefines;
  34243. /**
  34244. * Base class for the main features of a material in Babylon.js
  34245. */
  34246. var Material = /** @class */ (function () {
  34247. /**
  34248. * Creates a material instance
  34249. * @param name defines the name of the material
  34250. * @param scene defines the scene to reference
  34251. * @param doNotAdd specifies if the material should be added to the scene
  34252. */
  34253. function Material(name, scene, doNotAdd) {
  34254. /**
  34255. * Specifies if the ready state should be checked on each call
  34256. */
  34257. this.checkReadyOnEveryCall = false;
  34258. /**
  34259. * Specifies if the ready state should be checked once
  34260. */
  34261. this.checkReadyOnlyOnce = false;
  34262. /**
  34263. * The state of the material
  34264. */
  34265. this.state = "";
  34266. /**
  34267. * The alpha value of the material
  34268. */
  34269. this._alpha = 1.0;
  34270. /**
  34271. * Specifies if back face culling is enabled
  34272. */
  34273. this._backFaceCulling = true;
  34274. /**
  34275. * Gets a boolean indicating that current material needs to register RTT
  34276. */
  34277. this.hasRenderTargetTextures = false;
  34278. /**
  34279. * Specifies if the material should be serialized
  34280. */
  34281. this.doNotSerialize = false;
  34282. /**
  34283. * Specifies if the effect should be stored on sub meshes
  34284. */
  34285. this.storeEffectOnSubMeshes = false;
  34286. /**
  34287. * An event triggered when the material is disposed
  34288. */
  34289. this.onDisposeObservable = new BABYLON.Observable();
  34290. /**
  34291. * Stores the value of the alpha mode
  34292. */
  34293. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34294. /**
  34295. * Stores the state of the need depth pre-pass value
  34296. */
  34297. this._needDepthPrePass = false;
  34298. /**
  34299. * Specifies if depth writing should be disabled
  34300. */
  34301. this.disableDepthWrite = false;
  34302. /**
  34303. * Specifies if depth writing should be forced
  34304. */
  34305. this.forceDepthWrite = false;
  34306. /**
  34307. * Specifies if there should be a separate pass for culling
  34308. */
  34309. this.separateCullingPass = false;
  34310. /**
  34311. * Stores the state specifing if fog should be enabled
  34312. */
  34313. this._fogEnabled = true;
  34314. /**
  34315. * Stores the size of points
  34316. */
  34317. this.pointSize = 1.0;
  34318. /**
  34319. * Stores the z offset value
  34320. */
  34321. this.zOffset = 0;
  34322. /**
  34323. * @hidden
  34324. * Specifies if the material was previously ready
  34325. */
  34326. this._wasPreviouslyReady = false;
  34327. /**
  34328. * Stores the fill mode state
  34329. */
  34330. this._fillMode = Material.TriangleFillMode;
  34331. this.name = name;
  34332. this.id = name || BABYLON.Tools.RandomId();
  34333. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34334. this.uniqueId = this._scene.getUniqueId();
  34335. if (this._scene.useRightHandedSystem) {
  34336. this.sideOrientation = Material.ClockWiseSideOrientation;
  34337. }
  34338. else {
  34339. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34340. }
  34341. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34342. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34343. if (!doNotAdd) {
  34344. this._scene.materials.push(this);
  34345. }
  34346. }
  34347. Object.defineProperty(Material, "TriangleFillMode", {
  34348. /**
  34349. * Returns the triangle fill mode
  34350. */
  34351. get: function () {
  34352. return Material._TriangleFillMode;
  34353. },
  34354. enumerable: true,
  34355. configurable: true
  34356. });
  34357. Object.defineProperty(Material, "WireFrameFillMode", {
  34358. /**
  34359. * Returns the wireframe mode
  34360. */
  34361. get: function () {
  34362. return Material._WireFrameFillMode;
  34363. },
  34364. enumerable: true,
  34365. configurable: true
  34366. });
  34367. Object.defineProperty(Material, "PointFillMode", {
  34368. /**
  34369. * Returns the point fill mode
  34370. */
  34371. get: function () {
  34372. return Material._PointFillMode;
  34373. },
  34374. enumerable: true,
  34375. configurable: true
  34376. });
  34377. Object.defineProperty(Material, "PointListDrawMode", {
  34378. /**
  34379. * Returns the point list draw mode
  34380. */
  34381. get: function () {
  34382. return Material._PointListDrawMode;
  34383. },
  34384. enumerable: true,
  34385. configurable: true
  34386. });
  34387. Object.defineProperty(Material, "LineListDrawMode", {
  34388. /**
  34389. * Returns the line list draw mode
  34390. */
  34391. get: function () {
  34392. return Material._LineListDrawMode;
  34393. },
  34394. enumerable: true,
  34395. configurable: true
  34396. });
  34397. Object.defineProperty(Material, "LineLoopDrawMode", {
  34398. /**
  34399. * Returns the line loop draw mode
  34400. */
  34401. get: function () {
  34402. return Material._LineLoopDrawMode;
  34403. },
  34404. enumerable: true,
  34405. configurable: true
  34406. });
  34407. Object.defineProperty(Material, "LineStripDrawMode", {
  34408. /**
  34409. * Returns the line strip draw mode
  34410. */
  34411. get: function () {
  34412. return Material._LineStripDrawMode;
  34413. },
  34414. enumerable: true,
  34415. configurable: true
  34416. });
  34417. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34418. /**
  34419. * Returns the triangle strip draw mode
  34420. */
  34421. get: function () {
  34422. return Material._TriangleStripDrawMode;
  34423. },
  34424. enumerable: true,
  34425. configurable: true
  34426. });
  34427. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34428. /**
  34429. * Returns the triangle fan draw mode
  34430. */
  34431. get: function () {
  34432. return Material._TriangleFanDrawMode;
  34433. },
  34434. enumerable: true,
  34435. configurable: true
  34436. });
  34437. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34438. /**
  34439. * Returns the clock-wise side orientation
  34440. */
  34441. get: function () {
  34442. return Material._ClockWiseSideOrientation;
  34443. },
  34444. enumerable: true,
  34445. configurable: true
  34446. });
  34447. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34448. /**
  34449. * Returns the counter clock-wise side orientation
  34450. */
  34451. get: function () {
  34452. return Material._CounterClockWiseSideOrientation;
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(Material, "TextureDirtyFlag", {
  34458. /**
  34459. * Returns the dirty texture flag value
  34460. */
  34461. get: function () {
  34462. return Material._TextureDirtyFlag;
  34463. },
  34464. enumerable: true,
  34465. configurable: true
  34466. });
  34467. Object.defineProperty(Material, "LightDirtyFlag", {
  34468. /**
  34469. * Returns the dirty light flag value
  34470. */
  34471. get: function () {
  34472. return Material._LightDirtyFlag;
  34473. },
  34474. enumerable: true,
  34475. configurable: true
  34476. });
  34477. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34478. /**
  34479. * Returns the dirty fresnel flag value
  34480. */
  34481. get: function () {
  34482. return Material._FresnelDirtyFlag;
  34483. },
  34484. enumerable: true,
  34485. configurable: true
  34486. });
  34487. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34488. /**
  34489. * Returns the dirty attributes flag value
  34490. */
  34491. get: function () {
  34492. return Material._AttributesDirtyFlag;
  34493. },
  34494. enumerable: true,
  34495. configurable: true
  34496. });
  34497. Object.defineProperty(Material, "MiscDirtyFlag", {
  34498. /**
  34499. * Returns the dirty misc flag value
  34500. */
  34501. get: function () {
  34502. return Material._MiscDirtyFlag;
  34503. },
  34504. enumerable: true,
  34505. configurable: true
  34506. });
  34507. Object.defineProperty(Material.prototype, "alpha", {
  34508. /**
  34509. * Gets the alpha value of the material
  34510. */
  34511. get: function () {
  34512. return this._alpha;
  34513. },
  34514. /**
  34515. * Sets the alpha value of the material
  34516. */
  34517. set: function (value) {
  34518. if (this._alpha === value) {
  34519. return;
  34520. }
  34521. this._alpha = value;
  34522. this.markAsDirty(Material.MiscDirtyFlag);
  34523. },
  34524. enumerable: true,
  34525. configurable: true
  34526. });
  34527. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34528. /**
  34529. * Gets the back-face culling state
  34530. */
  34531. get: function () {
  34532. return this._backFaceCulling;
  34533. },
  34534. /**
  34535. * Sets the back-face culling state
  34536. */
  34537. set: function (value) {
  34538. if (this._backFaceCulling === value) {
  34539. return;
  34540. }
  34541. this._backFaceCulling = value;
  34542. this.markAsDirty(Material.TextureDirtyFlag);
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. Object.defineProperty(Material.prototype, "onDispose", {
  34548. /**
  34549. * Called during a dispose event
  34550. */
  34551. set: function (callback) {
  34552. if (this._onDisposeObserver) {
  34553. this.onDisposeObservable.remove(this._onDisposeObserver);
  34554. }
  34555. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34556. },
  34557. enumerable: true,
  34558. configurable: true
  34559. });
  34560. Object.defineProperty(Material.prototype, "onBindObservable", {
  34561. /**
  34562. * An event triggered when the material is bound
  34563. */
  34564. get: function () {
  34565. if (!this._onBindObservable) {
  34566. this._onBindObservable = new BABYLON.Observable();
  34567. }
  34568. return this._onBindObservable;
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Material.prototype, "onBind", {
  34574. /**
  34575. * Called during a bind event
  34576. */
  34577. set: function (callback) {
  34578. if (this._onBindObserver) {
  34579. this.onBindObservable.remove(this._onBindObserver);
  34580. }
  34581. this._onBindObserver = this.onBindObservable.add(callback);
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34587. /**
  34588. * An event triggered when the material is unbound
  34589. */
  34590. get: function () {
  34591. if (!this._onUnBindObservable) {
  34592. this._onUnBindObservable = new BABYLON.Observable();
  34593. }
  34594. return this._onUnBindObservable;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material.prototype, "alphaMode", {
  34600. /**
  34601. * Gets the value of the alpha mode
  34602. */
  34603. get: function () {
  34604. return this._alphaMode;
  34605. },
  34606. /**
  34607. * Sets the value of the alpha mode.
  34608. *
  34609. * | Value | Type | Description |
  34610. * | --- | --- | --- |
  34611. * | 0 | ALPHA_DISABLE | |
  34612. * | 1 | ALPHA_ADD | |
  34613. * | 2 | ALPHA_COMBINE | |
  34614. * | 3 | ALPHA_SUBTRACT | |
  34615. * | 4 | ALPHA_MULTIPLY | |
  34616. * | 5 | ALPHA_MAXIMIZED | |
  34617. * | 6 | ALPHA_ONEONE | |
  34618. * | 7 | ALPHA_PREMULTIPLIED | |
  34619. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34620. * | 9 | ALPHA_INTERPOLATE | |
  34621. * | 10 | ALPHA_SCREENMODE | |
  34622. *
  34623. */
  34624. set: function (value) {
  34625. if (this._alphaMode === value) {
  34626. return;
  34627. }
  34628. this._alphaMode = value;
  34629. this.markAsDirty(Material.TextureDirtyFlag);
  34630. },
  34631. enumerable: true,
  34632. configurable: true
  34633. });
  34634. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34635. /**
  34636. * Gets the depth pre-pass value
  34637. */
  34638. get: function () {
  34639. return this._needDepthPrePass;
  34640. },
  34641. /**
  34642. * Sets the need depth pre-pass value
  34643. */
  34644. set: function (value) {
  34645. if (this._needDepthPrePass === value) {
  34646. return;
  34647. }
  34648. this._needDepthPrePass = value;
  34649. if (this._needDepthPrePass) {
  34650. this.checkReadyOnEveryCall = true;
  34651. }
  34652. },
  34653. enumerable: true,
  34654. configurable: true
  34655. });
  34656. Object.defineProperty(Material.prototype, "fogEnabled", {
  34657. /**
  34658. * Gets the value of the fog enabled state
  34659. */
  34660. get: function () {
  34661. return this._fogEnabled;
  34662. },
  34663. /**
  34664. * Sets the state for enabling fog
  34665. */
  34666. set: function (value) {
  34667. if (this._fogEnabled === value) {
  34668. return;
  34669. }
  34670. this._fogEnabled = value;
  34671. this.markAsDirty(Material.MiscDirtyFlag);
  34672. },
  34673. enumerable: true,
  34674. configurable: true
  34675. });
  34676. Object.defineProperty(Material.prototype, "wireframe", {
  34677. /**
  34678. * Gets a value specifying if wireframe mode is enabled
  34679. */
  34680. get: function () {
  34681. switch (this._fillMode) {
  34682. case Material.WireFrameFillMode:
  34683. case Material.LineListDrawMode:
  34684. case Material.LineLoopDrawMode:
  34685. case Material.LineStripDrawMode:
  34686. return true;
  34687. }
  34688. return this._scene.forceWireframe;
  34689. },
  34690. /**
  34691. * Sets the state of wireframe mode
  34692. */
  34693. set: function (value) {
  34694. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material.prototype, "pointsCloud", {
  34700. /**
  34701. * Gets the value specifying if point clouds are enabled
  34702. */
  34703. get: function () {
  34704. switch (this._fillMode) {
  34705. case Material.PointFillMode:
  34706. case Material.PointListDrawMode:
  34707. return true;
  34708. }
  34709. return this._scene.forcePointsCloud;
  34710. },
  34711. /**
  34712. * Sets the state of point cloud mode
  34713. */
  34714. set: function (value) {
  34715. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. Object.defineProperty(Material.prototype, "fillMode", {
  34721. /**
  34722. * Gets the material fill mode
  34723. */
  34724. get: function () {
  34725. return this._fillMode;
  34726. },
  34727. /**
  34728. * Sets the material fill mode
  34729. */
  34730. set: function (value) {
  34731. if (this._fillMode === value) {
  34732. return;
  34733. }
  34734. this._fillMode = value;
  34735. this.markAsDirty(Material.MiscDirtyFlag);
  34736. },
  34737. enumerable: true,
  34738. configurable: true
  34739. });
  34740. /**
  34741. * Returns a string representation of the current material
  34742. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34743. * @returns a string with material information
  34744. */
  34745. Material.prototype.toString = function (fullDetails) {
  34746. var ret = "Name: " + this.name;
  34747. if (fullDetails) {
  34748. }
  34749. return ret;
  34750. };
  34751. /**
  34752. * Gets the class name of the material
  34753. * @returns a string with the class name of the material
  34754. */
  34755. Material.prototype.getClassName = function () {
  34756. return "Material";
  34757. };
  34758. Object.defineProperty(Material.prototype, "isFrozen", {
  34759. /**
  34760. * Specifies if updates for the material been locked
  34761. */
  34762. get: function () {
  34763. return this.checkReadyOnlyOnce;
  34764. },
  34765. enumerable: true,
  34766. configurable: true
  34767. });
  34768. /**
  34769. * Locks updates for the material
  34770. */
  34771. Material.prototype.freeze = function () {
  34772. this.checkReadyOnlyOnce = true;
  34773. };
  34774. /**
  34775. * Unlocks updates for the material
  34776. */
  34777. Material.prototype.unfreeze = function () {
  34778. this.checkReadyOnlyOnce = false;
  34779. };
  34780. /**
  34781. * Specifies if the material is ready to be used
  34782. * @param mesh defines the mesh to check
  34783. * @param useInstances specifies if instances should be used
  34784. * @returns a boolean indicating if the material is ready to be used
  34785. */
  34786. Material.prototype.isReady = function (mesh, useInstances) {
  34787. return true;
  34788. };
  34789. /**
  34790. * Specifies that the submesh is ready to be used
  34791. * @param mesh defines the mesh to check
  34792. * @param subMesh defines which submesh to check
  34793. * @param useInstances specifies that instances should be used
  34794. * @returns a boolean indicating that the submesh is ready or not
  34795. */
  34796. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34797. return false;
  34798. };
  34799. /**
  34800. * Returns the material effect
  34801. * @returns the effect associated with the material
  34802. */
  34803. Material.prototype.getEffect = function () {
  34804. return this._effect;
  34805. };
  34806. /**
  34807. * Returns the current scene
  34808. * @returns a Scene
  34809. */
  34810. Material.prototype.getScene = function () {
  34811. return this._scene;
  34812. };
  34813. /**
  34814. * Specifies if the material will require alpha blending
  34815. * @returns a boolean specifying if alpha blending is needed
  34816. */
  34817. Material.prototype.needAlphaBlending = function () {
  34818. return (this.alpha < 1.0);
  34819. };
  34820. /**
  34821. * Specifies if the mesh will require alpha blending
  34822. * @param mesh defines the mesh to check
  34823. * @returns a boolean specifying if alpha blending is needed for the mesh
  34824. */
  34825. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34826. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34827. };
  34828. /**
  34829. * Specifies if this material should be rendered in alpha test mode
  34830. * @returns a boolean specifying if an alpha test is needed.
  34831. */
  34832. Material.prototype.needAlphaTesting = function () {
  34833. return false;
  34834. };
  34835. /**
  34836. * Gets the texture used for the alpha test
  34837. * @returns the texture to use for alpha testing
  34838. */
  34839. Material.prototype.getAlphaTestTexture = function () {
  34840. return null;
  34841. };
  34842. /**
  34843. * Marks the material to indicate that it needs to be re-calculated
  34844. */
  34845. Material.prototype.markDirty = function () {
  34846. this._wasPreviouslyReady = false;
  34847. };
  34848. /** @hidden */
  34849. Material.prototype._preBind = function (effect, overrideOrientation) {
  34850. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34851. var engine = this._scene.getEngine();
  34852. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34853. var reverse = orientation === Material.ClockWiseSideOrientation;
  34854. engine.enableEffect(effect ? effect : this._effect);
  34855. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34856. return reverse;
  34857. };
  34858. /**
  34859. * Binds the material to the mesh
  34860. * @param world defines the world transformation matrix
  34861. * @param mesh defines the mesh to bind the material to
  34862. */
  34863. Material.prototype.bind = function (world, mesh) {
  34864. };
  34865. /**
  34866. * Binds the submesh to the material
  34867. * @param world defines the world transformation matrix
  34868. * @param mesh defines the mesh containing the submesh
  34869. * @param subMesh defines the submesh to bind the material to
  34870. */
  34871. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34872. };
  34873. /**
  34874. * Binds the world matrix to the material
  34875. * @param world defines the world transformation matrix
  34876. */
  34877. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34878. };
  34879. /**
  34880. * Binds the scene's uniform buffer to the effect.
  34881. * @param effect defines the effect to bind to the scene uniform buffer
  34882. * @param sceneUbo defines the uniform buffer storing scene data
  34883. */
  34884. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34885. sceneUbo.bindToEffect(effect, "Scene");
  34886. };
  34887. /**
  34888. * Binds the view matrix to the effect
  34889. * @param effect defines the effect to bind the view matrix to
  34890. */
  34891. Material.prototype.bindView = function (effect) {
  34892. if (!this._useUBO) {
  34893. effect.setMatrix("view", this.getScene().getViewMatrix());
  34894. }
  34895. else {
  34896. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34897. }
  34898. };
  34899. /**
  34900. * Binds the view projection matrix to the effect
  34901. * @param effect defines the effect to bind the view projection matrix to
  34902. */
  34903. Material.prototype.bindViewProjection = function (effect) {
  34904. if (!this._useUBO) {
  34905. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34906. }
  34907. else {
  34908. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34909. }
  34910. };
  34911. /**
  34912. * Specifies if material alpha testing should be turned on for the mesh
  34913. * @param mesh defines the mesh to check
  34914. */
  34915. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34916. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34917. };
  34918. /**
  34919. * Processes to execute after binding the material to a mesh
  34920. * @param mesh defines the rendered mesh
  34921. */
  34922. Material.prototype._afterBind = function (mesh) {
  34923. this._scene._cachedMaterial = this;
  34924. if (mesh) {
  34925. this._scene._cachedVisibility = mesh.visibility;
  34926. }
  34927. else {
  34928. this._scene._cachedVisibility = 1;
  34929. }
  34930. if (this._onBindObservable && mesh) {
  34931. this._onBindObservable.notifyObservers(mesh);
  34932. }
  34933. if (this.disableDepthWrite) {
  34934. var engine = this._scene.getEngine();
  34935. this._cachedDepthWriteState = engine.getDepthWrite();
  34936. engine.setDepthWrite(false);
  34937. }
  34938. };
  34939. /**
  34940. * Unbinds the material from the mesh
  34941. */
  34942. Material.prototype.unbind = function () {
  34943. if (this._onUnBindObservable) {
  34944. this._onUnBindObservable.notifyObservers(this);
  34945. }
  34946. if (this.disableDepthWrite) {
  34947. var engine = this._scene.getEngine();
  34948. engine.setDepthWrite(this._cachedDepthWriteState);
  34949. }
  34950. };
  34951. /**
  34952. * Gets the active textures from the material
  34953. * @returns an array of textures
  34954. */
  34955. Material.prototype.getActiveTextures = function () {
  34956. return [];
  34957. };
  34958. /**
  34959. * Specifies if the material uses a texture
  34960. * @param texture defines the texture to check against the material
  34961. * @returns a boolean specifying if the material uses the texture
  34962. */
  34963. Material.prototype.hasTexture = function (texture) {
  34964. return false;
  34965. };
  34966. /**
  34967. * Makes a duplicate of the material, and gives it a new name
  34968. * @param name defines the new name for the duplicated material
  34969. * @returns the cloned material
  34970. */
  34971. Material.prototype.clone = function (name) {
  34972. return null;
  34973. };
  34974. /**
  34975. * Gets the meshes bound to the material
  34976. * @returns an array of meshes bound to the material
  34977. */
  34978. Material.prototype.getBindedMeshes = function () {
  34979. var result = new Array();
  34980. for (var index = 0; index < this._scene.meshes.length; index++) {
  34981. var mesh = this._scene.meshes[index];
  34982. if (mesh.material === this) {
  34983. result.push(mesh);
  34984. }
  34985. }
  34986. return result;
  34987. };
  34988. /**
  34989. * Force shader compilation
  34990. * @param mesh defines the mesh associated with this material
  34991. * @param onCompiled defines a function to execute once the material is compiled
  34992. * @param options defines the options to configure the compilation
  34993. */
  34994. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34995. var _this = this;
  34996. var localOptions = __assign({ clipPlane: false }, options);
  34997. var subMesh = new BABYLON.BaseSubMesh();
  34998. var scene = this.getScene();
  34999. var checkReady = function () {
  35000. if (!_this._scene || !_this._scene.getEngine()) {
  35001. return;
  35002. }
  35003. if (subMesh._materialDefines) {
  35004. subMesh._materialDefines._renderId = -1;
  35005. }
  35006. var clipPlaneState = scene.clipPlane;
  35007. if (localOptions.clipPlane) {
  35008. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35009. }
  35010. if (_this.storeEffectOnSubMeshes) {
  35011. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35012. if (onCompiled) {
  35013. onCompiled(_this);
  35014. }
  35015. }
  35016. else {
  35017. setTimeout(checkReady, 16);
  35018. }
  35019. }
  35020. else {
  35021. if (_this.isReady(mesh)) {
  35022. if (onCompiled) {
  35023. onCompiled(_this);
  35024. }
  35025. }
  35026. else {
  35027. setTimeout(checkReady, 16);
  35028. }
  35029. }
  35030. if (localOptions.clipPlane) {
  35031. scene.clipPlane = clipPlaneState;
  35032. }
  35033. };
  35034. checkReady();
  35035. };
  35036. /**
  35037. * Force shader compilation
  35038. * @param mesh defines the mesh that will use this material
  35039. * @param options defines additional options for compiling the shaders
  35040. * @returns a promise that resolves when the compilation completes
  35041. */
  35042. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35043. var _this = this;
  35044. return new Promise(function (resolve) {
  35045. _this.forceCompilation(mesh, function () {
  35046. resolve();
  35047. }, options);
  35048. });
  35049. };
  35050. /**
  35051. * Marks a define in the material to indicate that it needs to be re-computed
  35052. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35053. */
  35054. Material.prototype.markAsDirty = function (flag) {
  35055. if (flag & Material.TextureDirtyFlag) {
  35056. this._markAllSubMeshesAsTexturesDirty();
  35057. }
  35058. if (flag & Material.LightDirtyFlag) {
  35059. this._markAllSubMeshesAsLightsDirty();
  35060. }
  35061. if (flag & Material.FresnelDirtyFlag) {
  35062. this._markAllSubMeshesAsFresnelDirty();
  35063. }
  35064. if (flag & Material.AttributesDirtyFlag) {
  35065. this._markAllSubMeshesAsAttributesDirty();
  35066. }
  35067. if (flag & Material.MiscDirtyFlag) {
  35068. this._markAllSubMeshesAsMiscDirty();
  35069. }
  35070. this.getScene().resetCachedMaterial();
  35071. };
  35072. /**
  35073. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35074. * @param func defines a function which checks material defines against the submeshes
  35075. */
  35076. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35077. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35078. var mesh = _a[_i];
  35079. if (!mesh.subMeshes) {
  35080. continue;
  35081. }
  35082. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35083. var subMesh = _c[_b];
  35084. if (subMesh.getMaterial() !== this) {
  35085. continue;
  35086. }
  35087. if (!subMesh._materialDefines) {
  35088. continue;
  35089. }
  35090. func(subMesh._materialDefines);
  35091. }
  35092. }
  35093. };
  35094. /**
  35095. * Indicates that image processing needs to be re-calculated for all submeshes
  35096. */
  35097. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35098. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35099. };
  35100. /**
  35101. * Indicates that textures need to be re-calculated for all submeshes
  35102. */
  35103. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35104. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35105. };
  35106. /**
  35107. * Indicates that fresnel needs to be re-calculated for all submeshes
  35108. */
  35109. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35110. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35111. };
  35112. /**
  35113. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35114. */
  35115. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35116. this._markAllSubMeshesAsDirty(function (defines) {
  35117. defines.markAsFresnelDirty();
  35118. defines.markAsMiscDirty();
  35119. });
  35120. };
  35121. /**
  35122. * Indicates that lights need to be re-calculated for all submeshes
  35123. */
  35124. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35125. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35126. };
  35127. /**
  35128. * Indicates that attributes need to be re-calculated for all submeshes
  35129. */
  35130. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35131. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35132. };
  35133. /**
  35134. * Indicates that misc needs to be re-calculated for all submeshes
  35135. */
  35136. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35137. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35138. };
  35139. /**
  35140. * Indicates that textures and misc need to be re-calculated for all submeshes
  35141. */
  35142. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35143. this._markAllSubMeshesAsDirty(function (defines) {
  35144. defines.markAsTexturesDirty();
  35145. defines.markAsMiscDirty();
  35146. });
  35147. };
  35148. /**
  35149. * Disposes the material
  35150. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35151. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35152. */
  35153. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35154. // Animations
  35155. this.getScene().stopAnimation(this);
  35156. this.getScene().freeProcessedMaterials();
  35157. // Remove from scene
  35158. var index = this._scene.materials.indexOf(this);
  35159. if (index >= 0) {
  35160. this._scene.materials.splice(index, 1);
  35161. }
  35162. // Remove from meshes
  35163. for (index = 0; index < this._scene.meshes.length; index++) {
  35164. var mesh = this._scene.meshes[index];
  35165. if (mesh.material === this) {
  35166. mesh.material = null;
  35167. if (mesh.geometry) {
  35168. var geometry = (mesh.geometry);
  35169. if (this.storeEffectOnSubMeshes) {
  35170. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35171. var subMesh = _a[_i];
  35172. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35173. if (forceDisposeEffect && subMesh._materialEffect) {
  35174. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35175. }
  35176. }
  35177. }
  35178. else {
  35179. geometry._releaseVertexArrayObject(this._effect);
  35180. }
  35181. }
  35182. }
  35183. }
  35184. this._uniformBuffer.dispose();
  35185. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35186. if (forceDisposeEffect && this._effect) {
  35187. if (!this.storeEffectOnSubMeshes) {
  35188. this._scene.getEngine()._releaseEffect(this._effect);
  35189. }
  35190. this._effect = null;
  35191. }
  35192. // Callback
  35193. this.onDisposeObservable.notifyObservers(this);
  35194. this.onDisposeObservable.clear();
  35195. if (this._onBindObservable) {
  35196. this._onBindObservable.clear();
  35197. }
  35198. if (this._onUnBindObservable) {
  35199. this._onUnBindObservable.clear();
  35200. }
  35201. };
  35202. /**
  35203. * Serializes this material
  35204. * @returns the serialized material object
  35205. */
  35206. Material.prototype.serialize = function () {
  35207. return BABYLON.SerializationHelper.Serialize(this);
  35208. };
  35209. /**
  35210. * Creates a MultiMaterial from parsed MultiMaterial data.
  35211. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35212. * @param scene defines the hosting scene
  35213. * @returns a new MultiMaterial
  35214. */
  35215. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35216. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35217. multiMaterial.id = parsedMultiMaterial.id;
  35218. if (BABYLON.Tags) {
  35219. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35220. }
  35221. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35222. var subMatId = parsedMultiMaterial.materials[matIndex];
  35223. if (subMatId) {
  35224. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35225. }
  35226. else {
  35227. multiMaterial.subMaterials.push(null);
  35228. }
  35229. }
  35230. return multiMaterial;
  35231. };
  35232. /**
  35233. * Creates a material from parsed material data
  35234. * @param parsedMaterial defines parsed material data
  35235. * @param scene defines the hosting scene
  35236. * @param rootUrl defines the root URL to use to load textures
  35237. * @returns a new material
  35238. */
  35239. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35240. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35241. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35242. }
  35243. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35244. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35245. if (!BABYLON.LegacyPBRMaterial) {
  35246. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35247. return;
  35248. }
  35249. }
  35250. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35251. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35252. };
  35253. // Triangle views
  35254. Material._TriangleFillMode = 0;
  35255. Material._WireFrameFillMode = 1;
  35256. Material._PointFillMode = 2;
  35257. // Draw modes
  35258. Material._PointListDrawMode = 3;
  35259. Material._LineListDrawMode = 4;
  35260. Material._LineLoopDrawMode = 5;
  35261. Material._LineStripDrawMode = 6;
  35262. Material._TriangleStripDrawMode = 7;
  35263. Material._TriangleFanDrawMode = 8;
  35264. /**
  35265. * Stores the clock-wise side orientation
  35266. */
  35267. Material._ClockWiseSideOrientation = 0;
  35268. /**
  35269. * Stores the counter clock-wise side orientation
  35270. */
  35271. Material._CounterClockWiseSideOrientation = 1;
  35272. /**
  35273. * The dirty texture flag value
  35274. */
  35275. Material._TextureDirtyFlag = 1;
  35276. /**
  35277. * The dirty light flag value
  35278. */
  35279. Material._LightDirtyFlag = 2;
  35280. /**
  35281. * The dirty fresnel flag value
  35282. */
  35283. Material._FresnelDirtyFlag = 4;
  35284. /**
  35285. * The dirty attribute flag value
  35286. */
  35287. Material._AttributesDirtyFlag = 8;
  35288. /**
  35289. * The dirty misc flag value
  35290. */
  35291. Material._MiscDirtyFlag = 16;
  35292. __decorate([
  35293. BABYLON.serialize()
  35294. ], Material.prototype, "id", void 0);
  35295. __decorate([
  35296. BABYLON.serialize()
  35297. ], Material.prototype, "uniqueId", void 0);
  35298. __decorate([
  35299. BABYLON.serialize()
  35300. ], Material.prototype, "name", void 0);
  35301. __decorate([
  35302. BABYLON.serialize()
  35303. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35304. __decorate([
  35305. BABYLON.serialize()
  35306. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35307. __decorate([
  35308. BABYLON.serialize()
  35309. ], Material.prototype, "state", void 0);
  35310. __decorate([
  35311. BABYLON.serialize("alpha")
  35312. ], Material.prototype, "_alpha", void 0);
  35313. __decorate([
  35314. BABYLON.serialize("backFaceCulling")
  35315. ], Material.prototype, "_backFaceCulling", void 0);
  35316. __decorate([
  35317. BABYLON.serialize()
  35318. ], Material.prototype, "sideOrientation", void 0);
  35319. __decorate([
  35320. BABYLON.serialize("alphaMode")
  35321. ], Material.prototype, "_alphaMode", void 0);
  35322. __decorate([
  35323. BABYLON.serialize()
  35324. ], Material.prototype, "_needDepthPrePass", void 0);
  35325. __decorate([
  35326. BABYLON.serialize()
  35327. ], Material.prototype, "disableDepthWrite", void 0);
  35328. __decorate([
  35329. BABYLON.serialize()
  35330. ], Material.prototype, "forceDepthWrite", void 0);
  35331. __decorate([
  35332. BABYLON.serialize()
  35333. ], Material.prototype, "separateCullingPass", void 0);
  35334. __decorate([
  35335. BABYLON.serialize("fogEnabled")
  35336. ], Material.prototype, "_fogEnabled", void 0);
  35337. __decorate([
  35338. BABYLON.serialize()
  35339. ], Material.prototype, "pointSize", void 0);
  35340. __decorate([
  35341. BABYLON.serialize()
  35342. ], Material.prototype, "zOffset", void 0);
  35343. __decorate([
  35344. BABYLON.serialize()
  35345. ], Material.prototype, "wireframe", null);
  35346. __decorate([
  35347. BABYLON.serialize()
  35348. ], Material.prototype, "pointsCloud", null);
  35349. __decorate([
  35350. BABYLON.serialize()
  35351. ], Material.prototype, "fillMode", null);
  35352. return Material;
  35353. }());
  35354. BABYLON.Material = Material;
  35355. })(BABYLON || (BABYLON = {}));
  35356. //# sourceMappingURL=babylon.material.js.map
  35357. var BABYLON;
  35358. (function (BABYLON) {
  35359. var UniformBuffer = /** @class */ (function () {
  35360. /**
  35361. * Uniform buffer objects.
  35362. *
  35363. * Handles blocks of uniform on the GPU.
  35364. *
  35365. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35366. *
  35367. * For more information, please refer to :
  35368. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35369. */
  35370. function UniformBuffer(engine, data, dynamic) {
  35371. this._engine = engine;
  35372. this._noUBO = !engine.supportsUniformBuffers;
  35373. this._dynamic = dynamic;
  35374. this._data = data || [];
  35375. this._uniformLocations = {};
  35376. this._uniformSizes = {};
  35377. this._uniformLocationPointer = 0;
  35378. this._needSync = false;
  35379. if (this._noUBO) {
  35380. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35381. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35382. this.updateFloat = this._updateFloatForEffect;
  35383. this.updateFloat2 = this._updateFloat2ForEffect;
  35384. this.updateFloat3 = this._updateFloat3ForEffect;
  35385. this.updateFloat4 = this._updateFloat4ForEffect;
  35386. this.updateMatrix = this._updateMatrixForEffect;
  35387. this.updateVector3 = this._updateVector3ForEffect;
  35388. this.updateVector4 = this._updateVector4ForEffect;
  35389. this.updateColor3 = this._updateColor3ForEffect;
  35390. this.updateColor4 = this._updateColor4ForEffect;
  35391. }
  35392. else {
  35393. this._engine._uniformBuffers.push(this);
  35394. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35395. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35396. this.updateFloat = this._updateFloatForUniform;
  35397. this.updateFloat2 = this._updateFloat2ForUniform;
  35398. this.updateFloat3 = this._updateFloat3ForUniform;
  35399. this.updateFloat4 = this._updateFloat4ForUniform;
  35400. this.updateMatrix = this._updateMatrixForUniform;
  35401. this.updateVector3 = this._updateVector3ForUniform;
  35402. this.updateVector4 = this._updateVector4ForUniform;
  35403. this.updateColor3 = this._updateColor3ForUniform;
  35404. this.updateColor4 = this._updateColor4ForUniform;
  35405. }
  35406. }
  35407. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35408. // Properties
  35409. /**
  35410. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35411. * or just falling back on setUniformXXX calls.
  35412. */
  35413. get: function () {
  35414. return !this._noUBO;
  35415. },
  35416. enumerable: true,
  35417. configurable: true
  35418. });
  35419. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35420. /**
  35421. * Indicates if the WebGL underlying uniform buffer is in sync
  35422. * with the javascript cache data.
  35423. */
  35424. get: function () {
  35425. return !this._needSync;
  35426. },
  35427. enumerable: true,
  35428. configurable: true
  35429. });
  35430. /**
  35431. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35432. * Also, a dynamic UniformBuffer will disable cache verification and always
  35433. * update the underlying WebGL uniform buffer to the GPU.
  35434. */
  35435. UniformBuffer.prototype.isDynamic = function () {
  35436. return this._dynamic !== undefined;
  35437. };
  35438. /**
  35439. * The data cache on JS side.
  35440. */
  35441. UniformBuffer.prototype.getData = function () {
  35442. return this._bufferData;
  35443. };
  35444. /**
  35445. * The underlying WebGL Uniform buffer.
  35446. */
  35447. UniformBuffer.prototype.getBuffer = function () {
  35448. return this._buffer;
  35449. };
  35450. /**
  35451. * std140 layout specifies how to align data within an UBO structure.
  35452. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35453. * for specs.
  35454. */
  35455. UniformBuffer.prototype._fillAlignment = function (size) {
  35456. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35457. // and 4x4 matrices
  35458. // TODO : change if other types are used
  35459. var alignment;
  35460. if (size <= 2) {
  35461. alignment = size;
  35462. }
  35463. else {
  35464. alignment = 4;
  35465. }
  35466. if ((this._uniformLocationPointer % alignment) !== 0) {
  35467. var oldPointer = this._uniformLocationPointer;
  35468. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35469. var diff = this._uniformLocationPointer - oldPointer;
  35470. for (var i = 0; i < diff; i++) {
  35471. this._data.push(0);
  35472. }
  35473. }
  35474. };
  35475. /**
  35476. * Adds an uniform in the buffer.
  35477. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35478. * for the layout to be correct !
  35479. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35480. * @param {number|number[]} size Data size, or data directly.
  35481. */
  35482. UniformBuffer.prototype.addUniform = function (name, size) {
  35483. if (this._noUBO) {
  35484. return;
  35485. }
  35486. if (this._uniformLocations[name] !== undefined) {
  35487. // Already existing uniform
  35488. return;
  35489. }
  35490. // This function must be called in the order of the shader layout !
  35491. // size can be the size of the uniform, or data directly
  35492. var data;
  35493. if (size instanceof Array) {
  35494. data = size;
  35495. size = data.length;
  35496. }
  35497. else {
  35498. size = size;
  35499. data = [];
  35500. // Fill with zeros
  35501. for (var i = 0; i < size; i++) {
  35502. data.push(0);
  35503. }
  35504. }
  35505. this._fillAlignment(size);
  35506. this._uniformSizes[name] = size;
  35507. this._uniformLocations[name] = this._uniformLocationPointer;
  35508. this._uniformLocationPointer += size;
  35509. for (var i = 0; i < size; i++) {
  35510. this._data.push(data[i]);
  35511. }
  35512. this._needSync = true;
  35513. };
  35514. /**
  35515. * Wrapper for addUniform.
  35516. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35517. * @param {Matrix} mat A 4x4 matrix.
  35518. */
  35519. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35520. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35521. };
  35522. /**
  35523. * Wrapper for addUniform.
  35524. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35525. * @param {number} x
  35526. * @param {number} y
  35527. */
  35528. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35529. var temp = [x, y];
  35530. this.addUniform(name, temp);
  35531. };
  35532. /**
  35533. * Wrapper for addUniform.
  35534. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35535. * @param {number} x
  35536. * @param {number} y
  35537. * @param {number} z
  35538. */
  35539. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35540. var temp = [x, y, z];
  35541. this.addUniform(name, temp);
  35542. };
  35543. /**
  35544. * Wrapper for addUniform.
  35545. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35546. * @param {Color3} color
  35547. */
  35548. UniformBuffer.prototype.addColor3 = function (name, color) {
  35549. var temp = new Array();
  35550. color.toArray(temp);
  35551. this.addUniform(name, temp);
  35552. };
  35553. /**
  35554. * Wrapper for addUniform.
  35555. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35556. * @param {Color3} color
  35557. * @param {number} alpha
  35558. */
  35559. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35560. var temp = new Array();
  35561. color.toArray(temp);
  35562. temp.push(alpha);
  35563. this.addUniform(name, temp);
  35564. };
  35565. /**
  35566. * Wrapper for addUniform.
  35567. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35568. * @param {Vector3} vector
  35569. */
  35570. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35571. var temp = new Array();
  35572. vector.toArray(temp);
  35573. this.addUniform(name, temp);
  35574. };
  35575. /**
  35576. * Wrapper for addUniform.
  35577. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35578. */
  35579. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35580. this.addUniform(name, 12);
  35581. };
  35582. /**
  35583. * Wrapper for addUniform.
  35584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35585. */
  35586. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35587. this.addUniform(name, 8);
  35588. };
  35589. /**
  35590. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35591. */
  35592. UniformBuffer.prototype.create = function () {
  35593. if (this._noUBO) {
  35594. return;
  35595. }
  35596. if (this._buffer) {
  35597. return; // nothing to do
  35598. }
  35599. // See spec, alignment must be filled as a vec4
  35600. this._fillAlignment(4);
  35601. this._bufferData = new Float32Array(this._data);
  35602. this._rebuild();
  35603. this._needSync = true;
  35604. };
  35605. /** @hidden */
  35606. UniformBuffer.prototype._rebuild = function () {
  35607. if (this._noUBO) {
  35608. return;
  35609. }
  35610. if (this._dynamic) {
  35611. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35612. }
  35613. else {
  35614. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35615. }
  35616. };
  35617. /**
  35618. * Updates the WebGL Uniform Buffer on the GPU.
  35619. * If the `dynamic` flag is set to true, no cache comparison is done.
  35620. * Otherwise, the buffer will be updated only if the cache differs.
  35621. */
  35622. UniformBuffer.prototype.update = function () {
  35623. if (!this._buffer) {
  35624. this.create();
  35625. return;
  35626. }
  35627. if (!this._dynamic && !this._needSync) {
  35628. return;
  35629. }
  35630. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35631. this._needSync = false;
  35632. };
  35633. /**
  35634. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35635. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35636. * @param {number[]|Float32Array} data Flattened data
  35637. * @param {number} size Size of the data.
  35638. */
  35639. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35640. var location = this._uniformLocations[uniformName];
  35641. if (location === undefined) {
  35642. if (this._buffer) {
  35643. // Cannot add an uniform if the buffer is already created
  35644. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35645. return;
  35646. }
  35647. this.addUniform(uniformName, size);
  35648. location = this._uniformLocations[uniformName];
  35649. }
  35650. if (!this._buffer) {
  35651. this.create();
  35652. }
  35653. if (!this._dynamic) {
  35654. // Cache for static uniform buffers
  35655. var changed = false;
  35656. for (var i = 0; i < size; i++) {
  35657. if (this._bufferData[location + i] !== data[i]) {
  35658. changed = true;
  35659. this._bufferData[location + i] = data[i];
  35660. }
  35661. }
  35662. this._needSync = this._needSync || changed;
  35663. }
  35664. else {
  35665. // No cache for dynamic
  35666. for (var i = 0; i < size; i++) {
  35667. this._bufferData[location + i] = data[i];
  35668. }
  35669. }
  35670. };
  35671. // Update methods
  35672. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35673. // To match std140, matrix must be realigned
  35674. for (var i = 0; i < 3; i++) {
  35675. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35676. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35677. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35678. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35679. }
  35680. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35681. };
  35682. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35683. this._currentEffect.setMatrix3x3(name, matrix);
  35684. };
  35685. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35686. this._currentEffect.setMatrix2x2(name, matrix);
  35687. };
  35688. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35689. // To match std140, matrix must be realigned
  35690. for (var i = 0; i < 2; i++) {
  35691. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35692. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35693. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35694. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35695. }
  35696. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35697. };
  35698. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35699. this._currentEffect.setFloat(name, x);
  35700. };
  35701. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35702. UniformBuffer._tempBuffer[0] = x;
  35703. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35704. };
  35705. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35706. if (suffix === void 0) { suffix = ""; }
  35707. this._currentEffect.setFloat2(name + suffix, x, y);
  35708. };
  35709. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35710. if (suffix === void 0) { suffix = ""; }
  35711. UniformBuffer._tempBuffer[0] = x;
  35712. UniformBuffer._tempBuffer[1] = y;
  35713. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35714. };
  35715. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35716. if (suffix === void 0) { suffix = ""; }
  35717. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35718. };
  35719. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35720. if (suffix === void 0) { suffix = ""; }
  35721. UniformBuffer._tempBuffer[0] = x;
  35722. UniformBuffer._tempBuffer[1] = y;
  35723. UniformBuffer._tempBuffer[2] = z;
  35724. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35725. };
  35726. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35727. if (suffix === void 0) { suffix = ""; }
  35728. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35729. };
  35730. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35731. if (suffix === void 0) { suffix = ""; }
  35732. UniformBuffer._tempBuffer[0] = x;
  35733. UniformBuffer._tempBuffer[1] = y;
  35734. UniformBuffer._tempBuffer[2] = z;
  35735. UniformBuffer._tempBuffer[3] = w;
  35736. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35737. };
  35738. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35739. this._currentEffect.setMatrix(name, mat);
  35740. };
  35741. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35742. this.updateUniform(name, mat.toArray(), 16);
  35743. };
  35744. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35745. this._currentEffect.setVector3(name, vector);
  35746. };
  35747. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35748. vector.toArray(UniformBuffer._tempBuffer);
  35749. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35750. };
  35751. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35752. this._currentEffect.setVector4(name, vector);
  35753. };
  35754. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35755. vector.toArray(UniformBuffer._tempBuffer);
  35756. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35757. };
  35758. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35759. if (suffix === void 0) { suffix = ""; }
  35760. this._currentEffect.setColor3(name + suffix, color);
  35761. };
  35762. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35763. if (suffix === void 0) { suffix = ""; }
  35764. color.toArray(UniformBuffer._tempBuffer);
  35765. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35766. };
  35767. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35768. if (suffix === void 0) { suffix = ""; }
  35769. this._currentEffect.setColor4(name + suffix, color, alpha);
  35770. };
  35771. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35772. if (suffix === void 0) { suffix = ""; }
  35773. color.toArray(UniformBuffer._tempBuffer);
  35774. UniformBuffer._tempBuffer[3] = alpha;
  35775. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35776. };
  35777. /**
  35778. * Sets a sampler uniform on the effect.
  35779. * @param {string} name Name of the sampler.
  35780. * @param {Texture} texture
  35781. */
  35782. UniformBuffer.prototype.setTexture = function (name, texture) {
  35783. this._currentEffect.setTexture(name, texture);
  35784. };
  35785. /**
  35786. * Directly updates the value of the uniform in the cache AND on the GPU.
  35787. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35788. * @param {number[]|Float32Array} data Flattened data
  35789. */
  35790. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35791. this.updateUniform(uniformName, data, data.length);
  35792. this.update();
  35793. };
  35794. /**
  35795. * Binds this uniform buffer to an effect.
  35796. * @param {Effect} effect
  35797. * @param {string} name Name of the uniform block in the shader.
  35798. */
  35799. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35800. this._currentEffect = effect;
  35801. if (this._noUBO || !this._buffer) {
  35802. return;
  35803. }
  35804. effect.bindUniformBuffer(this._buffer, name);
  35805. };
  35806. /**
  35807. * Disposes the uniform buffer.
  35808. */
  35809. UniformBuffer.prototype.dispose = function () {
  35810. if (this._noUBO) {
  35811. return;
  35812. }
  35813. var index = this._engine._uniformBuffers.indexOf(this);
  35814. if (index !== -1) {
  35815. this._engine._uniformBuffers.splice(index, 1);
  35816. }
  35817. if (!this._buffer) {
  35818. return;
  35819. }
  35820. if (this._engine._releaseBuffer(this._buffer)) {
  35821. this._buffer = null;
  35822. }
  35823. };
  35824. // Pool for avoiding memory leaks
  35825. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35826. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35827. return UniformBuffer;
  35828. }());
  35829. BABYLON.UniformBuffer = UniformBuffer;
  35830. })(BABYLON || (BABYLON = {}));
  35831. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35832. var BABYLON;
  35833. (function (BABYLON) {
  35834. /**
  35835. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35836. */
  35837. var VertexData = /** @class */ (function () {
  35838. function VertexData() {
  35839. }
  35840. /**
  35841. * Uses the passed data array to set the set the values for the specified kind of data
  35842. * @param data a linear array of floating numbers
  35843. * @param kind the type of data that is being set, eg positions, colors etc
  35844. */
  35845. VertexData.prototype.set = function (data, kind) {
  35846. switch (kind) {
  35847. case BABYLON.VertexBuffer.PositionKind:
  35848. this.positions = data;
  35849. break;
  35850. case BABYLON.VertexBuffer.NormalKind:
  35851. this.normals = data;
  35852. break;
  35853. case BABYLON.VertexBuffer.TangentKind:
  35854. this.tangents = data;
  35855. break;
  35856. case BABYLON.VertexBuffer.UVKind:
  35857. this.uvs = data;
  35858. break;
  35859. case BABYLON.VertexBuffer.UV2Kind:
  35860. this.uvs2 = data;
  35861. break;
  35862. case BABYLON.VertexBuffer.UV3Kind:
  35863. this.uvs3 = data;
  35864. break;
  35865. case BABYLON.VertexBuffer.UV4Kind:
  35866. this.uvs4 = data;
  35867. break;
  35868. case BABYLON.VertexBuffer.UV5Kind:
  35869. this.uvs5 = data;
  35870. break;
  35871. case BABYLON.VertexBuffer.UV6Kind:
  35872. this.uvs6 = data;
  35873. break;
  35874. case BABYLON.VertexBuffer.ColorKind:
  35875. this.colors = data;
  35876. break;
  35877. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35878. this.matricesIndices = data;
  35879. break;
  35880. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35881. this.matricesWeights = data;
  35882. break;
  35883. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35884. this.matricesIndicesExtra = data;
  35885. break;
  35886. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35887. this.matricesWeightsExtra = data;
  35888. break;
  35889. }
  35890. };
  35891. /**
  35892. * Associates the vertexData to the passed Mesh.
  35893. * Sets it as updatable or not (default `false`)
  35894. * @param mesh the mesh the vertexData is applied to
  35895. * @param updatable when used and having the value true allows new data to update the vertexData
  35896. * @returns the VertexData
  35897. */
  35898. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35899. this._applyTo(mesh, updatable);
  35900. return this;
  35901. };
  35902. /**
  35903. * Associates the vertexData to the passed Geometry.
  35904. * Sets it as updatable or not (default `false`)
  35905. * @param geometry the geometry the vertexData is applied to
  35906. * @param updatable when used and having the value true allows new data to update the vertexData
  35907. * @returns VertexData
  35908. */
  35909. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35910. this._applyTo(geometry, updatable);
  35911. return this;
  35912. };
  35913. /**
  35914. * Updates the associated mesh
  35915. * @param mesh the mesh to be updated
  35916. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35917. * @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
  35918. * @returns VertexData
  35919. */
  35920. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35921. this._update(mesh);
  35922. return this;
  35923. };
  35924. /**
  35925. * Updates the associated geometry
  35926. * @param geometry the geometry to be updated
  35927. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35928. * @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
  35929. * @returns VertexData.
  35930. */
  35931. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35932. this._update(geometry);
  35933. return this;
  35934. };
  35935. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35936. if (updatable === void 0) { updatable = false; }
  35937. if (this.positions) {
  35938. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35939. }
  35940. if (this.normals) {
  35941. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35942. }
  35943. if (this.tangents) {
  35944. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35945. }
  35946. if (this.uvs) {
  35947. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35948. }
  35949. if (this.uvs2) {
  35950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35951. }
  35952. if (this.uvs3) {
  35953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35954. }
  35955. if (this.uvs4) {
  35956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35957. }
  35958. if (this.uvs5) {
  35959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35960. }
  35961. if (this.uvs6) {
  35962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35963. }
  35964. if (this.colors) {
  35965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35966. }
  35967. if (this.matricesIndices) {
  35968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35969. }
  35970. if (this.matricesWeights) {
  35971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35972. }
  35973. if (this.matricesIndicesExtra) {
  35974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35975. }
  35976. if (this.matricesWeightsExtra) {
  35977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35978. }
  35979. if (this.indices) {
  35980. meshOrGeometry.setIndices(this.indices, null, updatable);
  35981. }
  35982. else {
  35983. meshOrGeometry.setIndices([], null);
  35984. }
  35985. return this;
  35986. };
  35987. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35988. if (this.positions) {
  35989. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35990. }
  35991. if (this.normals) {
  35992. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35993. }
  35994. if (this.tangents) {
  35995. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35996. }
  35997. if (this.uvs) {
  35998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35999. }
  36000. if (this.uvs2) {
  36001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36002. }
  36003. if (this.uvs3) {
  36004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36005. }
  36006. if (this.uvs4) {
  36007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36008. }
  36009. if (this.uvs5) {
  36010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36011. }
  36012. if (this.uvs6) {
  36013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36014. }
  36015. if (this.colors) {
  36016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36017. }
  36018. if (this.matricesIndices) {
  36019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36020. }
  36021. if (this.matricesWeights) {
  36022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36023. }
  36024. if (this.matricesIndicesExtra) {
  36025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36026. }
  36027. if (this.matricesWeightsExtra) {
  36028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36029. }
  36030. if (this.indices) {
  36031. meshOrGeometry.setIndices(this.indices, null);
  36032. }
  36033. return this;
  36034. };
  36035. /**
  36036. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36037. * @param matrix the transforming matrix
  36038. * @returns the VertexData
  36039. */
  36040. VertexData.prototype.transform = function (matrix) {
  36041. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36042. var transformed = BABYLON.Vector3.Zero();
  36043. var index;
  36044. if (this.positions) {
  36045. var position = BABYLON.Vector3.Zero();
  36046. for (index = 0; index < this.positions.length; index += 3) {
  36047. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36048. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36049. this.positions[index] = transformed.x;
  36050. this.positions[index + 1] = transformed.y;
  36051. this.positions[index + 2] = transformed.z;
  36052. }
  36053. }
  36054. if (this.normals) {
  36055. var normal = BABYLON.Vector3.Zero();
  36056. for (index = 0; index < this.normals.length; index += 3) {
  36057. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36058. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36059. this.normals[index] = transformed.x;
  36060. this.normals[index + 1] = transformed.y;
  36061. this.normals[index + 2] = transformed.z;
  36062. }
  36063. }
  36064. if (this.tangents) {
  36065. var tangent = BABYLON.Vector4.Zero();
  36066. var tangentTransformed = BABYLON.Vector4.Zero();
  36067. for (index = 0; index < this.tangents.length; index += 4) {
  36068. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36069. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36070. this.tangents[index] = tangentTransformed.x;
  36071. this.tangents[index + 1] = tangentTransformed.y;
  36072. this.tangents[index + 2] = tangentTransformed.z;
  36073. this.tangents[index + 3] = tangentTransformed.w;
  36074. }
  36075. }
  36076. if (flip && this.indices) {
  36077. for (index = 0; index < this.indices.length; index += 3) {
  36078. var tmp = this.indices[index + 1];
  36079. this.indices[index + 1] = this.indices[index + 2];
  36080. this.indices[index + 2] = tmp;
  36081. }
  36082. }
  36083. return this;
  36084. };
  36085. /**
  36086. * Merges the passed VertexData into the current one
  36087. * @param other the VertexData to be merged into the current one
  36088. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36089. * @returns the modified VertexData
  36090. */
  36091. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36092. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36093. this._validate();
  36094. other._validate();
  36095. if (!this.normals !== !other.normals ||
  36096. !this.tangents !== !other.tangents ||
  36097. !this.uvs !== !other.uvs ||
  36098. !this.uvs2 !== !other.uvs2 ||
  36099. !this.uvs3 !== !other.uvs3 ||
  36100. !this.uvs4 !== !other.uvs4 ||
  36101. !this.uvs5 !== !other.uvs5 ||
  36102. !this.uvs6 !== !other.uvs6 ||
  36103. !this.colors !== !other.colors ||
  36104. !this.matricesIndices !== !other.matricesIndices ||
  36105. !this.matricesWeights !== !other.matricesWeights ||
  36106. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36107. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36108. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36109. }
  36110. if (other.indices) {
  36111. if (!this.indices) {
  36112. this.indices = [];
  36113. }
  36114. var offset = this.positions ? this.positions.length / 3 : 0;
  36115. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36116. if (isSrcTypedArray) {
  36117. var len = this.indices.length + other.indices.length;
  36118. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36119. temp.set(this.indices);
  36120. var decal = this.indices.length;
  36121. for (var index = 0; index < other.indices.length; index++) {
  36122. temp[decal + index] = other.indices[index] + offset;
  36123. }
  36124. this.indices = temp;
  36125. }
  36126. else {
  36127. for (var index = 0; index < other.indices.length; index++) {
  36128. this.indices.push(other.indices[index] + offset);
  36129. }
  36130. }
  36131. }
  36132. this.positions = this._mergeElement(this.positions, other.positions);
  36133. this.normals = this._mergeElement(this.normals, other.normals);
  36134. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36135. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36136. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36137. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36138. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36139. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36140. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36141. this.colors = this._mergeElement(this.colors, other.colors);
  36142. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36143. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36144. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36145. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36146. return this;
  36147. };
  36148. VertexData.prototype._mergeElement = function (source, other) {
  36149. if (!source) {
  36150. return other;
  36151. }
  36152. if (!other) {
  36153. return source;
  36154. }
  36155. var len = other.length + source.length;
  36156. var isSrcTypedArray = source instanceof Float32Array;
  36157. var isOthTypedArray = other instanceof Float32Array;
  36158. // use non-loop method when the source is Float32Array
  36159. if (isSrcTypedArray) {
  36160. var ret32 = new Float32Array(len);
  36161. ret32.set(source);
  36162. ret32.set(other, source.length);
  36163. return ret32;
  36164. // source is number[], when other is also use concat
  36165. }
  36166. else if (!isOthTypedArray) {
  36167. return source.concat(other);
  36168. // source is a number[], but other is a Float32Array, loop required
  36169. }
  36170. else {
  36171. var ret = source.slice(0); // copy source to a separate array
  36172. for (var i = 0, len = other.length; i < len; i++) {
  36173. ret.push(other[i]);
  36174. }
  36175. return ret;
  36176. }
  36177. };
  36178. VertexData.prototype._validate = function () {
  36179. if (!this.positions) {
  36180. throw new Error("Positions are required");
  36181. }
  36182. var getElementCount = function (kind, values) {
  36183. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36184. if ((values.length % stride) !== 0) {
  36185. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36186. }
  36187. return values.length / stride;
  36188. };
  36189. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36190. var validateElementCount = function (kind, values) {
  36191. var elementCount = getElementCount(kind, values);
  36192. if (elementCount !== positionsElementCount) {
  36193. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36194. }
  36195. };
  36196. if (this.normals)
  36197. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36198. if (this.tangents)
  36199. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36200. if (this.uvs)
  36201. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36202. if (this.uvs2)
  36203. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36204. if (this.uvs3)
  36205. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36206. if (this.uvs4)
  36207. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36208. if (this.uvs5)
  36209. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36210. if (this.uvs6)
  36211. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36212. if (this.colors)
  36213. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36214. if (this.matricesIndices)
  36215. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36216. if (this.matricesWeights)
  36217. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36218. if (this.matricesIndicesExtra)
  36219. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36220. if (this.matricesWeightsExtra)
  36221. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36222. };
  36223. /**
  36224. * Serializes the VertexData
  36225. * @returns a serialized object
  36226. */
  36227. VertexData.prototype.serialize = function () {
  36228. var serializationObject = this.serialize();
  36229. if (this.positions) {
  36230. serializationObject.positions = this.positions;
  36231. }
  36232. if (this.normals) {
  36233. serializationObject.normals = this.normals;
  36234. }
  36235. if (this.tangents) {
  36236. serializationObject.tangents = this.tangents;
  36237. }
  36238. if (this.uvs) {
  36239. serializationObject.uvs = this.uvs;
  36240. }
  36241. if (this.uvs2) {
  36242. serializationObject.uvs2 = this.uvs2;
  36243. }
  36244. if (this.uvs3) {
  36245. serializationObject.uvs3 = this.uvs3;
  36246. }
  36247. if (this.uvs4) {
  36248. serializationObject.uvs4 = this.uvs4;
  36249. }
  36250. if (this.uvs5) {
  36251. serializationObject.uvs5 = this.uvs5;
  36252. }
  36253. if (this.uvs6) {
  36254. serializationObject.uvs6 = this.uvs6;
  36255. }
  36256. if (this.colors) {
  36257. serializationObject.colors = this.colors;
  36258. }
  36259. if (this.matricesIndices) {
  36260. serializationObject.matricesIndices = this.matricesIndices;
  36261. serializationObject.matricesIndices._isExpanded = true;
  36262. }
  36263. if (this.matricesWeights) {
  36264. serializationObject.matricesWeights = this.matricesWeights;
  36265. }
  36266. if (this.matricesIndicesExtra) {
  36267. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36268. serializationObject.matricesIndicesExtra._isExpanded = true;
  36269. }
  36270. if (this.matricesWeightsExtra) {
  36271. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36272. }
  36273. serializationObject.indices = this.indices;
  36274. return serializationObject;
  36275. };
  36276. // Statics
  36277. /**
  36278. * Extracts the vertexData from a mesh
  36279. * @param mesh the mesh from which to extract the VertexData
  36280. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36281. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36282. * @returns the object VertexData associated to the passed mesh
  36283. */
  36284. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36285. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36286. };
  36287. /**
  36288. * Extracts the vertexData from the geometry
  36289. * @param geometry the geometry from which to extract the VertexData
  36290. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36291. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36292. * @returns the object VertexData associated to the passed mesh
  36293. */
  36294. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36295. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36296. };
  36297. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36298. var result = new VertexData();
  36299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36300. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36301. }
  36302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36303. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36304. }
  36305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36306. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36307. }
  36308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36309. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36310. }
  36311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36312. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36313. }
  36314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36315. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36316. }
  36317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36318. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36319. }
  36320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36321. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36322. }
  36323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36324. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36325. }
  36326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36327. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36328. }
  36329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36330. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36331. }
  36332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36333. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36334. }
  36335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36336. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36337. }
  36338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36339. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36340. }
  36341. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36342. return result;
  36343. };
  36344. /**
  36345. * Creates the VertexData for a Ribbon
  36346. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36347. * * pathArray array of paths, each of which an array of successive Vector3
  36348. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36349. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36350. * * 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
  36351. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36352. * * 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)
  36353. * * 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)
  36354. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36355. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36356. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36357. * @returns the VertexData of the ribbon
  36358. */
  36359. VertexData.CreateRibbon = function (options) {
  36360. var pathArray = options.pathArray;
  36361. var closeArray = options.closeArray || false;
  36362. var closePath = options.closePath || false;
  36363. var invertUV = options.invertUV || false;
  36364. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36365. var offset = options.offset || defaultOffset;
  36366. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36368. var customUV = options.uvs;
  36369. var customColors = options.colors;
  36370. var positions = [];
  36371. var indices = [];
  36372. var normals = [];
  36373. var uvs = [];
  36374. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36375. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36376. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36377. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36378. var minlg; // minimal length among all paths from pathArray
  36379. var lg = []; // array of path lengths : nb of vertex per path
  36380. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36381. var p; // path iterator
  36382. var i; // point iterator
  36383. var j; // point iterator
  36384. // if single path in pathArray
  36385. if (pathArray.length < 2) {
  36386. var ar1 = [];
  36387. var ar2 = [];
  36388. for (i = 0; i < pathArray[0].length - offset; i++) {
  36389. ar1.push(pathArray[0][i]);
  36390. ar2.push(pathArray[0][i + offset]);
  36391. }
  36392. pathArray = [ar1, ar2];
  36393. }
  36394. // positions and horizontal distances (u)
  36395. var idc = 0;
  36396. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36397. var path;
  36398. var l;
  36399. minlg = pathArray[0].length;
  36400. var vectlg;
  36401. var dist;
  36402. for (p = 0; p < pathArray.length; p++) {
  36403. uTotalDistance[p] = 0;
  36404. us[p] = [0];
  36405. path = pathArray[p];
  36406. l = path.length;
  36407. minlg = (minlg < l) ? minlg : l;
  36408. j = 0;
  36409. while (j < l) {
  36410. positions.push(path[j].x, path[j].y, path[j].z);
  36411. if (j > 0) {
  36412. vectlg = path[j].subtract(path[j - 1]).length();
  36413. dist = vectlg + uTotalDistance[p];
  36414. us[p].push(dist);
  36415. uTotalDistance[p] = dist;
  36416. }
  36417. j++;
  36418. }
  36419. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36420. j--;
  36421. positions.push(path[0].x, path[0].y, path[0].z);
  36422. vectlg = path[j].subtract(path[0]).length();
  36423. dist = vectlg + uTotalDistance[p];
  36424. us[p].push(dist);
  36425. uTotalDistance[p] = dist;
  36426. }
  36427. lg[p] = l + closePathCorr;
  36428. idx[p] = idc;
  36429. idc += (l + closePathCorr);
  36430. }
  36431. // vertical distances (v)
  36432. var path1;
  36433. var path2;
  36434. var vertex1 = null;
  36435. var vertex2 = null;
  36436. for (i = 0; i < minlg + closePathCorr; i++) {
  36437. vTotalDistance[i] = 0;
  36438. vs[i] = [0];
  36439. for (p = 0; p < pathArray.length - 1; p++) {
  36440. path1 = pathArray[p];
  36441. path2 = pathArray[p + 1];
  36442. if (i === minlg) { // closePath
  36443. vertex1 = path1[0];
  36444. vertex2 = path2[0];
  36445. }
  36446. else {
  36447. vertex1 = path1[i];
  36448. vertex2 = path2[i];
  36449. }
  36450. vectlg = vertex2.subtract(vertex1).length();
  36451. dist = vectlg + vTotalDistance[i];
  36452. vs[i].push(dist);
  36453. vTotalDistance[i] = dist;
  36454. }
  36455. if (closeArray && vertex2 && vertex1) {
  36456. path1 = pathArray[p];
  36457. path2 = pathArray[0];
  36458. if (i === minlg) { // closePath
  36459. vertex2 = path2[0];
  36460. }
  36461. vectlg = vertex2.subtract(vertex1).length();
  36462. dist = vectlg + vTotalDistance[i];
  36463. vTotalDistance[i] = dist;
  36464. }
  36465. }
  36466. // uvs
  36467. var u;
  36468. var v;
  36469. if (customUV) {
  36470. for (p = 0; p < customUV.length; p++) {
  36471. uvs.push(customUV[p].x, customUV[p].y);
  36472. }
  36473. }
  36474. else {
  36475. for (p = 0; p < pathArray.length; p++) {
  36476. for (i = 0; i < minlg + closePathCorr; i++) {
  36477. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36478. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36479. if (invertUV) {
  36480. uvs.push(v, u);
  36481. }
  36482. else {
  36483. uvs.push(u, v);
  36484. }
  36485. }
  36486. }
  36487. }
  36488. // indices
  36489. p = 0; // path index
  36490. var pi = 0; // positions array index
  36491. var l1 = lg[p] - 1; // path1 length
  36492. var l2 = lg[p + 1] - 1; // path2 length
  36493. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36494. var shft = idx[1] - idx[0]; // shift
  36495. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36496. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36497. // 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
  36498. indices.push(pi, pi + shft, pi + 1);
  36499. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36500. pi += 1;
  36501. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36502. p++;
  36503. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36504. shft = idx[0] - idx[p];
  36505. l1 = lg[p] - 1;
  36506. l2 = lg[0] - 1;
  36507. }
  36508. else {
  36509. shft = idx[p + 1] - idx[p];
  36510. l1 = lg[p] - 1;
  36511. l2 = lg[p + 1] - 1;
  36512. }
  36513. pi = idx[p];
  36514. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36515. }
  36516. }
  36517. // normals
  36518. VertexData.ComputeNormals(positions, indices, normals);
  36519. if (closePath) { // update both the first and last vertex normals to their average value
  36520. var indexFirst = 0;
  36521. var indexLast = 0;
  36522. for (p = 0; p < pathArray.length; p++) {
  36523. indexFirst = idx[p] * 3;
  36524. if (p + 1 < pathArray.length) {
  36525. indexLast = (idx[p + 1] - 1) * 3;
  36526. }
  36527. else {
  36528. indexLast = normals.length - 3;
  36529. }
  36530. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36531. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36532. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36533. normals[indexLast] = normals[indexFirst];
  36534. normals[indexLast + 1] = normals[indexFirst + 1];
  36535. normals[indexLast + 2] = normals[indexFirst + 2];
  36536. }
  36537. }
  36538. // sides
  36539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36540. // Colors
  36541. var colors = null;
  36542. if (customColors) {
  36543. colors = new Float32Array(customColors.length * 4);
  36544. for (var c = 0; c < customColors.length; c++) {
  36545. colors[c * 4] = customColors[c].r;
  36546. colors[c * 4 + 1] = customColors[c].g;
  36547. colors[c * 4 + 2] = customColors[c].b;
  36548. colors[c * 4 + 3] = customColors[c].a;
  36549. }
  36550. }
  36551. // Result
  36552. var vertexData = new VertexData();
  36553. var positions32 = new Float32Array(positions);
  36554. var normals32 = new Float32Array(normals);
  36555. var uvs32 = new Float32Array(uvs);
  36556. vertexData.indices = indices;
  36557. vertexData.positions = positions32;
  36558. vertexData.normals = normals32;
  36559. vertexData.uvs = uvs32;
  36560. if (colors) {
  36561. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36562. }
  36563. if (closePath) {
  36564. vertexData._idx = idx;
  36565. }
  36566. return vertexData;
  36567. };
  36568. /**
  36569. * Creates the VertexData for a box
  36570. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36571. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36572. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36573. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36574. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36575. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36576. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36577. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36578. * * 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)
  36579. * * 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)
  36580. * @returns the VertexData of the box
  36581. */
  36582. VertexData.CreateBox = function (options) {
  36583. var normalsSource = [
  36584. new BABYLON.Vector3(0, 0, 1),
  36585. new BABYLON.Vector3(0, 0, -1),
  36586. new BABYLON.Vector3(1, 0, 0),
  36587. new BABYLON.Vector3(-1, 0, 0),
  36588. new BABYLON.Vector3(0, 1, 0),
  36589. new BABYLON.Vector3(0, -1, 0)
  36590. ];
  36591. var indices = [];
  36592. var positions = [];
  36593. var normals = [];
  36594. var uvs = [];
  36595. var width = options.width || options.size || 1;
  36596. var height = options.height || options.size || 1;
  36597. var depth = options.depth || options.size || 1;
  36598. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36599. var faceUV = options.faceUV || new Array(6);
  36600. var faceColors = options.faceColors;
  36601. var colors = [];
  36602. // default face colors and UV if undefined
  36603. for (var f = 0; f < 6; f++) {
  36604. if (faceUV[f] === undefined) {
  36605. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36606. }
  36607. if (faceColors && faceColors[f] === undefined) {
  36608. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36609. }
  36610. }
  36611. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36612. // Create each face in turn.
  36613. for (var index = 0; index < normalsSource.length; index++) {
  36614. var normal = normalsSource[index];
  36615. // Get two vectors perpendicular to the face normal and to each other.
  36616. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36617. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36618. // Six indices (two triangles) per face.
  36619. var verticesLength = positions.length / 3;
  36620. indices.push(verticesLength);
  36621. indices.push(verticesLength + 1);
  36622. indices.push(verticesLength + 2);
  36623. indices.push(verticesLength);
  36624. indices.push(verticesLength + 2);
  36625. indices.push(verticesLength + 3);
  36626. // Four vertices per face.
  36627. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36628. positions.push(vertex.x, vertex.y, vertex.z);
  36629. normals.push(normal.x, normal.y, normal.z);
  36630. uvs.push(faceUV[index].z, faceUV[index].w);
  36631. if (faceColors) {
  36632. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36633. }
  36634. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36635. positions.push(vertex.x, vertex.y, vertex.z);
  36636. normals.push(normal.x, normal.y, normal.z);
  36637. uvs.push(faceUV[index].x, faceUV[index].w);
  36638. if (faceColors) {
  36639. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36640. }
  36641. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36642. positions.push(vertex.x, vertex.y, vertex.z);
  36643. normals.push(normal.x, normal.y, normal.z);
  36644. uvs.push(faceUV[index].x, faceUV[index].y);
  36645. if (faceColors) {
  36646. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36647. }
  36648. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36649. positions.push(vertex.x, vertex.y, vertex.z);
  36650. normals.push(normal.x, normal.y, normal.z);
  36651. uvs.push(faceUV[index].z, faceUV[index].y);
  36652. if (faceColors) {
  36653. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36654. }
  36655. }
  36656. // sides
  36657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36658. // Result
  36659. var vertexData = new VertexData();
  36660. vertexData.indices = indices;
  36661. vertexData.positions = positions;
  36662. vertexData.normals = normals;
  36663. vertexData.uvs = uvs;
  36664. if (faceColors) {
  36665. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36666. vertexData.colors = totalColors;
  36667. }
  36668. return vertexData;
  36669. };
  36670. /**
  36671. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36672. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36673. * * segments sets the number of horizontal strips optional, default 32
  36674. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36675. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36676. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36677. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36678. * * 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
  36679. * * 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
  36680. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36681. * * 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)
  36682. * * 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)
  36683. * @returns the VertexData of the ellipsoid
  36684. */
  36685. VertexData.CreateSphere = function (options) {
  36686. var segments = options.segments || 32;
  36687. var diameterX = options.diameterX || options.diameter || 1;
  36688. var diameterY = options.diameterY || options.diameter || 1;
  36689. var diameterZ = options.diameterZ || options.diameter || 1;
  36690. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36691. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36692. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36693. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36694. var totalZRotationSteps = 2 + segments;
  36695. var totalYRotationSteps = 2 * totalZRotationSteps;
  36696. var indices = [];
  36697. var positions = [];
  36698. var normals = [];
  36699. var uvs = [];
  36700. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36701. var normalizedZ = zRotationStep / totalZRotationSteps;
  36702. var angleZ = normalizedZ * Math.PI * slice;
  36703. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36704. var normalizedY = yRotationStep / totalYRotationSteps;
  36705. var angleY = normalizedY * Math.PI * 2 * arc;
  36706. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36707. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36708. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36709. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36710. var vertex = complete.multiply(radius);
  36711. var normal = complete.divide(radius).normalize();
  36712. positions.push(vertex.x, vertex.y, vertex.z);
  36713. normals.push(normal.x, normal.y, normal.z);
  36714. uvs.push(normalizedY, normalizedZ);
  36715. }
  36716. if (zRotationStep > 0) {
  36717. var verticesCount = positions.length / 3;
  36718. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36719. indices.push((firstIndex));
  36720. indices.push((firstIndex + 1));
  36721. indices.push(firstIndex + totalYRotationSteps + 1);
  36722. indices.push((firstIndex + totalYRotationSteps + 1));
  36723. indices.push((firstIndex + 1));
  36724. indices.push((firstIndex + totalYRotationSteps + 2));
  36725. }
  36726. }
  36727. }
  36728. // Sides
  36729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36730. // Result
  36731. var vertexData = new VertexData();
  36732. vertexData.indices = indices;
  36733. vertexData.positions = positions;
  36734. vertexData.normals = normals;
  36735. vertexData.uvs = uvs;
  36736. return vertexData;
  36737. };
  36738. /**
  36739. * Creates the VertexData for a cylinder, cone or prism
  36740. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36741. * * height sets the height (y direction) of the cylinder, optional, default 2
  36742. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36743. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36744. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36745. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36746. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36747. * * 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
  36748. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36749. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36750. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36751. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36752. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36753. * * 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)
  36754. * * 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)
  36755. * @returns the VertexData of the cylinder, cone or prism
  36756. */
  36757. VertexData.CreateCylinder = function (options) {
  36758. var height = options.height || 2;
  36759. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36760. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36761. var tessellation = options.tessellation || 24;
  36762. var subdivisions = options.subdivisions || 1;
  36763. var hasRings = options.hasRings ? true : false;
  36764. var enclose = options.enclose ? true : false;
  36765. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36766. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36767. var faceUV = options.faceUV || new Array(3);
  36768. var faceColors = options.faceColors;
  36769. // default face colors and UV if undefined
  36770. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36771. var ringNb = (hasRings) ? subdivisions : 1;
  36772. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36773. var f;
  36774. for (f = 0; f < surfaceNb; f++) {
  36775. if (faceColors && faceColors[f] === undefined) {
  36776. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36777. }
  36778. }
  36779. for (f = 0; f < surfaceNb; f++) {
  36780. if (faceUV && faceUV[f] === undefined) {
  36781. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36782. }
  36783. }
  36784. var indices = new Array();
  36785. var positions = new Array();
  36786. var normals = new Array();
  36787. var uvs = new Array();
  36788. var colors = new Array();
  36789. var angle_step = Math.PI * 2 * arc / tessellation;
  36790. var angle;
  36791. var h;
  36792. var radius;
  36793. var tan = (diameterBottom - diameterTop) / 2 / height;
  36794. var ringVertex = BABYLON.Vector3.Zero();
  36795. var ringNormal = BABYLON.Vector3.Zero();
  36796. var ringFirstVertex = BABYLON.Vector3.Zero();
  36797. var ringFirstNormal = BABYLON.Vector3.Zero();
  36798. var quadNormal = BABYLON.Vector3.Zero();
  36799. var Y = BABYLON.Axis.Y;
  36800. // positions, normals, uvs
  36801. var i;
  36802. var j;
  36803. var r;
  36804. var ringIdx = 1;
  36805. var s = 1; // surface index
  36806. var cs = 0;
  36807. var v = 0;
  36808. for (i = 0; i <= subdivisions; i++) {
  36809. h = i / subdivisions;
  36810. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36811. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36812. for (r = 0; r < ringIdx; r++) {
  36813. if (hasRings) {
  36814. s += r;
  36815. }
  36816. if (enclose) {
  36817. s += 2 * r;
  36818. }
  36819. for (j = 0; j <= tessellation; j++) {
  36820. angle = j * angle_step;
  36821. // position
  36822. ringVertex.x = Math.cos(-angle) * radius;
  36823. ringVertex.y = -height / 2 + h * height;
  36824. ringVertex.z = Math.sin(-angle) * radius;
  36825. // normal
  36826. if (diameterTop === 0 && i === subdivisions) {
  36827. // if no top cap, reuse former normals
  36828. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36829. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36830. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36831. }
  36832. else {
  36833. ringNormal.x = ringVertex.x;
  36834. ringNormal.z = ringVertex.z;
  36835. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36836. ringNormal.normalize();
  36837. }
  36838. // keep first ring vertex values for enclose
  36839. if (j === 0) {
  36840. ringFirstVertex.copyFrom(ringVertex);
  36841. ringFirstNormal.copyFrom(ringNormal);
  36842. }
  36843. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36844. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36845. if (hasRings) {
  36846. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36847. }
  36848. else {
  36849. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36850. }
  36851. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36852. if (faceColors) {
  36853. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36854. }
  36855. }
  36856. // if enclose, add four vertices and their dedicated normals
  36857. if (arc !== 1 && enclose) {
  36858. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36859. positions.push(0, ringVertex.y, 0);
  36860. positions.push(0, ringVertex.y, 0);
  36861. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36862. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36863. quadNormal.normalize();
  36864. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36865. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36866. quadNormal.normalize();
  36867. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36868. if (hasRings) {
  36869. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36870. }
  36871. else {
  36872. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36873. }
  36874. uvs.push(faceUV[s + 1].x, v);
  36875. uvs.push(faceUV[s + 1].z, v);
  36876. if (hasRings) {
  36877. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36878. }
  36879. else {
  36880. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36881. }
  36882. uvs.push(faceUV[s + 2].x, v);
  36883. uvs.push(faceUV[s + 2].z, v);
  36884. if (faceColors) {
  36885. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36886. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36887. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36888. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36889. }
  36890. }
  36891. if (cs !== s) {
  36892. cs = s;
  36893. }
  36894. }
  36895. }
  36896. // indices
  36897. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36898. var s;
  36899. i = 0;
  36900. for (s = 0; s < subdivisions; s++) {
  36901. var i0 = 0;
  36902. var i1 = 0;
  36903. var i2 = 0;
  36904. var i3 = 0;
  36905. for (j = 0; j < tessellation; j++) {
  36906. i0 = i * (e + 1) + j;
  36907. i1 = (i + 1) * (e + 1) + j;
  36908. i2 = i * (e + 1) + (j + 1);
  36909. i3 = (i + 1) * (e + 1) + (j + 1);
  36910. indices.push(i0, i1, i2);
  36911. indices.push(i3, i2, i1);
  36912. }
  36913. if (arc !== 1 && enclose) { // if enclose, add two quads
  36914. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36915. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36916. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36917. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36918. }
  36919. i = (hasRings) ? (i + 2) : (i + 1);
  36920. }
  36921. // Caps
  36922. var createCylinderCap = function (isTop) {
  36923. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36924. if (radius === 0) {
  36925. return;
  36926. }
  36927. // Cap positions, normals & uvs
  36928. var angle;
  36929. var circleVector;
  36930. var i;
  36931. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36932. var c = null;
  36933. if (faceColors) {
  36934. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36935. }
  36936. // cap center
  36937. var vbase = positions.length / 3;
  36938. var offset = isTop ? height / 2 : -height / 2;
  36939. var center = new BABYLON.Vector3(0, offset, 0);
  36940. positions.push(center.x, center.y, center.z);
  36941. normals.push(0, isTop ? 1 : -1, 0);
  36942. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36943. if (c) {
  36944. colors.push(c.r, c.g, c.b, c.a);
  36945. }
  36946. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36947. for (i = 0; i <= tessellation; i++) {
  36948. angle = Math.PI * 2 * i * arc / tessellation;
  36949. var cos = Math.cos(-angle);
  36950. var sin = Math.sin(-angle);
  36951. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36952. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36953. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36954. normals.push(0, isTop ? 1 : -1, 0);
  36955. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36956. if (c) {
  36957. colors.push(c.r, c.g, c.b, c.a);
  36958. }
  36959. }
  36960. // Cap indices
  36961. for (i = 0; i < tessellation; i++) {
  36962. if (!isTop) {
  36963. indices.push(vbase);
  36964. indices.push(vbase + (i + 1));
  36965. indices.push(vbase + (i + 2));
  36966. }
  36967. else {
  36968. indices.push(vbase);
  36969. indices.push(vbase + (i + 2));
  36970. indices.push(vbase + (i + 1));
  36971. }
  36972. }
  36973. };
  36974. // add caps to geometry
  36975. createCylinderCap(false);
  36976. createCylinderCap(true);
  36977. // Sides
  36978. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36979. var vertexData = new VertexData();
  36980. vertexData.indices = indices;
  36981. vertexData.positions = positions;
  36982. vertexData.normals = normals;
  36983. vertexData.uvs = uvs;
  36984. if (faceColors) {
  36985. vertexData.colors = colors;
  36986. }
  36987. return vertexData;
  36988. };
  36989. /**
  36990. * Creates the VertexData for a torus
  36991. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36992. * * diameter the diameter of the torus, optional default 1
  36993. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36994. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36995. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36996. * * 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)
  36997. * * 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)
  36998. * @returns the VertexData of the torus
  36999. */
  37000. VertexData.CreateTorus = function (options) {
  37001. var indices = [];
  37002. var positions = [];
  37003. var normals = [];
  37004. var uvs = [];
  37005. var diameter = options.diameter || 1;
  37006. var thickness = options.thickness || 0.5;
  37007. var tessellation = options.tessellation || 16;
  37008. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37009. var stride = tessellation + 1;
  37010. for (var i = 0; i <= tessellation; i++) {
  37011. var u = i / tessellation;
  37012. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37013. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37014. for (var j = 0; j <= tessellation; j++) {
  37015. var v = 1 - j / tessellation;
  37016. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37017. var dx = Math.cos(innerAngle);
  37018. var dy = Math.sin(innerAngle);
  37019. // Create a vertex.
  37020. var normal = new BABYLON.Vector3(dx, dy, 0);
  37021. var position = normal.scale(thickness / 2);
  37022. var textureCoordinate = new BABYLON.Vector2(u, v);
  37023. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37024. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37025. positions.push(position.x, position.y, position.z);
  37026. normals.push(normal.x, normal.y, normal.z);
  37027. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37028. // And create indices for two triangles.
  37029. var nextI = (i + 1) % stride;
  37030. var nextJ = (j + 1) % stride;
  37031. indices.push(i * stride + j);
  37032. indices.push(i * stride + nextJ);
  37033. indices.push(nextI * stride + j);
  37034. indices.push(i * stride + nextJ);
  37035. indices.push(nextI * stride + nextJ);
  37036. indices.push(nextI * stride + j);
  37037. }
  37038. }
  37039. // Sides
  37040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37041. // Result
  37042. var vertexData = new VertexData();
  37043. vertexData.indices = indices;
  37044. vertexData.positions = positions;
  37045. vertexData.normals = normals;
  37046. vertexData.uvs = uvs;
  37047. return vertexData;
  37048. };
  37049. /**
  37050. * Creates the VertexData of the LineSystem
  37051. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37052. * - lines an array of lines, each line being an array of successive Vector3
  37053. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37054. * @returns the VertexData of the LineSystem
  37055. */
  37056. VertexData.CreateLineSystem = function (options) {
  37057. var indices = [];
  37058. var positions = [];
  37059. var lines = options.lines;
  37060. var colors = options.colors;
  37061. var vertexColors = [];
  37062. var idx = 0;
  37063. for (var l = 0; l < lines.length; l++) {
  37064. var points = lines[l];
  37065. for (var index = 0; index < points.length; index++) {
  37066. positions.push(points[index].x, points[index].y, points[index].z);
  37067. if (colors) {
  37068. var color = colors[l];
  37069. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37070. }
  37071. if (index > 0) {
  37072. indices.push(idx - 1);
  37073. indices.push(idx);
  37074. }
  37075. idx++;
  37076. }
  37077. }
  37078. var vertexData = new VertexData();
  37079. vertexData.indices = indices;
  37080. vertexData.positions = positions;
  37081. if (colors) {
  37082. vertexData.colors = vertexColors;
  37083. }
  37084. return vertexData;
  37085. };
  37086. /**
  37087. * Create the VertexData for a DashedLines
  37088. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37089. * - points an array successive Vector3
  37090. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37091. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37092. * - dashNb the intended total number of dashes, optional, default 200
  37093. * @returns the VertexData for the DashedLines
  37094. */
  37095. VertexData.CreateDashedLines = function (options) {
  37096. var dashSize = options.dashSize || 3;
  37097. var gapSize = options.gapSize || 1;
  37098. var dashNb = options.dashNb || 200;
  37099. var points = options.points;
  37100. var positions = new Array();
  37101. var indices = new Array();
  37102. var curvect = BABYLON.Vector3.Zero();
  37103. var lg = 0;
  37104. var nb = 0;
  37105. var shft = 0;
  37106. var dashshft = 0;
  37107. var curshft = 0;
  37108. var idx = 0;
  37109. var i = 0;
  37110. for (i = 0; i < points.length - 1; i++) {
  37111. points[i + 1].subtractToRef(points[i], curvect);
  37112. lg += curvect.length();
  37113. }
  37114. shft = lg / dashNb;
  37115. dashshft = dashSize * shft / (dashSize + gapSize);
  37116. for (i = 0; i < points.length - 1; i++) {
  37117. points[i + 1].subtractToRef(points[i], curvect);
  37118. nb = Math.floor(curvect.length() / shft);
  37119. curvect.normalize();
  37120. for (var j = 0; j < nb; j++) {
  37121. curshft = shft * j;
  37122. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37123. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37124. indices.push(idx, idx + 1);
  37125. idx += 2;
  37126. }
  37127. }
  37128. // Result
  37129. var vertexData = new VertexData();
  37130. vertexData.positions = positions;
  37131. vertexData.indices = indices;
  37132. return vertexData;
  37133. };
  37134. /**
  37135. * Creates the VertexData for a Ground
  37136. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37137. * - width the width (x direction) of the ground, optional, default 1
  37138. * - height the height (z direction) of the ground, optional, default 1
  37139. * - subdivisions the number of subdivisions per side, optional, default 1
  37140. * @returns the VertexData of the Ground
  37141. */
  37142. VertexData.CreateGround = function (options) {
  37143. var indices = [];
  37144. var positions = [];
  37145. var normals = [];
  37146. var uvs = [];
  37147. var row, col;
  37148. var width = options.width || 1;
  37149. var height = options.height || 1;
  37150. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37151. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37152. for (row = 0; row <= subdivisionsY; row++) {
  37153. for (col = 0; col <= subdivisionsX; col++) {
  37154. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37155. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37156. positions.push(position.x, position.y, position.z);
  37157. normals.push(normal.x, normal.y, normal.z);
  37158. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37159. }
  37160. }
  37161. for (row = 0; row < subdivisionsY; row++) {
  37162. for (col = 0; col < subdivisionsX; col++) {
  37163. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37164. indices.push(col + 1 + row * (subdivisionsX + 1));
  37165. indices.push(col + row * (subdivisionsX + 1));
  37166. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37167. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37168. indices.push(col + row * (subdivisionsX + 1));
  37169. }
  37170. }
  37171. // Result
  37172. var vertexData = new VertexData();
  37173. vertexData.indices = indices;
  37174. vertexData.positions = positions;
  37175. vertexData.normals = normals;
  37176. vertexData.uvs = uvs;
  37177. return vertexData;
  37178. };
  37179. /**
  37180. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37181. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37182. * * xmin the ground minimum X coordinate, optional, default -1
  37183. * * zmin the ground minimum Z coordinate, optional, default -1
  37184. * * xmax the ground maximum X coordinate, optional, default 1
  37185. * * zmax the ground maximum Z coordinate, optional, default 1
  37186. * * 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}
  37187. * * 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}
  37188. * @returns the VertexData of the TiledGround
  37189. */
  37190. VertexData.CreateTiledGround = function (options) {
  37191. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37192. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37193. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37194. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37195. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37196. var precision = options.precision || { w: 1, h: 1 };
  37197. var indices = new Array();
  37198. var positions = new Array();
  37199. var normals = new Array();
  37200. var uvs = new Array();
  37201. var row, col, tileRow, tileCol;
  37202. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37203. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37204. precision.w = (precision.w < 1) ? 1 : precision.w;
  37205. precision.h = (precision.h < 1) ? 1 : precision.h;
  37206. var tileSize = {
  37207. 'w': (xmax - xmin) / subdivisions.w,
  37208. 'h': (zmax - zmin) / subdivisions.h
  37209. };
  37210. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37211. // Indices
  37212. var base = positions.length / 3;
  37213. var rowLength = precision.w + 1;
  37214. for (row = 0; row < precision.h; row++) {
  37215. for (col = 0; col < precision.w; col++) {
  37216. var square = [
  37217. base + col + row * rowLength,
  37218. base + (col + 1) + row * rowLength,
  37219. base + (col + 1) + (row + 1) * rowLength,
  37220. base + col + (row + 1) * rowLength
  37221. ];
  37222. indices.push(square[1]);
  37223. indices.push(square[2]);
  37224. indices.push(square[3]);
  37225. indices.push(square[0]);
  37226. indices.push(square[1]);
  37227. indices.push(square[3]);
  37228. }
  37229. }
  37230. // Position, normals and uvs
  37231. var position = BABYLON.Vector3.Zero();
  37232. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37233. for (row = 0; row <= precision.h; row++) {
  37234. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37235. for (col = 0; col <= precision.w; col++) {
  37236. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37237. position.y = 0;
  37238. positions.push(position.x, position.y, position.z);
  37239. normals.push(normal.x, normal.y, normal.z);
  37240. uvs.push(col / precision.w, row / precision.h);
  37241. }
  37242. }
  37243. }
  37244. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37245. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37246. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37247. }
  37248. }
  37249. // Result
  37250. var vertexData = new VertexData();
  37251. vertexData.indices = indices;
  37252. vertexData.positions = positions;
  37253. vertexData.normals = normals;
  37254. vertexData.uvs = uvs;
  37255. return vertexData;
  37256. };
  37257. /**
  37258. * Creates the VertexData of the Ground designed from a heightmap
  37259. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37260. * * width the width (x direction) of the ground
  37261. * * height the height (z direction) of the ground
  37262. * * subdivisions the number of subdivisions per side
  37263. * * minHeight the minimum altitude on the ground, optional, default 0
  37264. * * maxHeight the maximum altitude on the ground, optional default 1
  37265. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37266. * * buffer the array holding the image color data
  37267. * * bufferWidth the width of image
  37268. * * bufferHeight the height of image
  37269. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37270. * @returns the VertexData of the Ground designed from a heightmap
  37271. */
  37272. VertexData.CreateGroundFromHeightMap = function (options) {
  37273. var indices = [];
  37274. var positions = [];
  37275. var normals = [];
  37276. var uvs = [];
  37277. var row, col;
  37278. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37279. var alphaFilter = options.alphaFilter || 0.0;
  37280. // Vertices
  37281. for (row = 0; row <= options.subdivisions; row++) {
  37282. for (col = 0; col <= options.subdivisions; col++) {
  37283. 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));
  37284. // Compute height
  37285. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37286. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37287. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37288. var r = options.buffer[pos] / 255.0;
  37289. var g = options.buffer[pos + 1] / 255.0;
  37290. var b = options.buffer[pos + 2] / 255.0;
  37291. var a = options.buffer[pos + 3] / 255.0;
  37292. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37293. // If our alpha channel is not within our filter then we will assign a 'special' height
  37294. // Then when building the indices, we will ignore any vertex that is using the special height
  37295. if (a >= alphaFilter)
  37296. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37297. else {
  37298. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37299. }
  37300. // Add vertex
  37301. positions.push(position.x, position.y, position.z);
  37302. normals.push(0, 0, 0);
  37303. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37304. }
  37305. }
  37306. // Indices
  37307. for (row = 0; row < options.subdivisions; row++) {
  37308. for (col = 0; col < options.subdivisions; col++) {
  37309. // Calculate Indices
  37310. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37311. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37312. var idx3 = (col + row * (options.subdivisions + 1));
  37313. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37314. // Check that all indices are visible (based on our special height)
  37315. // Only display the vertex if all Indices are visible
  37316. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37317. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37318. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37319. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37320. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37321. indices.push(idx1);
  37322. indices.push(idx2);
  37323. indices.push(idx3);
  37324. }
  37325. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37326. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37327. indices.push(idx4);
  37328. indices.push(idx1);
  37329. indices.push(idx3);
  37330. }
  37331. }
  37332. }
  37333. // Normals
  37334. VertexData.ComputeNormals(positions, indices, normals);
  37335. // Result
  37336. var vertexData = new VertexData();
  37337. vertexData.indices = indices;
  37338. vertexData.positions = positions;
  37339. vertexData.normals = normals;
  37340. vertexData.uvs = uvs;
  37341. return vertexData;
  37342. };
  37343. /**
  37344. * Creates the VertexData for a Plane
  37345. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37346. * * size sets the width and height of the plane to the value of size, optional default 1
  37347. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37348. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37349. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37350. * * 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)
  37351. * * 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)
  37352. * @returns the VertexData of the box
  37353. */
  37354. VertexData.CreatePlane = function (options) {
  37355. var indices = [];
  37356. var positions = [];
  37357. var normals = [];
  37358. var uvs = [];
  37359. var width = options.width || options.size || 1;
  37360. var height = options.height || options.size || 1;
  37361. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37362. // Vertices
  37363. var halfWidth = width / 2.0;
  37364. var halfHeight = height / 2.0;
  37365. positions.push(-halfWidth, -halfHeight, 0);
  37366. normals.push(0, 0, -1.0);
  37367. uvs.push(0.0, 0.0);
  37368. positions.push(halfWidth, -halfHeight, 0);
  37369. normals.push(0, 0, -1.0);
  37370. uvs.push(1.0, 0.0);
  37371. positions.push(halfWidth, halfHeight, 0);
  37372. normals.push(0, 0, -1.0);
  37373. uvs.push(1.0, 1.0);
  37374. positions.push(-halfWidth, halfHeight, 0);
  37375. normals.push(0, 0, -1.0);
  37376. uvs.push(0.0, 1.0);
  37377. // Indices
  37378. indices.push(0);
  37379. indices.push(1);
  37380. indices.push(2);
  37381. indices.push(0);
  37382. indices.push(2);
  37383. indices.push(3);
  37384. // Sides
  37385. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37386. // Result
  37387. var vertexData = new VertexData();
  37388. vertexData.indices = indices;
  37389. vertexData.positions = positions;
  37390. vertexData.normals = normals;
  37391. vertexData.uvs = uvs;
  37392. return vertexData;
  37393. };
  37394. /**
  37395. * Creates the VertexData of the Disc or regular Polygon
  37396. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37397. * * radius the radius of the disc, optional default 0.5
  37398. * * tessellation the number of polygon sides, optional, default 64
  37399. * * 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
  37400. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37401. * * 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)
  37402. * * 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)
  37403. * @returns the VertexData of the box
  37404. */
  37405. VertexData.CreateDisc = function (options) {
  37406. var positions = new Array();
  37407. var indices = new Array();
  37408. var normals = new Array();
  37409. var uvs = new Array();
  37410. var radius = options.radius || 0.5;
  37411. var tessellation = options.tessellation || 64;
  37412. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37413. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37414. // positions and uvs
  37415. positions.push(0, 0, 0); // disc center first
  37416. uvs.push(0.5, 0.5);
  37417. var theta = Math.PI * 2 * arc;
  37418. var step = theta / tessellation;
  37419. for (var a = 0; a < theta; a += step) {
  37420. var x = Math.cos(a);
  37421. var y = Math.sin(a);
  37422. var u = (x + 1) / 2;
  37423. var v = (1 - y) / 2;
  37424. positions.push(radius * x, radius * y, 0);
  37425. uvs.push(u, v);
  37426. }
  37427. if (arc === 1) {
  37428. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37429. uvs.push(uvs[2], uvs[3]);
  37430. }
  37431. //indices
  37432. var vertexNb = positions.length / 3;
  37433. for (var i = 1; i < vertexNb - 1; i++) {
  37434. indices.push(i + 1, 0, i);
  37435. }
  37436. // result
  37437. VertexData.ComputeNormals(positions, indices, normals);
  37438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37439. var vertexData = new VertexData();
  37440. vertexData.indices = indices;
  37441. vertexData.positions = positions;
  37442. vertexData.normals = normals;
  37443. vertexData.uvs = uvs;
  37444. return vertexData;
  37445. };
  37446. /**
  37447. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37448. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37449. * @param polygon a mesh built from polygonTriangulation.build()
  37450. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37451. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37452. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37453. * @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)
  37454. * @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)
  37455. * @returns the VertexData of the Polygon
  37456. */
  37457. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37458. var faceUV = fUV || new Array(3);
  37459. var faceColors = fColors;
  37460. var colors = [];
  37461. // default face colors and UV if undefined
  37462. for (var f = 0; f < 3; f++) {
  37463. if (faceUV[f] === undefined) {
  37464. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37465. }
  37466. if (faceColors && faceColors[f] === undefined) {
  37467. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37468. }
  37469. }
  37470. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37471. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37472. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37473. var indices = polygon.getIndices();
  37474. // set face colours and textures
  37475. var idx = 0;
  37476. var face = 0;
  37477. for (var index = 0; index < normals.length; index += 3) {
  37478. //Edge Face no. 1
  37479. if (Math.abs(normals[index + 1]) < 0.001) {
  37480. face = 1;
  37481. }
  37482. //Top Face no. 0
  37483. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37484. face = 0;
  37485. }
  37486. //Bottom Face no. 2
  37487. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37488. face = 2;
  37489. }
  37490. idx = index / 3;
  37491. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37492. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37493. if (faceColors) {
  37494. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37495. }
  37496. }
  37497. // sides
  37498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37499. // Result
  37500. var vertexData = new VertexData();
  37501. vertexData.indices = indices;
  37502. vertexData.positions = positions;
  37503. vertexData.normals = normals;
  37504. vertexData.uvs = uvs;
  37505. if (faceColors) {
  37506. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37507. vertexData.colors = totalColors;
  37508. }
  37509. return vertexData;
  37510. };
  37511. /**
  37512. * Creates the VertexData of the IcoSphere
  37513. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37514. * * radius the radius of the IcoSphere, optional default 1
  37515. * * radiusX allows stretching in the x direction, optional, default radius
  37516. * * radiusY allows stretching in the y direction, optional, default radius
  37517. * * radiusZ allows stretching in the z direction, optional, default radius
  37518. * * flat when true creates a flat shaded mesh, optional, default true
  37519. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37520. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37521. * * 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)
  37522. * * 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)
  37523. * @returns the VertexData of the IcoSphere
  37524. */
  37525. VertexData.CreateIcoSphere = function (options) {
  37526. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37527. var radius = options.radius || 1;
  37528. var flat = (options.flat === undefined) ? true : options.flat;
  37529. var subdivisions = options.subdivisions || 4;
  37530. var radiusX = options.radiusX || radius;
  37531. var radiusY = options.radiusY || radius;
  37532. var radiusZ = options.radiusZ || radius;
  37533. var t = (1 + Math.sqrt(5)) / 2;
  37534. // 12 vertex x,y,z
  37535. var ico_vertices = [
  37536. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37537. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37538. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37539. ];
  37540. // index of 3 vertex makes a face of icopshere
  37541. var ico_indices = [
  37542. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37543. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37544. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37545. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37546. ];
  37547. // vertex for uv have aliased position, not for UV
  37548. var vertices_unalias_id = [
  37549. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37550. // vertex alias
  37551. 0,
  37552. 2,
  37553. 3,
  37554. 3,
  37555. 3,
  37556. 4,
  37557. 7,
  37558. 8,
  37559. 9,
  37560. 9,
  37561. 10,
  37562. 11 // 23: B + 12
  37563. ];
  37564. // uv as integer step (not pixels !)
  37565. var ico_vertexuv = [
  37566. 5, 1, 3, 1, 6, 4, 0, 0,
  37567. 5, 3, 4, 2, 2, 2, 4, 0,
  37568. 2, 0, 1, 1, 6, 0, 6, 2,
  37569. // vertex alias (for same vertex on different faces)
  37570. 0, 4,
  37571. 3, 3,
  37572. 4, 4,
  37573. 3, 1,
  37574. 4, 2,
  37575. 4, 4,
  37576. 0, 2,
  37577. 1, 1,
  37578. 2, 2,
  37579. 3, 3,
  37580. 1, 3,
  37581. 2, 4 // 23: B + 12
  37582. ];
  37583. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37584. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37585. // First island of uv mapping
  37586. // v = 4h 3+ 2
  37587. // v = 3h 9+ 4
  37588. // v = 2h 9+ 5 B
  37589. // v = 1h 9 1 0
  37590. // v = 0h 3 8 7 A
  37591. // u = 0 1 2 3 4 5 6 *a
  37592. // Second island of uv mapping
  37593. // v = 4h 0+ B+ 4+
  37594. // v = 3h A+ 2+
  37595. // v = 2h 7+ 6 3+
  37596. // v = 1h 8+ 3+
  37597. // v = 0h
  37598. // u = 0 1 2 3 4 5 6 *a
  37599. // Face layout on texture UV mapping
  37600. // ============
  37601. // \ 4 /\ 16 / ======
  37602. // \ / \ / /\ 11 /
  37603. // \/ 7 \/ / \ /
  37604. // ======= / 10 \/
  37605. // /\ 17 /\ =======
  37606. // / \ / \ \ 15 /\
  37607. // / 8 \/ 12 \ \ / \
  37608. // ============ \/ 6 \
  37609. // \ 18 /\ ============
  37610. // \ / \ \ 5 /\ 0 /
  37611. // \/ 13 \ \ / \ /
  37612. // ======= \/ 1 \/
  37613. // =============
  37614. // /\ 19 /\ 2 /\
  37615. // / \ / \ / \
  37616. // / 14 \/ 9 \/ 3 \
  37617. // ===================
  37618. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37619. var ustep = 138 / 1024;
  37620. var vstep = 239 / 1024;
  37621. var uoffset = 60 / 1024;
  37622. var voffset = 26 / 1024;
  37623. // Second island should have margin, not to touch the first island
  37624. // avoid any borderline artefact in pixel rounding
  37625. var island_u_offset = -40 / 1024;
  37626. var island_v_offset = +20 / 1024;
  37627. // face is either island 0 or 1 :
  37628. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37629. var island = [
  37630. 0, 0, 0, 0, 1,
  37631. 0, 0, 1, 1, 0,
  37632. 0, 0, 1, 1, 0,
  37633. 0, 1, 1, 1, 0 // 15 - 19
  37634. ];
  37635. var indices = new Array();
  37636. var positions = new Array();
  37637. var normals = new Array();
  37638. var uvs = new Array();
  37639. var current_indice = 0;
  37640. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37641. var face_vertex_pos = new Array(3);
  37642. var face_vertex_uv = new Array(3);
  37643. var v012;
  37644. for (v012 = 0; v012 < 3; v012++) {
  37645. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37646. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37647. }
  37648. // create all with normals
  37649. for (var face = 0; face < 20; face++) {
  37650. // 3 vertex per face
  37651. for (v012 = 0; v012 < 3; v012++) {
  37652. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37653. var v_id = ico_indices[3 * face + v012];
  37654. // vertex have 3D position (x,y,z)
  37655. 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]);
  37656. // Normalize to get normal, then scale to radius
  37657. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37658. // uv Coordinates from vertex ID
  37659. 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);
  37660. }
  37661. // Subdivide the face (interpolate pos, norm, uv)
  37662. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37663. // - norm is linear interpolation of vertex corner normal
  37664. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37665. // - uv is linear interpolation
  37666. //
  37667. // Topology is as below for sub-divide by 2
  37668. // vertex shown as v0,v1,v2
  37669. // interp index is i1 to progress in range [v0,v1[
  37670. // interp index is i2 to progress in range [v0,v2[
  37671. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37672. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37673. //
  37674. //
  37675. // i2 v2
  37676. // ^ ^
  37677. // / / \
  37678. // / / \
  37679. // / / \
  37680. // / / (0,1) \
  37681. // / #---------\
  37682. // / / \ (0,0)'/ \
  37683. // / / \ / \
  37684. // / / \ / \
  37685. // / / (0,0) \ / (1,0) \
  37686. // / #---------#---------\
  37687. // v0 v1
  37688. //
  37689. // --------------------> i1
  37690. //
  37691. // interp of (i1,i2):
  37692. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37693. // along i1 : lerp(x0,x1, i1/(S-i2))
  37694. //
  37695. // centroid of triangle is needed to get help normal computation
  37696. // (c1,c2) are used for centroid location
  37697. var interp_vertex = function (i1, i2, c1, c2) {
  37698. // vertex is interpolated from
  37699. // - face_vertex_pos[0..2]
  37700. // - face_vertex_uv[0..2]
  37701. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37702. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37703. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37704. pos_interp.normalize();
  37705. var vertex_normal;
  37706. if (flat) {
  37707. // in flat mode, recalculate normal as face centroid normal
  37708. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37709. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37710. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37711. }
  37712. else {
  37713. // in smooth mode, recalculate normal from each single vertex position
  37714. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37715. }
  37716. // Vertex normal need correction due to X,Y,Z radius scaling
  37717. vertex_normal.x /= radiusX;
  37718. vertex_normal.y /= radiusY;
  37719. vertex_normal.z /= radiusZ;
  37720. vertex_normal.normalize();
  37721. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37722. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37723. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37724. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37725. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37726. uvs.push(uv_interp.x, uv_interp.y);
  37727. // push each vertex has member of a face
  37728. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37729. indices.push(current_indice);
  37730. current_indice++;
  37731. };
  37732. for (var i2 = 0; i2 < subdivisions; i2++) {
  37733. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37734. // face : (i1,i2) for /\ :
  37735. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37736. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37737. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37738. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37739. if (i1 + i2 + 1 < subdivisions) {
  37740. // face : (i1,i2)' for \/ :
  37741. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37742. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37743. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37744. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37745. }
  37746. }
  37747. }
  37748. }
  37749. // Sides
  37750. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37751. // Result
  37752. var vertexData = new VertexData();
  37753. vertexData.indices = indices;
  37754. vertexData.positions = positions;
  37755. vertexData.normals = normals;
  37756. vertexData.uvs = uvs;
  37757. return vertexData;
  37758. };
  37759. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37760. /**
  37761. * Creates the VertexData for a Polyhedron
  37762. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37763. * * type provided types are:
  37764. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37765. * * 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)
  37766. * * size the size of the IcoSphere, optional default 1
  37767. * * sizeX allows stretching in the x direction, optional, default size
  37768. * * sizeY allows stretching in the y direction, optional, default size
  37769. * * sizeZ allows stretching in the z direction, optional, default size
  37770. * * 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
  37771. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37772. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37773. * * flat when true creates a flat shaded mesh, optional, default true
  37774. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37775. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37776. * * 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)
  37777. * * 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)
  37778. * @returns the VertexData of the Polyhedron
  37779. */
  37780. VertexData.CreatePolyhedron = function (options) {
  37781. // provided polyhedron types :
  37782. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37783. // 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)
  37784. var polyhedra = [];
  37785. 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]] };
  37786. 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]] };
  37787. polyhedra[2] = {
  37788. 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]],
  37789. 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]]
  37790. };
  37791. polyhedra[3] = {
  37792. 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]],
  37793. 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]]
  37794. };
  37795. polyhedra[4] = {
  37796. 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]],
  37797. 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]]
  37798. };
  37799. 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]] };
  37800. 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]] };
  37801. 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]] };
  37802. 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]] };
  37803. 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]] };
  37804. 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]] };
  37805. 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]] };
  37806. 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]] };
  37807. 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]] };
  37808. polyhedra[14] = {
  37809. 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]],
  37810. 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]]
  37811. };
  37812. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37813. var size = options.size;
  37814. var sizeX = options.sizeX || size || 1;
  37815. var sizeY = options.sizeY || size || 1;
  37816. var sizeZ = options.sizeZ || size || 1;
  37817. var data = options.custom || polyhedra[type];
  37818. var nbfaces = data.face.length;
  37819. var faceUV = options.faceUV || new Array(nbfaces);
  37820. var faceColors = options.faceColors;
  37821. var flat = (options.flat === undefined) ? true : options.flat;
  37822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37823. var positions = new Array();
  37824. var indices = new Array();
  37825. var normals = new Array();
  37826. var uvs = new Array();
  37827. var colors = new Array();
  37828. var index = 0;
  37829. var faceIdx = 0; // face cursor in the array "indexes"
  37830. var indexes = new Array();
  37831. var i = 0;
  37832. var f = 0;
  37833. var u, v, ang, x, y, tmp;
  37834. // default face colors and UV if undefined
  37835. if (flat) {
  37836. for (f = 0; f < nbfaces; f++) {
  37837. if (faceColors && faceColors[f] === undefined) {
  37838. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37839. }
  37840. if (faceUV && faceUV[f] === undefined) {
  37841. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37842. }
  37843. }
  37844. }
  37845. if (!flat) {
  37846. for (i = 0; i < data.vertex.length; i++) {
  37847. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37848. uvs.push(0, 0);
  37849. }
  37850. for (f = 0; f < nbfaces; f++) {
  37851. for (i = 0; i < data.face[f].length - 2; i++) {
  37852. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37853. }
  37854. }
  37855. }
  37856. else {
  37857. for (f = 0; f < nbfaces; f++) {
  37858. var fl = data.face[f].length; // number of vertices of the current face
  37859. ang = 2 * Math.PI / fl;
  37860. x = 0.5 * Math.tan(ang / 2);
  37861. y = 0.5;
  37862. // positions, uvs, colors
  37863. for (i = 0; i < fl; i++) {
  37864. // positions
  37865. 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);
  37866. indexes.push(index);
  37867. index++;
  37868. // uvs
  37869. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37870. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37871. uvs.push(u, v);
  37872. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37873. y = x * Math.sin(ang) + y * Math.cos(ang);
  37874. x = tmp;
  37875. // colors
  37876. if (faceColors) {
  37877. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37878. }
  37879. }
  37880. // indices from indexes
  37881. for (i = 0; i < fl - 2; i++) {
  37882. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37883. }
  37884. faceIdx += fl;
  37885. }
  37886. }
  37887. VertexData.ComputeNormals(positions, indices, normals);
  37888. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37889. var vertexData = new VertexData();
  37890. vertexData.positions = positions;
  37891. vertexData.indices = indices;
  37892. vertexData.normals = normals;
  37893. vertexData.uvs = uvs;
  37894. if (faceColors && flat) {
  37895. vertexData.colors = colors;
  37896. }
  37897. return vertexData;
  37898. };
  37899. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37900. /**
  37901. * Creates the VertexData for a TorusKnot
  37902. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37903. * * radius the radius of the torus knot, optional, default 2
  37904. * * tube the thickness of the tube, optional, default 0.5
  37905. * * radialSegments the number of sides on each tube segments, optional, default 32
  37906. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37907. * * p the number of windings around the z axis, optional, default 2
  37908. * * q the number of windings around the x axis, optional, default 3
  37909. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37910. * * 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)
  37911. * * 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)
  37912. * @returns the VertexData of the Torus Knot
  37913. */
  37914. VertexData.CreateTorusKnot = function (options) {
  37915. var indices = new Array();
  37916. var positions = new Array();
  37917. var normals = new Array();
  37918. var uvs = new Array();
  37919. var radius = options.radius || 2;
  37920. var tube = options.tube || 0.5;
  37921. var radialSegments = options.radialSegments || 32;
  37922. var tubularSegments = options.tubularSegments || 32;
  37923. var p = options.p || 2;
  37924. var q = options.q || 3;
  37925. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37926. // Helper
  37927. var getPos = function (angle) {
  37928. var cu = Math.cos(angle);
  37929. var su = Math.sin(angle);
  37930. var quOverP = q / p * angle;
  37931. var cs = Math.cos(quOverP);
  37932. var tx = radius * (2 + cs) * 0.5 * cu;
  37933. var ty = radius * (2 + cs) * su * 0.5;
  37934. var tz = radius * Math.sin(quOverP) * 0.5;
  37935. return new BABYLON.Vector3(tx, ty, tz);
  37936. };
  37937. // Vertices
  37938. var i;
  37939. var j;
  37940. for (i = 0; i <= radialSegments; i++) {
  37941. var modI = i % radialSegments;
  37942. var u = modI / radialSegments * 2 * p * Math.PI;
  37943. var p1 = getPos(u);
  37944. var p2 = getPos(u + 0.01);
  37945. var tang = p2.subtract(p1);
  37946. var n = p2.add(p1);
  37947. var bitan = BABYLON.Vector3.Cross(tang, n);
  37948. n = BABYLON.Vector3.Cross(bitan, tang);
  37949. bitan.normalize();
  37950. n.normalize();
  37951. for (j = 0; j < tubularSegments; j++) {
  37952. var modJ = j % tubularSegments;
  37953. var v = modJ / tubularSegments * 2 * Math.PI;
  37954. var cx = -tube * Math.cos(v);
  37955. var cy = tube * Math.sin(v);
  37956. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37957. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37958. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37959. uvs.push(i / radialSegments);
  37960. uvs.push(j / tubularSegments);
  37961. }
  37962. }
  37963. for (i = 0; i < radialSegments; i++) {
  37964. for (j = 0; j < tubularSegments; j++) {
  37965. var jNext = (j + 1) % tubularSegments;
  37966. var a = i * tubularSegments + j;
  37967. var b = (i + 1) * tubularSegments + j;
  37968. var c = (i + 1) * tubularSegments + jNext;
  37969. var d = i * tubularSegments + jNext;
  37970. indices.push(d);
  37971. indices.push(b);
  37972. indices.push(a);
  37973. indices.push(d);
  37974. indices.push(c);
  37975. indices.push(b);
  37976. }
  37977. }
  37978. // Normals
  37979. VertexData.ComputeNormals(positions, indices, normals);
  37980. // Sides
  37981. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37982. // Result
  37983. var vertexData = new VertexData();
  37984. vertexData.indices = indices;
  37985. vertexData.positions = positions;
  37986. vertexData.normals = normals;
  37987. vertexData.uvs = uvs;
  37988. return vertexData;
  37989. };
  37990. // Tools
  37991. /**
  37992. * Compute normals for given positions and indices
  37993. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37994. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37995. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37996. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37997. * * facetNormals : optional array of facet normals (vector3)
  37998. * * facetPositions : optional array of facet positions (vector3)
  37999. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38000. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38001. * * bInfo : optional bounding info, required for facetPartitioning computation
  38002. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38003. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38004. * * useRightHandedSystem: optional boolean to for right handed system computation
  38005. * * depthSort : optional boolean to enable the facet depth sort computation
  38006. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38007. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38008. */
  38009. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38010. // temporary scalar variables
  38011. var index = 0; // facet index
  38012. var p1p2x = 0.0; // p1p2 vector x coordinate
  38013. var p1p2y = 0.0; // p1p2 vector y coordinate
  38014. var p1p2z = 0.0; // p1p2 vector z coordinate
  38015. var p3p2x = 0.0; // p3p2 vector x coordinate
  38016. var p3p2y = 0.0; // p3p2 vector y coordinate
  38017. var p3p2z = 0.0; // p3p2 vector z coordinate
  38018. var faceNormalx = 0.0; // facet normal x coordinate
  38019. var faceNormaly = 0.0; // facet normal y coordinate
  38020. var faceNormalz = 0.0; // facet normal z coordinate
  38021. var length = 0.0; // facet normal length before normalization
  38022. var v1x = 0; // vector1 x index in the positions array
  38023. var v1y = 0; // vector1 y index in the positions array
  38024. var v1z = 0; // vector1 z index in the positions array
  38025. var v2x = 0; // vector2 x index in the positions array
  38026. var v2y = 0; // vector2 y index in the positions array
  38027. var v2z = 0; // vector2 z index in the positions array
  38028. var v3x = 0; // vector3 x index in the positions array
  38029. var v3y = 0; // vector3 y index in the positions array
  38030. var v3z = 0; // vector3 z index in the positions array
  38031. var computeFacetNormals = false;
  38032. var computeFacetPositions = false;
  38033. var computeFacetPartitioning = false;
  38034. var computeDepthSort = false;
  38035. var faceNormalSign = 1;
  38036. var ratio = 0;
  38037. var distanceTo = null;
  38038. if (options) {
  38039. computeFacetNormals = (options.facetNormals) ? true : false;
  38040. computeFacetPositions = (options.facetPositions) ? true : false;
  38041. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38042. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38043. ratio = options.ratio || 0;
  38044. computeDepthSort = (options.depthSort) ? true : false;
  38045. distanceTo = (options.distanceTo);
  38046. if (computeDepthSort) {
  38047. if (distanceTo === undefined) {
  38048. distanceTo = BABYLON.Vector3.Zero();
  38049. }
  38050. var depthSortedFacets = options.depthSortedFacets;
  38051. }
  38052. }
  38053. // facetPartitioning reinit if needed
  38054. var xSubRatio = 0;
  38055. var ySubRatio = 0;
  38056. var zSubRatio = 0;
  38057. var subSq = 0;
  38058. if (computeFacetPartitioning && options && options.bbSize) {
  38059. var ox = 0; // X partitioning index for facet position
  38060. var oy = 0; // Y partinioning index for facet position
  38061. var oz = 0; // Z partinioning index for facet position
  38062. var b1x = 0; // X partitioning index for facet v1 vertex
  38063. var b1y = 0; // Y partitioning index for facet v1 vertex
  38064. var b1z = 0; // z partitioning index for facet v1 vertex
  38065. var b2x = 0; // X partitioning index for facet v2 vertex
  38066. var b2y = 0; // Y partitioning index for facet v2 vertex
  38067. var b2z = 0; // Z partitioning index for facet v2 vertex
  38068. var b3x = 0; // X partitioning index for facet v3 vertex
  38069. var b3y = 0; // Y partitioning index for facet v3 vertex
  38070. var b3z = 0; // Z partitioning index for facet v3 vertex
  38071. var block_idx_o = 0; // facet barycenter block index
  38072. var block_idx_v1 = 0; // v1 vertex block index
  38073. var block_idx_v2 = 0; // v2 vertex block index
  38074. var block_idx_v3 = 0; // v3 vertex block index
  38075. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38076. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38077. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38078. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38079. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38080. subSq = options.subDiv.max * options.subDiv.max;
  38081. options.facetPartitioning.length = 0;
  38082. }
  38083. // reset the normals
  38084. for (index = 0; index < positions.length; index++) {
  38085. normals[index] = 0.0;
  38086. }
  38087. // Loop : 1 indice triplet = 1 facet
  38088. var nbFaces = (indices.length / 3) | 0;
  38089. for (index = 0; index < nbFaces; index++) {
  38090. // get the indexes of the coordinates of each vertex of the facet
  38091. v1x = indices[index * 3] * 3;
  38092. v1y = v1x + 1;
  38093. v1z = v1x + 2;
  38094. v2x = indices[index * 3 + 1] * 3;
  38095. v2y = v2x + 1;
  38096. v2z = v2x + 2;
  38097. v3x = indices[index * 3 + 2] * 3;
  38098. v3y = v3x + 1;
  38099. v3z = v3x + 2;
  38100. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38101. p1p2y = positions[v1y] - positions[v2y];
  38102. p1p2z = positions[v1z] - positions[v2z];
  38103. p3p2x = positions[v3x] - positions[v2x];
  38104. p3p2y = positions[v3y] - positions[v2y];
  38105. p3p2z = positions[v3z] - positions[v2z];
  38106. // compute the face normal with the cross product
  38107. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38108. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38109. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38110. // normalize this normal and store it in the array facetData
  38111. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38112. length = (length === 0) ? 1.0 : length;
  38113. faceNormalx /= length;
  38114. faceNormaly /= length;
  38115. faceNormalz /= length;
  38116. if (computeFacetNormals && options) {
  38117. options.facetNormals[index].x = faceNormalx;
  38118. options.facetNormals[index].y = faceNormaly;
  38119. options.facetNormals[index].z = faceNormalz;
  38120. }
  38121. if (computeFacetPositions && options) {
  38122. // compute and the facet barycenter coordinates in the array facetPositions
  38123. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38124. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38125. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38126. }
  38127. if (computeFacetPartitioning && options) {
  38128. // store the facet indexes in arrays in the main facetPartitioning array :
  38129. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38130. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38131. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38132. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38133. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38134. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38135. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38136. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38137. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38138. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38139. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38140. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38141. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38142. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38143. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38144. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38145. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38146. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38147. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38148. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38149. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38150. // push each facet index in each block containing the vertex
  38151. options.facetPartitioning[block_idx_v1].push(index);
  38152. if (block_idx_v2 != block_idx_v1) {
  38153. options.facetPartitioning[block_idx_v2].push(index);
  38154. }
  38155. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38156. options.facetPartitioning[block_idx_v3].push(index);
  38157. }
  38158. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38159. options.facetPartitioning[block_idx_o].push(index);
  38160. }
  38161. }
  38162. if (computeDepthSort && options && options.facetPositions) {
  38163. var dsf = depthSortedFacets[index];
  38164. dsf.ind = index * 3;
  38165. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38166. }
  38167. // compute the normals anyway
  38168. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38169. normals[v1y] += faceNormaly;
  38170. normals[v1z] += faceNormalz;
  38171. normals[v2x] += faceNormalx;
  38172. normals[v2y] += faceNormaly;
  38173. normals[v2z] += faceNormalz;
  38174. normals[v3x] += faceNormalx;
  38175. normals[v3y] += faceNormaly;
  38176. normals[v3z] += faceNormalz;
  38177. }
  38178. // last normalization of each normal
  38179. for (index = 0; index < normals.length / 3; index++) {
  38180. faceNormalx = normals[index * 3];
  38181. faceNormaly = normals[index * 3 + 1];
  38182. faceNormalz = normals[index * 3 + 2];
  38183. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38184. length = (length === 0) ? 1.0 : length;
  38185. faceNormalx /= length;
  38186. faceNormaly /= length;
  38187. faceNormalz /= length;
  38188. normals[index * 3] = faceNormalx;
  38189. normals[index * 3 + 1] = faceNormaly;
  38190. normals[index * 3 + 2] = faceNormalz;
  38191. }
  38192. };
  38193. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38194. var li = indices.length;
  38195. var ln = normals.length;
  38196. var i;
  38197. var n;
  38198. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38199. switch (sideOrientation) {
  38200. case BABYLON.Mesh.FRONTSIDE:
  38201. // nothing changed
  38202. break;
  38203. case BABYLON.Mesh.BACKSIDE:
  38204. var tmp;
  38205. // indices
  38206. for (i = 0; i < li; i += 3) {
  38207. tmp = indices[i];
  38208. indices[i] = indices[i + 2];
  38209. indices[i + 2] = tmp;
  38210. }
  38211. // normals
  38212. for (n = 0; n < ln; n++) {
  38213. normals[n] = -normals[n];
  38214. }
  38215. break;
  38216. case BABYLON.Mesh.DOUBLESIDE:
  38217. // positions
  38218. var lp = positions.length;
  38219. var l = lp / 3;
  38220. for (var p = 0; p < lp; p++) {
  38221. positions[lp + p] = positions[p];
  38222. }
  38223. // indices
  38224. for (i = 0; i < li; i += 3) {
  38225. indices[i + li] = indices[i + 2] + l;
  38226. indices[i + 1 + li] = indices[i + 1] + l;
  38227. indices[i + 2 + li] = indices[i] + l;
  38228. }
  38229. // normals
  38230. for (n = 0; n < ln; n++) {
  38231. normals[ln + n] = -normals[n];
  38232. }
  38233. // uvs
  38234. var lu = uvs.length;
  38235. var u = 0;
  38236. for (u = 0; u < lu; u++) {
  38237. uvs[u + lu] = uvs[u];
  38238. }
  38239. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38240. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38241. u = 0;
  38242. for (i = 0; i < lu / 2; i++) {
  38243. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38244. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38245. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38246. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38247. u += 2;
  38248. }
  38249. break;
  38250. }
  38251. };
  38252. /**
  38253. * Applies VertexData created from the imported parameters to the geometry
  38254. * @param parsedVertexData the parsed data from an imported file
  38255. * @param geometry the geometry to apply the VertexData to
  38256. */
  38257. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38258. var vertexData = new VertexData();
  38259. // positions
  38260. var positions = parsedVertexData.positions;
  38261. if (positions) {
  38262. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38263. }
  38264. // normals
  38265. var normals = parsedVertexData.normals;
  38266. if (normals) {
  38267. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38268. }
  38269. // tangents
  38270. var tangents = parsedVertexData.tangents;
  38271. if (tangents) {
  38272. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38273. }
  38274. // uvs
  38275. var uvs = parsedVertexData.uvs;
  38276. if (uvs) {
  38277. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38278. }
  38279. // uv2s
  38280. var uv2s = parsedVertexData.uv2s;
  38281. if (uv2s) {
  38282. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38283. }
  38284. // uv3s
  38285. var uv3s = parsedVertexData.uv3s;
  38286. if (uv3s) {
  38287. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38288. }
  38289. // uv4s
  38290. var uv4s = parsedVertexData.uv4s;
  38291. if (uv4s) {
  38292. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38293. }
  38294. // uv5s
  38295. var uv5s = parsedVertexData.uv5s;
  38296. if (uv5s) {
  38297. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38298. }
  38299. // uv6s
  38300. var uv6s = parsedVertexData.uv6s;
  38301. if (uv6s) {
  38302. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38303. }
  38304. // colors
  38305. var colors = parsedVertexData.colors;
  38306. if (colors) {
  38307. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38308. }
  38309. // matricesIndices
  38310. var matricesIndices = parsedVertexData.matricesIndices;
  38311. if (matricesIndices) {
  38312. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38313. }
  38314. // matricesWeights
  38315. var matricesWeights = parsedVertexData.matricesWeights;
  38316. if (matricesWeights) {
  38317. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38318. }
  38319. // indices
  38320. var indices = parsedVertexData.indices;
  38321. if (indices) {
  38322. vertexData.indices = indices;
  38323. }
  38324. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38325. };
  38326. return VertexData;
  38327. }());
  38328. BABYLON.VertexData = VertexData;
  38329. })(BABYLON || (BABYLON = {}));
  38330. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38331. var BABYLON;
  38332. (function (BABYLON) {
  38333. /**
  38334. * Class used to store geometry data (vertex buffers + index buffer)
  38335. */
  38336. var Geometry = /** @class */ (function () {
  38337. /**
  38338. * Creates a new geometry
  38339. * @param id defines the unique ID
  38340. * @param scene defines the hosting scene
  38341. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38342. * @param updatable defines if geometry must be updatable (false by default)
  38343. * @param mesh defines the mesh that will be associated with the geometry
  38344. */
  38345. function Geometry(id, scene, vertexData, updatable, mesh) {
  38346. if (updatable === void 0) { updatable = false; }
  38347. if (mesh === void 0) { mesh = null; }
  38348. /**
  38349. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38350. */
  38351. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38352. this._totalVertices = 0;
  38353. this._isDisposed = false;
  38354. this._indexBufferIsUpdatable = false;
  38355. this.id = id;
  38356. this._engine = scene.getEngine();
  38357. this._meshes = [];
  38358. this._scene = scene;
  38359. //Init vertex buffer cache
  38360. this._vertexBuffers = {};
  38361. this._indices = [];
  38362. this._updatable = updatable;
  38363. // vertexData
  38364. if (vertexData) {
  38365. this.setAllVerticesData(vertexData, updatable);
  38366. }
  38367. else {
  38368. this._totalVertices = 0;
  38369. this._indices = [];
  38370. }
  38371. if (this._engine.getCaps().vertexArrayObject) {
  38372. this._vertexArrayObjects = {};
  38373. }
  38374. // applyToMesh
  38375. if (mesh) {
  38376. if (mesh.getClassName() === "LinesMesh") {
  38377. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38378. this._updateExtend();
  38379. }
  38380. this.applyToMesh(mesh);
  38381. mesh.computeWorldMatrix(true);
  38382. }
  38383. }
  38384. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38385. /**
  38386. * 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
  38387. */
  38388. get: function () {
  38389. return this._boundingBias;
  38390. },
  38391. /**
  38392. * 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
  38393. */
  38394. set: function (value) {
  38395. if (this._boundingBias && this._boundingBias.equals(value)) {
  38396. return;
  38397. }
  38398. this._boundingBias = value.clone();
  38399. this._updateBoundingInfo(true, null);
  38400. },
  38401. enumerable: true,
  38402. configurable: true
  38403. });
  38404. /**
  38405. * Static function used to attach a new empty geometry to a mesh
  38406. * @param mesh defines the mesh to attach the geometry to
  38407. * @returns the new {BABYLON.Geometry}
  38408. */
  38409. Geometry.CreateGeometryForMesh = function (mesh) {
  38410. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38411. geometry.applyToMesh(mesh);
  38412. return geometry;
  38413. };
  38414. Object.defineProperty(Geometry.prototype, "extend", {
  38415. /**
  38416. * Gets the current extend of the geometry
  38417. */
  38418. get: function () {
  38419. return this._extend;
  38420. },
  38421. enumerable: true,
  38422. configurable: true
  38423. });
  38424. /**
  38425. * Gets the hosting scene
  38426. * @returns the hosting {BABYLON.Scene}
  38427. */
  38428. Geometry.prototype.getScene = function () {
  38429. return this._scene;
  38430. };
  38431. /**
  38432. * Gets the hosting engine
  38433. * @returns the hosting {BABYLON.Engine}
  38434. */
  38435. Geometry.prototype.getEngine = function () {
  38436. return this._engine;
  38437. };
  38438. /**
  38439. * Defines if the geometry is ready to use
  38440. * @returns true if the geometry is ready to be used
  38441. */
  38442. Geometry.prototype.isReady = function () {
  38443. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38444. };
  38445. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38446. /**
  38447. * Gets a value indicating that the geometry should not be serialized
  38448. */
  38449. get: function () {
  38450. for (var index = 0; index < this._meshes.length; index++) {
  38451. if (!this._meshes[index].doNotSerialize) {
  38452. return false;
  38453. }
  38454. }
  38455. return true;
  38456. },
  38457. enumerable: true,
  38458. configurable: true
  38459. });
  38460. /** @hidden */
  38461. Geometry.prototype._rebuild = function () {
  38462. if (this._vertexArrayObjects) {
  38463. this._vertexArrayObjects = {};
  38464. }
  38465. // Index buffer
  38466. if (this._meshes.length !== 0 && this._indices) {
  38467. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38468. }
  38469. // Vertex buffers
  38470. for (var key in this._vertexBuffers) {
  38471. var vertexBuffer = this._vertexBuffers[key];
  38472. vertexBuffer._rebuild();
  38473. }
  38474. };
  38475. /**
  38476. * Affects all geometry data in one call
  38477. * @param vertexData defines the geometry data
  38478. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38479. */
  38480. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38481. vertexData.applyToGeometry(this, updatable);
  38482. this.notifyUpdate();
  38483. };
  38484. /**
  38485. * Set specific vertex data
  38486. * @param kind defines the data kind (Position, normal, etc...)
  38487. * @param data defines the vertex data to use
  38488. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38489. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38490. */
  38491. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38492. if (updatable === void 0) { updatable = false; }
  38493. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38494. this.setVerticesBuffer(buffer);
  38495. };
  38496. /**
  38497. * Removes a specific vertex data
  38498. * @param kind defines the data kind (Position, normal, etc...)
  38499. */
  38500. Geometry.prototype.removeVerticesData = function (kind) {
  38501. if (this._vertexBuffers[kind]) {
  38502. this._vertexBuffers[kind].dispose();
  38503. delete this._vertexBuffers[kind];
  38504. }
  38505. };
  38506. /**
  38507. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38508. * @param buffer defines the vertex buffer to use
  38509. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38510. */
  38511. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38512. if (totalVertices === void 0) { totalVertices = null; }
  38513. var kind = buffer.getKind();
  38514. if (this._vertexBuffers[kind]) {
  38515. this._vertexBuffers[kind].dispose();
  38516. }
  38517. this._vertexBuffers[kind] = buffer;
  38518. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38519. var data = buffer.getData();
  38520. if (totalVertices != null) {
  38521. this._totalVertices = totalVertices;
  38522. }
  38523. else {
  38524. if (data != null) {
  38525. this._totalVertices = data.length / (buffer.byteStride / 4);
  38526. }
  38527. }
  38528. this._updateExtend(data);
  38529. this._resetPointsArrayCache();
  38530. var meshes = this._meshes;
  38531. var numOfMeshes = meshes.length;
  38532. for (var index = 0; index < numOfMeshes; index++) {
  38533. var mesh = meshes[index];
  38534. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38535. mesh._createGlobalSubMesh(false);
  38536. mesh.computeWorldMatrix(true);
  38537. }
  38538. }
  38539. this.notifyUpdate(kind);
  38540. if (this._vertexArrayObjects) {
  38541. this._disposeVertexArrayObjects();
  38542. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38543. }
  38544. };
  38545. /**
  38546. * Update a specific vertex buffer
  38547. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38548. * It will do nothing if the buffer is not updatable
  38549. * @param kind defines the data kind (Position, normal, etc...)
  38550. * @param data defines the data to use
  38551. * @param offset defines the offset in the target buffer where to store the data
  38552. * @param useBytes set to true if the offset is in bytes
  38553. */
  38554. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38555. if (useBytes === void 0) { useBytes = false; }
  38556. var vertexBuffer = this.getVertexBuffer(kind);
  38557. if (!vertexBuffer) {
  38558. return;
  38559. }
  38560. vertexBuffer.updateDirectly(data, offset, useBytes);
  38561. this.notifyUpdate(kind);
  38562. };
  38563. /**
  38564. * Update a specific vertex buffer
  38565. * This function will create a new buffer if the current one is not updatable
  38566. * @param kind defines the data kind (Position, normal, etc...)
  38567. * @param data defines the data to use
  38568. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38569. */
  38570. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38571. if (updateExtends === void 0) { updateExtends = false; }
  38572. var vertexBuffer = this.getVertexBuffer(kind);
  38573. if (!vertexBuffer) {
  38574. return;
  38575. }
  38576. vertexBuffer.update(data);
  38577. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38578. this._updateBoundingInfo(updateExtends, data);
  38579. }
  38580. this.notifyUpdate(kind);
  38581. };
  38582. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38583. if (updateExtends) {
  38584. this._updateExtend(data);
  38585. }
  38586. var meshes = this._meshes;
  38587. var numOfMeshes = meshes.length;
  38588. this._resetPointsArrayCache();
  38589. for (var index = 0; index < numOfMeshes; index++) {
  38590. var mesh = meshes[index];
  38591. if (updateExtends) {
  38592. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38593. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38594. var subMesh = mesh.subMeshes[subIndex];
  38595. subMesh.refreshBoundingInfo();
  38596. }
  38597. }
  38598. }
  38599. };
  38600. /** @hidden */
  38601. Geometry.prototype._bind = function (effect, indexToBind) {
  38602. if (!effect) {
  38603. return;
  38604. }
  38605. if (indexToBind === undefined) {
  38606. indexToBind = this._indexBuffer;
  38607. }
  38608. var vbs = this.getVertexBuffers();
  38609. if (!vbs) {
  38610. return;
  38611. }
  38612. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38613. this._engine.bindBuffers(vbs, indexToBind, effect);
  38614. return;
  38615. }
  38616. // Using VAO
  38617. if (!this._vertexArrayObjects[effect.key]) {
  38618. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38619. }
  38620. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38621. };
  38622. /**
  38623. * Gets total number of vertices
  38624. * @returns the total number of vertices
  38625. */
  38626. Geometry.prototype.getTotalVertices = function () {
  38627. if (!this.isReady()) {
  38628. return 0;
  38629. }
  38630. return this._totalVertices;
  38631. };
  38632. /**
  38633. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38634. * @param kind defines the data kind (Position, normal, etc...)
  38635. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38636. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38637. * @returns a float array containing vertex data
  38638. */
  38639. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38640. var vertexBuffer = this.getVertexBuffer(kind);
  38641. if (!vertexBuffer) {
  38642. return null;
  38643. }
  38644. var data = vertexBuffer.getData();
  38645. if (!data) {
  38646. return null;
  38647. }
  38648. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38649. var count = this._totalVertices * vertexBuffer.getSize();
  38650. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38651. var copy_1 = new Array(count);
  38652. vertexBuffer.forEach(count, function (value, index) {
  38653. copy_1[index] = value;
  38654. });
  38655. return copy_1;
  38656. }
  38657. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38658. if (data instanceof Array) {
  38659. var offset = vertexBuffer.byteOffset / 4;
  38660. return BABYLON.Tools.Slice(data, offset, offset + count);
  38661. }
  38662. else if (data instanceof ArrayBuffer) {
  38663. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38664. }
  38665. else {
  38666. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38667. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38668. var result = new Float32Array(count);
  38669. var source = new Float32Array(data.buffer, offset, count);
  38670. result.set(source);
  38671. return result;
  38672. }
  38673. return new Float32Array(data.buffer, offset, count);
  38674. }
  38675. }
  38676. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38677. return BABYLON.Tools.Slice(data);
  38678. }
  38679. return data;
  38680. };
  38681. /**
  38682. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38683. * @param kind defines the data kind (Position, normal, etc...)
  38684. * @returns true if the vertex buffer with the specified kind is updatable
  38685. */
  38686. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38687. var vb = this._vertexBuffers[kind];
  38688. if (!vb) {
  38689. return false;
  38690. }
  38691. return vb.isUpdatable();
  38692. };
  38693. /**
  38694. * Gets a specific vertex buffer
  38695. * @param kind defines the data kind (Position, normal, etc...)
  38696. * @returns a {BABYLON.VertexBuffer}
  38697. */
  38698. Geometry.prototype.getVertexBuffer = function (kind) {
  38699. if (!this.isReady()) {
  38700. return null;
  38701. }
  38702. return this._vertexBuffers[kind];
  38703. };
  38704. /**
  38705. * Returns all vertex buffers
  38706. * @return an object holding all vertex buffers indexed by kind
  38707. */
  38708. Geometry.prototype.getVertexBuffers = function () {
  38709. if (!this.isReady()) {
  38710. return null;
  38711. }
  38712. return this._vertexBuffers;
  38713. };
  38714. /**
  38715. * Gets a boolean indicating if specific vertex buffer is present
  38716. * @param kind defines the data kind (Position, normal, etc...)
  38717. * @returns true if data is present
  38718. */
  38719. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38720. if (!this._vertexBuffers) {
  38721. if (this._delayInfo) {
  38722. return this._delayInfo.indexOf(kind) !== -1;
  38723. }
  38724. return false;
  38725. }
  38726. return this._vertexBuffers[kind] !== undefined;
  38727. };
  38728. /**
  38729. * Gets a list of all attached data kinds (Position, normal, etc...)
  38730. * @returns a list of string containing all kinds
  38731. */
  38732. Geometry.prototype.getVerticesDataKinds = function () {
  38733. var result = [];
  38734. var kind;
  38735. if (!this._vertexBuffers && this._delayInfo) {
  38736. for (kind in this._delayInfo) {
  38737. result.push(kind);
  38738. }
  38739. }
  38740. else {
  38741. for (kind in this._vertexBuffers) {
  38742. result.push(kind);
  38743. }
  38744. }
  38745. return result;
  38746. };
  38747. /**
  38748. * Update index buffer
  38749. * @param indices defines the indices to store in the index buffer
  38750. * @param offset defines the offset in the target buffer where to store the data
  38751. */
  38752. Geometry.prototype.updateIndices = function (indices, offset) {
  38753. if (!this._indexBuffer) {
  38754. return;
  38755. }
  38756. if (!this._indexBufferIsUpdatable) {
  38757. this.setIndices(indices, null, true);
  38758. }
  38759. else {
  38760. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38761. }
  38762. };
  38763. /**
  38764. * Creates a new index buffer
  38765. * @param indices defines the indices to store in the index buffer
  38766. * @param totalVertices defines the total number of vertices (could be null)
  38767. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38768. */
  38769. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38770. if (totalVertices === void 0) { totalVertices = null; }
  38771. if (updatable === void 0) { updatable = false; }
  38772. if (this._indexBuffer) {
  38773. this._engine._releaseBuffer(this._indexBuffer);
  38774. }
  38775. this._disposeVertexArrayObjects();
  38776. this._indices = indices;
  38777. this._indexBufferIsUpdatable = updatable;
  38778. if (this._meshes.length !== 0 && this._indices) {
  38779. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38780. }
  38781. if (totalVertices != undefined) { // including null and undefined
  38782. this._totalVertices = totalVertices;
  38783. }
  38784. var meshes = this._meshes;
  38785. var numOfMeshes = meshes.length;
  38786. for (var index = 0; index < numOfMeshes; index++) {
  38787. meshes[index]._createGlobalSubMesh(true);
  38788. }
  38789. this.notifyUpdate();
  38790. };
  38791. /**
  38792. * Return the total number of indices
  38793. * @returns the total number of indices
  38794. */
  38795. Geometry.prototype.getTotalIndices = function () {
  38796. if (!this.isReady()) {
  38797. return 0;
  38798. }
  38799. return this._indices.length;
  38800. };
  38801. /**
  38802. * Gets the index buffer array
  38803. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38804. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38805. * @returns the index buffer array
  38806. */
  38807. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38808. if (!this.isReady()) {
  38809. return null;
  38810. }
  38811. var orig = this._indices;
  38812. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  38813. return orig;
  38814. }
  38815. else {
  38816. var len = orig.length;
  38817. var copy = [];
  38818. for (var i = 0; i < len; i++) {
  38819. copy.push(orig[i]);
  38820. }
  38821. return copy;
  38822. }
  38823. };
  38824. /**
  38825. * Gets the index buffer
  38826. * @return the index buffer
  38827. */
  38828. Geometry.prototype.getIndexBuffer = function () {
  38829. if (!this.isReady()) {
  38830. return null;
  38831. }
  38832. return this._indexBuffer;
  38833. };
  38834. /** @hidden */
  38835. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38836. if (effect === void 0) { effect = null; }
  38837. if (!effect || !this._vertexArrayObjects) {
  38838. return;
  38839. }
  38840. if (this._vertexArrayObjects[effect.key]) {
  38841. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38842. delete this._vertexArrayObjects[effect.key];
  38843. }
  38844. };
  38845. /**
  38846. * Release the associated resources for a specific mesh
  38847. * @param mesh defines the source mesh
  38848. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38849. */
  38850. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38851. var meshes = this._meshes;
  38852. var index = meshes.indexOf(mesh);
  38853. if (index === -1) {
  38854. return;
  38855. }
  38856. meshes.splice(index, 1);
  38857. mesh._geometry = null;
  38858. if (meshes.length === 0 && shouldDispose) {
  38859. this.dispose();
  38860. }
  38861. };
  38862. /**
  38863. * Apply current geometry to a given mesh
  38864. * @param mesh defines the mesh to apply geometry to
  38865. */
  38866. Geometry.prototype.applyToMesh = function (mesh) {
  38867. if (mesh._geometry === this) {
  38868. return;
  38869. }
  38870. var previousGeometry = mesh._geometry;
  38871. if (previousGeometry) {
  38872. previousGeometry.releaseForMesh(mesh);
  38873. }
  38874. var meshes = this._meshes;
  38875. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38876. mesh._geometry = this;
  38877. this._scene.pushGeometry(this);
  38878. meshes.push(mesh);
  38879. if (this.isReady()) {
  38880. this._applyToMesh(mesh);
  38881. }
  38882. else {
  38883. mesh._boundingInfo = this._boundingInfo;
  38884. }
  38885. };
  38886. Geometry.prototype._updateExtend = function (data) {
  38887. if (data === void 0) { data = null; }
  38888. if (!data) {
  38889. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38890. }
  38891. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38892. };
  38893. Geometry.prototype._applyToMesh = function (mesh) {
  38894. var numOfMeshes = this._meshes.length;
  38895. // vertexBuffers
  38896. for (var kind in this._vertexBuffers) {
  38897. if (numOfMeshes === 1) {
  38898. this._vertexBuffers[kind].create();
  38899. }
  38900. var buffer = this._vertexBuffers[kind].getBuffer();
  38901. if (buffer)
  38902. buffer.references = numOfMeshes;
  38903. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38904. if (!this._extend) {
  38905. this._updateExtend();
  38906. }
  38907. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38908. mesh._createGlobalSubMesh(false);
  38909. //bounding info was just created again, world matrix should be applied again.
  38910. mesh._updateBoundingInfo();
  38911. }
  38912. }
  38913. // indexBuffer
  38914. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38915. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38916. }
  38917. if (this._indexBuffer) {
  38918. this._indexBuffer.references = numOfMeshes;
  38919. }
  38920. };
  38921. Geometry.prototype.notifyUpdate = function (kind) {
  38922. if (this.onGeometryUpdated) {
  38923. this.onGeometryUpdated(this, kind);
  38924. }
  38925. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38926. var mesh = _a[_i];
  38927. mesh._markSubMeshesAsAttributesDirty();
  38928. }
  38929. };
  38930. /**
  38931. * Load the geometry if it was flagged as delay loaded
  38932. * @param scene defines the hosting scene
  38933. * @param onLoaded defines a callback called when the geometry is loaded
  38934. */
  38935. Geometry.prototype.load = function (scene, onLoaded) {
  38936. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38937. return;
  38938. }
  38939. if (this.isReady()) {
  38940. if (onLoaded) {
  38941. onLoaded();
  38942. }
  38943. return;
  38944. }
  38945. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38946. this._queueLoad(scene, onLoaded);
  38947. };
  38948. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38949. var _this = this;
  38950. if (!this.delayLoadingFile) {
  38951. return;
  38952. }
  38953. scene._addPendingData(this);
  38954. scene._loadFile(this.delayLoadingFile, function (data) {
  38955. if (!_this._delayLoadingFunction) {
  38956. return;
  38957. }
  38958. _this._delayLoadingFunction(JSON.parse(data), _this);
  38959. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38960. _this._delayInfo = [];
  38961. scene._removePendingData(_this);
  38962. var meshes = _this._meshes;
  38963. var numOfMeshes = meshes.length;
  38964. for (var index = 0; index < numOfMeshes; index++) {
  38965. _this._applyToMesh(meshes[index]);
  38966. }
  38967. if (onLoaded) {
  38968. onLoaded();
  38969. }
  38970. }, undefined, true);
  38971. };
  38972. /**
  38973. * Invert the geometry to move from a right handed system to a left handed one.
  38974. */
  38975. Geometry.prototype.toLeftHanded = function () {
  38976. // Flip faces
  38977. var tIndices = this.getIndices(false);
  38978. if (tIndices != null && tIndices.length > 0) {
  38979. for (var i = 0; i < tIndices.length; i += 3) {
  38980. var tTemp = tIndices[i + 0];
  38981. tIndices[i + 0] = tIndices[i + 2];
  38982. tIndices[i + 2] = tTemp;
  38983. }
  38984. this.setIndices(tIndices);
  38985. }
  38986. // Negate position.z
  38987. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38988. if (tPositions != null && tPositions.length > 0) {
  38989. for (var i = 0; i < tPositions.length; i += 3) {
  38990. tPositions[i + 2] = -tPositions[i + 2];
  38991. }
  38992. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38993. }
  38994. // Negate normal.z
  38995. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38996. if (tNormals != null && tNormals.length > 0) {
  38997. for (var i = 0; i < tNormals.length; i += 3) {
  38998. tNormals[i + 2] = -tNormals[i + 2];
  38999. }
  39000. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39001. }
  39002. };
  39003. // Cache
  39004. /** @hidden */
  39005. Geometry.prototype._resetPointsArrayCache = function () {
  39006. this._positions = null;
  39007. };
  39008. /** @hidden */
  39009. Geometry.prototype._generatePointsArray = function () {
  39010. if (this._positions)
  39011. return true;
  39012. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39013. if (!data || data.length === 0) {
  39014. return false;
  39015. }
  39016. this._positions = [];
  39017. for (var index = 0; index < data.length; index += 3) {
  39018. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39019. }
  39020. return true;
  39021. };
  39022. /**
  39023. * Gets a value indicating if the geometry is disposed
  39024. * @returns true if the geometry was disposed
  39025. */
  39026. Geometry.prototype.isDisposed = function () {
  39027. return this._isDisposed;
  39028. };
  39029. Geometry.prototype._disposeVertexArrayObjects = function () {
  39030. if (this._vertexArrayObjects) {
  39031. for (var kind in this._vertexArrayObjects) {
  39032. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39033. }
  39034. this._vertexArrayObjects = {};
  39035. }
  39036. };
  39037. /**
  39038. * Free all associated resources
  39039. */
  39040. Geometry.prototype.dispose = function () {
  39041. var meshes = this._meshes;
  39042. var numOfMeshes = meshes.length;
  39043. var index;
  39044. for (index = 0; index < numOfMeshes; index++) {
  39045. this.releaseForMesh(meshes[index]);
  39046. }
  39047. this._meshes = [];
  39048. this._disposeVertexArrayObjects();
  39049. for (var kind in this._vertexBuffers) {
  39050. this._vertexBuffers[kind].dispose();
  39051. }
  39052. this._vertexBuffers = {};
  39053. this._totalVertices = 0;
  39054. if (this._indexBuffer) {
  39055. this._engine._releaseBuffer(this._indexBuffer);
  39056. }
  39057. this._indexBuffer = null;
  39058. this._indices = [];
  39059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39060. this.delayLoadingFile = null;
  39061. this._delayLoadingFunction = null;
  39062. this._delayInfo = [];
  39063. this._boundingInfo = null;
  39064. this._scene.removeGeometry(this);
  39065. this._isDisposed = true;
  39066. };
  39067. /**
  39068. * Clone the current geometry into a new geometry
  39069. * @param id defines the unique ID of the new geometry
  39070. * @returns a new geometry object
  39071. */
  39072. Geometry.prototype.copy = function (id) {
  39073. var vertexData = new BABYLON.VertexData();
  39074. vertexData.indices = [];
  39075. var indices = this.getIndices();
  39076. if (indices) {
  39077. for (var index = 0; index < indices.length; index++) {
  39078. vertexData.indices.push(indices[index]);
  39079. }
  39080. }
  39081. var updatable = false;
  39082. var stopChecking = false;
  39083. var kind;
  39084. for (kind in this._vertexBuffers) {
  39085. // using slice() to make a copy of the array and not just reference it
  39086. var data = this.getVerticesData(kind);
  39087. if (data instanceof Float32Array) {
  39088. vertexData.set(new Float32Array(data), kind);
  39089. }
  39090. else {
  39091. vertexData.set(data.slice(0), kind);
  39092. }
  39093. if (!stopChecking) {
  39094. var vb = this.getVertexBuffer(kind);
  39095. if (vb) {
  39096. updatable = vb.isUpdatable();
  39097. stopChecking = !updatable;
  39098. }
  39099. }
  39100. }
  39101. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39102. geometry.delayLoadState = this.delayLoadState;
  39103. geometry.delayLoadingFile = this.delayLoadingFile;
  39104. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39105. for (kind in this._delayInfo) {
  39106. geometry._delayInfo = geometry._delayInfo || [];
  39107. geometry._delayInfo.push(kind);
  39108. }
  39109. // Bounding info
  39110. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39111. return geometry;
  39112. };
  39113. /**
  39114. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39115. * @return a JSON representation of the current geometry data (without the vertices data)
  39116. */
  39117. Geometry.prototype.serialize = function () {
  39118. var serializationObject = {};
  39119. serializationObject.id = this.id;
  39120. serializationObject.updatable = this._updatable;
  39121. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39122. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39123. }
  39124. return serializationObject;
  39125. };
  39126. Geometry.prototype.toNumberArray = function (origin) {
  39127. if (Array.isArray(origin)) {
  39128. return origin;
  39129. }
  39130. else {
  39131. return Array.prototype.slice.call(origin);
  39132. }
  39133. };
  39134. /**
  39135. * Serialize all vertices data into a JSON oject
  39136. * @returns a JSON representation of the current geometry data
  39137. */
  39138. Geometry.prototype.serializeVerticeData = function () {
  39139. var serializationObject = this.serialize();
  39140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39141. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39142. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39143. serializationObject.positions._updatable = true;
  39144. }
  39145. }
  39146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39147. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39148. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39149. serializationObject.normals._updatable = true;
  39150. }
  39151. }
  39152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39153. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39154. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39155. serializationObject.tangets._updatable = true;
  39156. }
  39157. }
  39158. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39159. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39160. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39161. serializationObject.uvs._updatable = true;
  39162. }
  39163. }
  39164. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39165. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39166. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39167. serializationObject.uv2s._updatable = true;
  39168. }
  39169. }
  39170. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39171. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39172. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39173. serializationObject.uv3s._updatable = true;
  39174. }
  39175. }
  39176. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39177. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39178. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39179. serializationObject.uv4s._updatable = true;
  39180. }
  39181. }
  39182. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39183. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39184. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39185. serializationObject.uv5s._updatable = true;
  39186. }
  39187. }
  39188. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39189. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39190. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39191. serializationObject.uv6s._updatable = true;
  39192. }
  39193. }
  39194. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39195. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39196. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39197. serializationObject.colors._updatable = true;
  39198. }
  39199. }
  39200. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39201. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39202. serializationObject.matricesIndices._isExpanded = true;
  39203. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39204. serializationObject.matricesIndices._updatable = true;
  39205. }
  39206. }
  39207. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39208. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39209. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39210. serializationObject.matricesWeights._updatable = true;
  39211. }
  39212. }
  39213. serializationObject.indices = this.toNumberArray(this.getIndices());
  39214. return serializationObject;
  39215. };
  39216. // Statics
  39217. /**
  39218. * Extracts a clone of a mesh geometry
  39219. * @param mesh defines the source mesh
  39220. * @param id defines the unique ID of the new geometry object
  39221. * @returns the new geometry object
  39222. */
  39223. Geometry.ExtractFromMesh = function (mesh, id) {
  39224. var geometry = mesh._geometry;
  39225. if (!geometry) {
  39226. return null;
  39227. }
  39228. return geometry.copy(id);
  39229. };
  39230. /**
  39231. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39232. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39233. * Be aware Math.random() could cause collisions, but:
  39234. * "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"
  39235. * @returns a string containing a new GUID
  39236. */
  39237. Geometry.RandomId = function () {
  39238. return BABYLON.Tools.RandomId();
  39239. };
  39240. /** @hidden */
  39241. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39242. var scene = mesh.getScene();
  39243. // Geometry
  39244. var geometryId = parsedGeometry.geometryId;
  39245. if (geometryId) {
  39246. var geometry = scene.getGeometryByID(geometryId);
  39247. if (geometry) {
  39248. geometry.applyToMesh(mesh);
  39249. }
  39250. }
  39251. else if (parsedGeometry instanceof ArrayBuffer) {
  39252. var binaryInfo = mesh._binaryInfo;
  39253. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39254. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39255. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39256. }
  39257. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39258. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39259. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39260. }
  39261. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39262. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39263. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39264. }
  39265. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39266. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39267. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39268. }
  39269. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39270. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39271. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39272. }
  39273. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39274. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39275. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39276. }
  39277. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39278. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39279. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39280. }
  39281. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39282. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39283. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39284. }
  39285. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39286. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39287. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39288. }
  39289. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39290. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39291. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39292. }
  39293. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39294. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39295. var floatIndices = [];
  39296. for (var i = 0; i < matricesIndicesData.length; i++) {
  39297. var index = matricesIndicesData[i];
  39298. floatIndices.push(index & 0x000000FF);
  39299. floatIndices.push((index & 0x0000FF00) >> 8);
  39300. floatIndices.push((index & 0x00FF0000) >> 16);
  39301. floatIndices.push(index >> 24);
  39302. }
  39303. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39304. }
  39305. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39306. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39307. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39308. }
  39309. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39310. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39311. mesh.setIndices(indicesData, null);
  39312. }
  39313. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39314. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39315. mesh.subMeshes = [];
  39316. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39317. var materialIndex = subMeshesData[(i * 5) + 0];
  39318. var verticesStart = subMeshesData[(i * 5) + 1];
  39319. var verticesCount = subMeshesData[(i * 5) + 2];
  39320. var indexStart = subMeshesData[(i * 5) + 3];
  39321. var indexCount = subMeshesData[(i * 5) + 4];
  39322. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39323. }
  39324. }
  39325. }
  39326. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39327. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39328. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39329. if (parsedGeometry.tangents) {
  39330. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39331. }
  39332. if (parsedGeometry.uvs) {
  39333. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39334. }
  39335. if (parsedGeometry.uvs2) {
  39336. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39337. }
  39338. if (parsedGeometry.uvs3) {
  39339. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39340. }
  39341. if (parsedGeometry.uvs4) {
  39342. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39343. }
  39344. if (parsedGeometry.uvs5) {
  39345. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39346. }
  39347. if (parsedGeometry.uvs6) {
  39348. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39349. }
  39350. if (parsedGeometry.colors) {
  39351. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39352. }
  39353. if (parsedGeometry.matricesIndices) {
  39354. if (!parsedGeometry.matricesIndices._isExpanded) {
  39355. var floatIndices = [];
  39356. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39357. var matricesIndex = parsedGeometry.matricesIndices[i];
  39358. floatIndices.push(matricesIndex & 0x000000FF);
  39359. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39360. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39361. floatIndices.push(matricesIndex >> 24);
  39362. }
  39363. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39364. }
  39365. else {
  39366. delete parsedGeometry.matricesIndices._isExpanded;
  39367. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39368. }
  39369. }
  39370. if (parsedGeometry.matricesIndicesExtra) {
  39371. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39372. var floatIndices = [];
  39373. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39374. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39375. floatIndices.push(matricesIndex & 0x000000FF);
  39376. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39377. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39378. floatIndices.push(matricesIndex >> 24);
  39379. }
  39380. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39381. }
  39382. else {
  39383. delete parsedGeometry.matricesIndices._isExpanded;
  39384. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39385. }
  39386. }
  39387. if (parsedGeometry.matricesWeights) {
  39388. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39389. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39390. }
  39391. if (parsedGeometry.matricesWeightsExtra) {
  39392. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39393. }
  39394. mesh.setIndices(parsedGeometry.indices, null);
  39395. }
  39396. // SubMeshes
  39397. if (parsedGeometry.subMeshes) {
  39398. mesh.subMeshes = [];
  39399. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39400. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39401. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39402. }
  39403. }
  39404. // Flat shading
  39405. if (mesh._shouldGenerateFlatShading) {
  39406. mesh.convertToFlatShadedMesh();
  39407. delete mesh._shouldGenerateFlatShading;
  39408. }
  39409. // Update
  39410. mesh.computeWorldMatrix(true);
  39411. scene.onMeshImportedObservable.notifyObservers(mesh);
  39412. };
  39413. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39414. var epsilon = 1e-3;
  39415. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39416. return;
  39417. }
  39418. var noInfluenceBoneIndex = 0.0;
  39419. if (parsedGeometry.skeletonId > -1) {
  39420. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39421. if (!skeleton) {
  39422. return;
  39423. }
  39424. noInfluenceBoneIndex = skeleton.bones.length;
  39425. }
  39426. else {
  39427. return;
  39428. }
  39429. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39430. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39431. var matricesWeights = parsedGeometry.matricesWeights;
  39432. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39433. var influencers = parsedGeometry.numBoneInfluencer;
  39434. var size = matricesWeights.length;
  39435. for (var i = 0; i < size; i += 4) {
  39436. var weight = 0.0;
  39437. var firstZeroWeight = -1;
  39438. for (var j = 0; j < 4; j++) {
  39439. var w = matricesWeights[i + j];
  39440. weight += w;
  39441. if (w < epsilon && firstZeroWeight < 0) {
  39442. firstZeroWeight = j;
  39443. }
  39444. }
  39445. if (matricesWeightsExtra) {
  39446. for (var j = 0; j < 4; j++) {
  39447. var w = matricesWeightsExtra[i + j];
  39448. weight += w;
  39449. if (w < epsilon && firstZeroWeight < 0) {
  39450. firstZeroWeight = j + 4;
  39451. }
  39452. }
  39453. }
  39454. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39455. firstZeroWeight = influencers - 1;
  39456. }
  39457. if (weight > epsilon) {
  39458. var mweight = 1.0 / weight;
  39459. for (var j = 0; j < 4; j++) {
  39460. matricesWeights[i + j] *= mweight;
  39461. }
  39462. if (matricesWeightsExtra) {
  39463. for (var j = 0; j < 4; j++) {
  39464. matricesWeightsExtra[i + j] *= mweight;
  39465. }
  39466. }
  39467. }
  39468. else {
  39469. if (firstZeroWeight >= 4) {
  39470. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39471. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39472. }
  39473. else {
  39474. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39475. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39476. }
  39477. }
  39478. }
  39479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39480. if (parsedGeometry.matricesWeightsExtra) {
  39481. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39482. }
  39483. };
  39484. /**
  39485. * Create a new geometry from persisted data (Using .babylon file format)
  39486. * @param parsedVertexData defines the persisted data
  39487. * @param scene defines the hosting scene
  39488. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39489. * @returns the new geometry object
  39490. */
  39491. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39492. if (scene.getGeometryByID(parsedVertexData.id)) {
  39493. return null; // null since geometry could be something else than a box...
  39494. }
  39495. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39496. if (BABYLON.Tags) {
  39497. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39498. }
  39499. if (parsedVertexData.delayLoadingFile) {
  39500. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39501. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39502. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39503. geometry._delayInfo = [];
  39504. if (parsedVertexData.hasUVs) {
  39505. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39506. }
  39507. if (parsedVertexData.hasUVs2) {
  39508. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39509. }
  39510. if (parsedVertexData.hasUVs3) {
  39511. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39512. }
  39513. if (parsedVertexData.hasUVs4) {
  39514. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39515. }
  39516. if (parsedVertexData.hasUVs5) {
  39517. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39518. }
  39519. if (parsedVertexData.hasUVs6) {
  39520. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39521. }
  39522. if (parsedVertexData.hasColors) {
  39523. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39524. }
  39525. if (parsedVertexData.hasMatricesIndices) {
  39526. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39527. }
  39528. if (parsedVertexData.hasMatricesWeights) {
  39529. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39530. }
  39531. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39532. }
  39533. else {
  39534. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39535. }
  39536. scene.pushGeometry(geometry, true);
  39537. return geometry;
  39538. };
  39539. return Geometry;
  39540. }());
  39541. BABYLON.Geometry = Geometry;
  39542. // Primitives
  39543. /// Abstract class
  39544. /**
  39545. * Abstract class used to provide common services for all typed geometries
  39546. * @hidden
  39547. */
  39548. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39549. __extends(_PrimitiveGeometry, _super);
  39550. /**
  39551. * Creates a new typed geometry
  39552. * @param id defines the unique ID of the geometry
  39553. * @param scene defines the hosting scene
  39554. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39555. * @param mesh defines the hosting mesh (can be null)
  39556. */
  39557. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39558. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39559. if (mesh === void 0) { mesh = null; }
  39560. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39561. _this._canBeRegenerated = _canBeRegenerated;
  39562. _this._beingRegenerated = true;
  39563. _this.regenerate();
  39564. _this._beingRegenerated = false;
  39565. return _this;
  39566. }
  39567. /**
  39568. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39569. * @returns true if the geometry can be regenerated
  39570. */
  39571. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39572. return this._canBeRegenerated;
  39573. };
  39574. /**
  39575. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39576. */
  39577. _PrimitiveGeometry.prototype.regenerate = function () {
  39578. if (!this._canBeRegenerated) {
  39579. return;
  39580. }
  39581. this._beingRegenerated = true;
  39582. this.setAllVerticesData(this._regenerateVertexData(), false);
  39583. this._beingRegenerated = false;
  39584. };
  39585. /**
  39586. * Clone the geometry
  39587. * @param id defines the unique ID of the new geometry
  39588. * @returns the new geometry
  39589. */
  39590. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39591. return _super.prototype.copy.call(this, id);
  39592. };
  39593. // overrides
  39594. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39595. if (!this._beingRegenerated) {
  39596. return;
  39597. }
  39598. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39599. };
  39600. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39601. if (!this._beingRegenerated) {
  39602. return;
  39603. }
  39604. _super.prototype.setVerticesData.call(this, kind, data, false);
  39605. };
  39606. // to override
  39607. /** @hidden */
  39608. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39609. throw new Error("Abstract method");
  39610. };
  39611. _PrimitiveGeometry.prototype.copy = function (id) {
  39612. throw new Error("Must be overriden in sub-classes.");
  39613. };
  39614. _PrimitiveGeometry.prototype.serialize = function () {
  39615. var serializationObject = _super.prototype.serialize.call(this);
  39616. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39617. return serializationObject;
  39618. };
  39619. return _PrimitiveGeometry;
  39620. }(Geometry));
  39621. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39622. /**
  39623. * Creates a ribbon geometry
  39624. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39625. */
  39626. var RibbonGeometry = /** @class */ (function (_super) {
  39627. __extends(RibbonGeometry, _super);
  39628. /**
  39629. * Creates a ribbon geometry
  39630. * @param id defines the unique ID of the geometry
  39631. * @param scene defines the hosting scene
  39632. * @param pathArray defines the array of paths to use
  39633. * @param closeArray defines if the last path and the first path must be joined
  39634. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39635. * @param offset defines the offset between points
  39636. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39637. * @param mesh defines the hosting mesh (can be null)
  39638. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39639. */
  39640. function RibbonGeometry(id, scene,
  39641. /**
  39642. * Defines the array of paths to use
  39643. */
  39644. pathArray,
  39645. /**
  39646. * Defines if the last and first points of each path in your pathArray must be joined
  39647. */
  39648. closeArray,
  39649. /**
  39650. * Defines if the last and first points of each path in your pathArray must be joined
  39651. */
  39652. closePath,
  39653. /**
  39654. * Defines the offset between points
  39655. */
  39656. offset, canBeRegenerated, mesh,
  39657. /**
  39658. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39659. */
  39660. side) {
  39661. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39662. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39663. _this.pathArray = pathArray;
  39664. _this.closeArray = closeArray;
  39665. _this.closePath = closePath;
  39666. _this.offset = offset;
  39667. _this.side = side;
  39668. return _this;
  39669. }
  39670. /** @hidden */
  39671. RibbonGeometry.prototype._regenerateVertexData = function () {
  39672. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39673. };
  39674. RibbonGeometry.prototype.copy = function (id) {
  39675. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39676. };
  39677. return RibbonGeometry;
  39678. }(_PrimitiveGeometry));
  39679. BABYLON.RibbonGeometry = RibbonGeometry;
  39680. /**
  39681. * Creates a box geometry
  39682. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39683. */
  39684. var BoxGeometry = /** @class */ (function (_super) {
  39685. __extends(BoxGeometry, _super);
  39686. /**
  39687. * Creates a box geometry
  39688. * @param id defines the unique ID of the geometry
  39689. * @param scene defines the hosting scene
  39690. * @param size defines the zise of the box (width, height and depth are the same)
  39691. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39692. * @param mesh defines the hosting mesh (can be null)
  39693. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39694. */
  39695. function BoxGeometry(id, scene,
  39696. /**
  39697. * Defines the zise of the box (width, height and depth are the same)
  39698. */
  39699. size, canBeRegenerated, mesh,
  39700. /**
  39701. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39702. */
  39703. side) {
  39704. if (mesh === void 0) { mesh = null; }
  39705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39707. _this.size = size;
  39708. _this.side = side;
  39709. return _this;
  39710. }
  39711. /** @hidden */
  39712. BoxGeometry.prototype._regenerateVertexData = function () {
  39713. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39714. };
  39715. BoxGeometry.prototype.copy = function (id) {
  39716. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39717. };
  39718. BoxGeometry.prototype.serialize = function () {
  39719. var serializationObject = _super.prototype.serialize.call(this);
  39720. serializationObject.size = this.size;
  39721. return serializationObject;
  39722. };
  39723. BoxGeometry.Parse = function (parsedBox, scene) {
  39724. if (scene.getGeometryByID(parsedBox.id)) {
  39725. return null; // null since geometry could be something else than a box...
  39726. }
  39727. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39728. if (BABYLON.Tags) {
  39729. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39730. }
  39731. scene.pushGeometry(box, true);
  39732. return box;
  39733. };
  39734. return BoxGeometry;
  39735. }(_PrimitiveGeometry));
  39736. BABYLON.BoxGeometry = BoxGeometry;
  39737. /**
  39738. * Creates a sphere geometry
  39739. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39740. */
  39741. var SphereGeometry = /** @class */ (function (_super) {
  39742. __extends(SphereGeometry, _super);
  39743. /**
  39744. * Create a new sphere geometry
  39745. * @param id defines the unique ID of the geometry
  39746. * @param scene defines the hosting scene
  39747. * @param segments defines the number of segments to use to create the sphere
  39748. * @param diameter defines the diameter of the sphere
  39749. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39750. * @param mesh defines the hosting mesh (can be null)
  39751. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39752. */
  39753. function SphereGeometry(id, scene,
  39754. /**
  39755. * Defines the number of segments to use to create the sphere
  39756. */
  39757. segments,
  39758. /**
  39759. * Defines the diameter of the sphere
  39760. */
  39761. diameter, canBeRegenerated, mesh,
  39762. /**
  39763. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39764. */
  39765. side) {
  39766. if (mesh === void 0) { mesh = null; }
  39767. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39768. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39769. _this.segments = segments;
  39770. _this.diameter = diameter;
  39771. _this.side = side;
  39772. return _this;
  39773. }
  39774. /** @hidden */
  39775. SphereGeometry.prototype._regenerateVertexData = function () {
  39776. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39777. };
  39778. SphereGeometry.prototype.copy = function (id) {
  39779. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39780. };
  39781. SphereGeometry.prototype.serialize = function () {
  39782. var serializationObject = _super.prototype.serialize.call(this);
  39783. serializationObject.segments = this.segments;
  39784. serializationObject.diameter = this.diameter;
  39785. return serializationObject;
  39786. };
  39787. SphereGeometry.Parse = function (parsedSphere, scene) {
  39788. if (scene.getGeometryByID(parsedSphere.id)) {
  39789. return null; // null since geometry could be something else than a sphere...
  39790. }
  39791. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39792. if (BABYLON.Tags) {
  39793. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39794. }
  39795. scene.pushGeometry(sphere, true);
  39796. return sphere;
  39797. };
  39798. return SphereGeometry;
  39799. }(_PrimitiveGeometry));
  39800. BABYLON.SphereGeometry = SphereGeometry;
  39801. /**
  39802. * Creates a disc geometry
  39803. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39804. */
  39805. var DiscGeometry = /** @class */ (function (_super) {
  39806. __extends(DiscGeometry, _super);
  39807. /**
  39808. * Creates a new disc geometry
  39809. * @param id defines the unique ID of the geometry
  39810. * @param scene defines the hosting scene
  39811. * @param radius defines the radius of the disc
  39812. * @param tessellation defines the tesselation factor to apply to the disc
  39813. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39814. * @param mesh defines the hosting mesh (can be null)
  39815. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39816. */
  39817. function DiscGeometry(id, scene,
  39818. /**
  39819. * Defines the radius of the disc
  39820. */
  39821. radius,
  39822. /**
  39823. * Defines the tesselation factor to apply to the disc
  39824. */
  39825. tessellation, canBeRegenerated, mesh,
  39826. /**
  39827. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39828. */
  39829. side) {
  39830. if (mesh === void 0) { mesh = null; }
  39831. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39832. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39833. _this.radius = radius;
  39834. _this.tessellation = tessellation;
  39835. _this.side = side;
  39836. return _this;
  39837. }
  39838. /** @hidden */
  39839. DiscGeometry.prototype._regenerateVertexData = function () {
  39840. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39841. };
  39842. DiscGeometry.prototype.copy = function (id) {
  39843. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39844. };
  39845. return DiscGeometry;
  39846. }(_PrimitiveGeometry));
  39847. BABYLON.DiscGeometry = DiscGeometry;
  39848. /**
  39849. * Creates a new cylinder geometry
  39850. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39851. */
  39852. var CylinderGeometry = /** @class */ (function (_super) {
  39853. __extends(CylinderGeometry, _super);
  39854. /**
  39855. * Creates a new cylinder geometry
  39856. * @param id defines the unique ID of the geometry
  39857. * @param scene defines the hosting scene
  39858. * @param height defines the height of the cylinder
  39859. * @param diameterTop defines the diameter of the cylinder's top cap
  39860. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39861. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39862. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39863. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39864. * @param mesh defines the hosting mesh (can be null)
  39865. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39866. */
  39867. function CylinderGeometry(id, scene,
  39868. /**
  39869. * Defines the height of the cylinder
  39870. */
  39871. height,
  39872. /**
  39873. * Defines the diameter of the cylinder's top cap
  39874. */
  39875. diameterTop,
  39876. /**
  39877. * Defines the diameter of the cylinder's bottom cap
  39878. */
  39879. diameterBottom,
  39880. /**
  39881. * Defines the tessellation factor to apply to the cylinder
  39882. */
  39883. tessellation,
  39884. /**
  39885. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39886. */
  39887. subdivisions, canBeRegenerated, mesh,
  39888. /**
  39889. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39890. */
  39891. side) {
  39892. if (subdivisions === void 0) { subdivisions = 1; }
  39893. if (mesh === void 0) { mesh = null; }
  39894. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39895. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39896. _this.height = height;
  39897. _this.diameterTop = diameterTop;
  39898. _this.diameterBottom = diameterBottom;
  39899. _this.tessellation = tessellation;
  39900. _this.subdivisions = subdivisions;
  39901. _this.side = side;
  39902. return _this;
  39903. }
  39904. /** @hidden */
  39905. CylinderGeometry.prototype._regenerateVertexData = function () {
  39906. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39907. };
  39908. CylinderGeometry.prototype.copy = function (id) {
  39909. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39910. };
  39911. CylinderGeometry.prototype.serialize = function () {
  39912. var serializationObject = _super.prototype.serialize.call(this);
  39913. serializationObject.height = this.height;
  39914. serializationObject.diameterTop = this.diameterTop;
  39915. serializationObject.diameterBottom = this.diameterBottom;
  39916. serializationObject.tessellation = this.tessellation;
  39917. return serializationObject;
  39918. };
  39919. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39920. if (scene.getGeometryByID(parsedCylinder.id)) {
  39921. return null; // null since geometry could be something else than a cylinder...
  39922. }
  39923. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39924. if (BABYLON.Tags) {
  39925. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39926. }
  39927. scene.pushGeometry(cylinder, true);
  39928. return cylinder;
  39929. };
  39930. return CylinderGeometry;
  39931. }(_PrimitiveGeometry));
  39932. BABYLON.CylinderGeometry = CylinderGeometry;
  39933. /**
  39934. * Creates a new torus geometry
  39935. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39936. */
  39937. var TorusGeometry = /** @class */ (function (_super) {
  39938. __extends(TorusGeometry, _super);
  39939. /**
  39940. * Creates a new torus geometry
  39941. * @param id defines the unique ID of the geometry
  39942. * @param scene defines the hosting scene
  39943. * @param diameter defines the diameter of the torus
  39944. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39945. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39946. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39947. * @param mesh defines the hosting mesh (can be null)
  39948. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39949. */
  39950. function TorusGeometry(id, scene,
  39951. /**
  39952. * Defines the diameter of the torus
  39953. */
  39954. diameter,
  39955. /**
  39956. * Defines the thickness of the torus (ie. internal diameter)
  39957. */
  39958. thickness,
  39959. /**
  39960. * Defines the tesselation factor to apply to the torus
  39961. */
  39962. tessellation, canBeRegenerated, mesh,
  39963. /**
  39964. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39965. */
  39966. side) {
  39967. if (mesh === void 0) { mesh = null; }
  39968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39969. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39970. _this.diameter = diameter;
  39971. _this.thickness = thickness;
  39972. _this.tessellation = tessellation;
  39973. _this.side = side;
  39974. return _this;
  39975. }
  39976. /** @hidden */
  39977. TorusGeometry.prototype._regenerateVertexData = function () {
  39978. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39979. };
  39980. TorusGeometry.prototype.copy = function (id) {
  39981. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39982. };
  39983. TorusGeometry.prototype.serialize = function () {
  39984. var serializationObject = _super.prototype.serialize.call(this);
  39985. serializationObject.diameter = this.diameter;
  39986. serializationObject.thickness = this.thickness;
  39987. serializationObject.tessellation = this.tessellation;
  39988. return serializationObject;
  39989. };
  39990. TorusGeometry.Parse = function (parsedTorus, scene) {
  39991. if (scene.getGeometryByID(parsedTorus.id)) {
  39992. return null; // null since geometry could be something else than a torus...
  39993. }
  39994. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39995. if (BABYLON.Tags) {
  39996. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39997. }
  39998. scene.pushGeometry(torus, true);
  39999. return torus;
  40000. };
  40001. return TorusGeometry;
  40002. }(_PrimitiveGeometry));
  40003. BABYLON.TorusGeometry = TorusGeometry;
  40004. /**
  40005. * Creates a new ground geometry
  40006. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40007. */
  40008. var GroundGeometry = /** @class */ (function (_super) {
  40009. __extends(GroundGeometry, _super);
  40010. /**
  40011. * Creates a new ground geometry
  40012. * @param id defines the unique ID of the geometry
  40013. * @param scene defines the hosting scene
  40014. * @param width defines the width of the ground
  40015. * @param height defines the height of the ground
  40016. * @param subdivisions defines the subdivisions to apply to the ground
  40017. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40018. * @param mesh defines the hosting mesh (can be null)
  40019. */
  40020. function GroundGeometry(id, scene,
  40021. /**
  40022. * Defines the width of the ground
  40023. */
  40024. width,
  40025. /**
  40026. * Defines the height of the ground
  40027. */
  40028. height,
  40029. /**
  40030. * Defines the subdivisions to apply to the ground
  40031. */
  40032. subdivisions, canBeRegenerated, mesh) {
  40033. if (mesh === void 0) { mesh = null; }
  40034. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40035. _this.width = width;
  40036. _this.height = height;
  40037. _this.subdivisions = subdivisions;
  40038. return _this;
  40039. }
  40040. /** @hidden */
  40041. GroundGeometry.prototype._regenerateVertexData = function () {
  40042. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40043. };
  40044. GroundGeometry.prototype.copy = function (id) {
  40045. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40046. };
  40047. GroundGeometry.prototype.serialize = function () {
  40048. var serializationObject = _super.prototype.serialize.call(this);
  40049. serializationObject.width = this.width;
  40050. serializationObject.height = this.height;
  40051. serializationObject.subdivisions = this.subdivisions;
  40052. return serializationObject;
  40053. };
  40054. GroundGeometry.Parse = function (parsedGround, scene) {
  40055. if (scene.getGeometryByID(parsedGround.id)) {
  40056. return null; // null since geometry could be something else than a ground...
  40057. }
  40058. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40059. if (BABYLON.Tags) {
  40060. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40061. }
  40062. scene.pushGeometry(ground, true);
  40063. return ground;
  40064. };
  40065. return GroundGeometry;
  40066. }(_PrimitiveGeometry));
  40067. BABYLON.GroundGeometry = GroundGeometry;
  40068. /**
  40069. * Creates a tiled ground geometry
  40070. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40071. */
  40072. var TiledGroundGeometry = /** @class */ (function (_super) {
  40073. __extends(TiledGroundGeometry, _super);
  40074. /**
  40075. * Creates a tiled ground geometry
  40076. * @param id defines the unique ID of the geometry
  40077. * @param scene defines the hosting scene
  40078. * @param xmin defines the minimum value on X axis
  40079. * @param zmin defines the minimum value on Z axis
  40080. * @param xmax defines the maximum value on X axis
  40081. * @param zmax defines the maximum value on Z axis
  40082. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40083. * @param precision defines the precision to use when computing the tiles
  40084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40085. * @param mesh defines the hosting mesh (can be null)
  40086. */
  40087. function TiledGroundGeometry(id, scene,
  40088. /**
  40089. * Defines the minimum value on X axis
  40090. */
  40091. xmin,
  40092. /**
  40093. * Defines the minimum value on Z axis
  40094. */
  40095. zmin,
  40096. /**
  40097. * Defines the maximum value on X axis
  40098. */
  40099. xmax,
  40100. /**
  40101. * Defines the maximum value on Z axis
  40102. */
  40103. zmax,
  40104. /**
  40105. * Defines the subdivisions to apply to the ground
  40106. */
  40107. subdivisions,
  40108. /**
  40109. * Defines the precision to use when computing the tiles
  40110. */
  40111. precision, canBeRegenerated, mesh) {
  40112. if (mesh === void 0) { mesh = null; }
  40113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40114. _this.xmin = xmin;
  40115. _this.zmin = zmin;
  40116. _this.xmax = xmax;
  40117. _this.zmax = zmax;
  40118. _this.subdivisions = subdivisions;
  40119. _this.precision = precision;
  40120. return _this;
  40121. }
  40122. /** @hidden */
  40123. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40124. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40125. };
  40126. TiledGroundGeometry.prototype.copy = function (id) {
  40127. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40128. };
  40129. return TiledGroundGeometry;
  40130. }(_PrimitiveGeometry));
  40131. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40132. /**
  40133. * Creates a plane geometry
  40134. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40135. */
  40136. var PlaneGeometry = /** @class */ (function (_super) {
  40137. __extends(PlaneGeometry, _super);
  40138. /**
  40139. * Creates a plane geometry
  40140. * @param id defines the unique ID of the geometry
  40141. * @param scene defines the hosting scene
  40142. * @param size defines the size of the plane (width === height)
  40143. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40144. * @param mesh defines the hosting mesh (can be null)
  40145. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40146. */
  40147. function PlaneGeometry(id, scene,
  40148. /**
  40149. * Defines the size of the plane (width === height)
  40150. */
  40151. size, canBeRegenerated, mesh,
  40152. /**
  40153. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40154. */
  40155. side) {
  40156. if (mesh === void 0) { mesh = null; }
  40157. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40158. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40159. _this.size = size;
  40160. _this.side = side;
  40161. return _this;
  40162. }
  40163. /** @hidden */
  40164. PlaneGeometry.prototype._regenerateVertexData = function () {
  40165. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40166. };
  40167. PlaneGeometry.prototype.copy = function (id) {
  40168. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40169. };
  40170. PlaneGeometry.prototype.serialize = function () {
  40171. var serializationObject = _super.prototype.serialize.call(this);
  40172. serializationObject.size = this.size;
  40173. return serializationObject;
  40174. };
  40175. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40176. if (scene.getGeometryByID(parsedPlane.id)) {
  40177. return null; // null since geometry could be something else than a ground...
  40178. }
  40179. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40180. if (BABYLON.Tags) {
  40181. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40182. }
  40183. scene.pushGeometry(plane, true);
  40184. return plane;
  40185. };
  40186. return PlaneGeometry;
  40187. }(_PrimitiveGeometry));
  40188. BABYLON.PlaneGeometry = PlaneGeometry;
  40189. /**
  40190. * Creates a torus knot geometry
  40191. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40192. */
  40193. var TorusKnotGeometry = /** @class */ (function (_super) {
  40194. __extends(TorusKnotGeometry, _super);
  40195. /**
  40196. * Creates a torus knot geometry
  40197. * @param id defines the unique ID of the geometry
  40198. * @param scene defines the hosting scene
  40199. * @param radius defines the radius of the torus knot
  40200. * @param tube defines the thickness of the torus knot tube
  40201. * @param radialSegments defines the number of radial segments
  40202. * @param tubularSegments defines the number of tubular segments
  40203. * @param p defines the first number of windings
  40204. * @param q defines the second number of windings
  40205. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40206. * @param mesh defines the hosting mesh (can be null)
  40207. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40208. */
  40209. function TorusKnotGeometry(id, scene,
  40210. /**
  40211. * Defines the radius of the torus knot
  40212. */
  40213. radius,
  40214. /**
  40215. * Defines the thickness of the torus knot tube
  40216. */
  40217. tube,
  40218. /**
  40219. * Defines the number of radial segments
  40220. */
  40221. radialSegments,
  40222. /**
  40223. * Defines the number of tubular segments
  40224. */
  40225. tubularSegments,
  40226. /**
  40227. * Defines the first number of windings
  40228. */
  40229. p,
  40230. /**
  40231. * Defines the second number of windings
  40232. */
  40233. q, canBeRegenerated, mesh,
  40234. /**
  40235. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40236. */
  40237. side) {
  40238. if (mesh === void 0) { mesh = null; }
  40239. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40240. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40241. _this.radius = radius;
  40242. _this.tube = tube;
  40243. _this.radialSegments = radialSegments;
  40244. _this.tubularSegments = tubularSegments;
  40245. _this.p = p;
  40246. _this.q = q;
  40247. _this.side = side;
  40248. return _this;
  40249. }
  40250. /** @hidden */
  40251. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40252. 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 });
  40253. };
  40254. TorusKnotGeometry.prototype.copy = function (id) {
  40255. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40256. };
  40257. TorusKnotGeometry.prototype.serialize = function () {
  40258. var serializationObject = _super.prototype.serialize.call(this);
  40259. serializationObject.radius = this.radius;
  40260. serializationObject.tube = this.tube;
  40261. serializationObject.radialSegments = this.radialSegments;
  40262. serializationObject.tubularSegments = this.tubularSegments;
  40263. serializationObject.p = this.p;
  40264. serializationObject.q = this.q;
  40265. return serializationObject;
  40266. };
  40267. ;
  40268. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40269. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40270. return null; // null since geometry could be something else than a ground...
  40271. }
  40272. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40273. if (BABYLON.Tags) {
  40274. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40275. }
  40276. scene.pushGeometry(torusKnot, true);
  40277. return torusKnot;
  40278. };
  40279. return TorusKnotGeometry;
  40280. }(_PrimitiveGeometry));
  40281. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40282. //}
  40283. })(BABYLON || (BABYLON = {}));
  40284. //# sourceMappingURL=babylon.geometry.js.map
  40285. var BABYLON;
  40286. (function (BABYLON) {
  40287. /**
  40288. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40289. */
  40290. var PerformanceMonitor = /** @class */ (function () {
  40291. /**
  40292. * constructor
  40293. * @param frameSampleSize The number of samples required to saturate the sliding window
  40294. */
  40295. function PerformanceMonitor(frameSampleSize) {
  40296. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40297. this._enabled = true;
  40298. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40299. }
  40300. /**
  40301. * Samples current frame
  40302. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40303. */
  40304. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40305. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40306. if (!this._enabled)
  40307. return;
  40308. if (this._lastFrameTimeMs != null) {
  40309. var dt = timeMs - this._lastFrameTimeMs;
  40310. this._rollingFrameTime.add(dt);
  40311. }
  40312. this._lastFrameTimeMs = timeMs;
  40313. };
  40314. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40315. /**
  40316. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40317. * @return Average frame time in milliseconds
  40318. */
  40319. get: function () {
  40320. return this._rollingFrameTime.average;
  40321. },
  40322. enumerable: true,
  40323. configurable: true
  40324. });
  40325. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40326. /**
  40327. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40328. * @return Frame time variance in milliseconds squared
  40329. */
  40330. get: function () {
  40331. return this._rollingFrameTime.variance;
  40332. },
  40333. enumerable: true,
  40334. configurable: true
  40335. });
  40336. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40337. /**
  40338. * Returns the frame time of the most recent frame
  40339. * @return Frame time in milliseconds
  40340. */
  40341. get: function () {
  40342. return this._rollingFrameTime.history(0);
  40343. },
  40344. enumerable: true,
  40345. configurable: true
  40346. });
  40347. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40348. /**
  40349. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40350. * @return Framerate in frames per second
  40351. */
  40352. get: function () {
  40353. return 1000.0 / this._rollingFrameTime.average;
  40354. },
  40355. enumerable: true,
  40356. configurable: true
  40357. });
  40358. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40359. /**
  40360. * Returns the average framerate in frames per second using the most recent frame time
  40361. * @return Framerate in frames per second
  40362. */
  40363. get: function () {
  40364. var history = this._rollingFrameTime.history(0);
  40365. if (history === 0) {
  40366. return 0;
  40367. }
  40368. return 1000.0 / history;
  40369. },
  40370. enumerable: true,
  40371. configurable: true
  40372. });
  40373. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40374. /**
  40375. * Returns true if enough samples have been taken to completely fill the sliding window
  40376. * @return true if saturated
  40377. */
  40378. get: function () {
  40379. return this._rollingFrameTime.isSaturated();
  40380. },
  40381. enumerable: true,
  40382. configurable: true
  40383. });
  40384. /**
  40385. * Enables contributions to the sliding window sample set
  40386. */
  40387. PerformanceMonitor.prototype.enable = function () {
  40388. this._enabled = true;
  40389. };
  40390. /**
  40391. * Disables contributions to the sliding window sample set
  40392. * Samples will not be interpolated over the disabled period
  40393. */
  40394. PerformanceMonitor.prototype.disable = function () {
  40395. this._enabled = false;
  40396. //clear last sample to avoid interpolating over the disabled period when next enabled
  40397. this._lastFrameTimeMs = null;
  40398. };
  40399. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40400. /**
  40401. * Returns true if sampling is enabled
  40402. * @return true if enabled
  40403. */
  40404. get: function () {
  40405. return this._enabled;
  40406. },
  40407. enumerable: true,
  40408. configurable: true
  40409. });
  40410. /**
  40411. * Resets performance monitor
  40412. */
  40413. PerformanceMonitor.prototype.reset = function () {
  40414. //clear last sample to avoid interpolating over the disabled period when next enabled
  40415. this._lastFrameTimeMs = null;
  40416. //wipe record
  40417. this._rollingFrameTime.reset();
  40418. };
  40419. return PerformanceMonitor;
  40420. }());
  40421. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40422. /**
  40423. * RollingAverage
  40424. *
  40425. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40426. */
  40427. var RollingAverage = /** @class */ (function () {
  40428. /**
  40429. * constructor
  40430. * @param length The number of samples required to saturate the sliding window
  40431. */
  40432. function RollingAverage(length) {
  40433. this._samples = new Array(length);
  40434. this.reset();
  40435. }
  40436. /**
  40437. * Adds a sample to the sample set
  40438. * @param v The sample value
  40439. */
  40440. RollingAverage.prototype.add = function (v) {
  40441. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40442. var delta;
  40443. //we need to check if we've already wrapped round
  40444. if (this.isSaturated()) {
  40445. //remove bottom of stack from mean
  40446. var bottomValue = this._samples[this._pos];
  40447. delta = bottomValue - this.average;
  40448. this.average -= delta / (this._sampleCount - 1);
  40449. this._m2 -= delta * (bottomValue - this.average);
  40450. }
  40451. else {
  40452. this._sampleCount++;
  40453. }
  40454. //add new value to mean
  40455. delta = v - this.average;
  40456. this.average += delta / (this._sampleCount);
  40457. this._m2 += delta * (v - this.average);
  40458. //set the new variance
  40459. this.variance = this._m2 / (this._sampleCount - 1);
  40460. this._samples[this._pos] = v;
  40461. this._pos++;
  40462. this._pos %= this._samples.length; //positive wrap around
  40463. };
  40464. /**
  40465. * Returns previously added values or null if outside of history or outside the sliding window domain
  40466. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40467. * @return Value previously recorded with add() or null if outside of range
  40468. */
  40469. RollingAverage.prototype.history = function (i) {
  40470. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40471. return 0;
  40472. }
  40473. var i0 = this._wrapPosition(this._pos - 1.0);
  40474. return this._samples[this._wrapPosition(i0 - i)];
  40475. };
  40476. /**
  40477. * Returns true if enough samples have been taken to completely fill the sliding window
  40478. * @return true if sample-set saturated
  40479. */
  40480. RollingAverage.prototype.isSaturated = function () {
  40481. return this._sampleCount >= this._samples.length;
  40482. };
  40483. /**
  40484. * Resets the rolling average (equivalent to 0 samples taken so far)
  40485. */
  40486. RollingAverage.prototype.reset = function () {
  40487. this.average = 0;
  40488. this.variance = 0;
  40489. this._sampleCount = 0;
  40490. this._pos = 0;
  40491. this._m2 = 0;
  40492. };
  40493. /**
  40494. * Wraps a value around the sample range boundaries
  40495. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40496. * @return Wrapped position in sample range
  40497. */
  40498. RollingAverage.prototype._wrapPosition = function (i) {
  40499. var max = this._samples.length;
  40500. return ((i % max) + max) % max;
  40501. };
  40502. return RollingAverage;
  40503. }());
  40504. BABYLON.RollingAverage = RollingAverage;
  40505. })(BABYLON || (BABYLON = {}));
  40506. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40507. var BABYLON;
  40508. (function (BABYLON) {
  40509. /**
  40510. * "Static Class" containing the most commonly used helper while dealing with material for
  40511. * rendering purpose.
  40512. *
  40513. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40514. *
  40515. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40516. */
  40517. var MaterialHelper = /** @class */ (function () {
  40518. function MaterialHelper() {
  40519. }
  40520. /**
  40521. * Bind the current view position to an effect.
  40522. * @param effect The effect to be bound
  40523. * @param scene The scene the eyes position is used from
  40524. */
  40525. MaterialHelper.BindEyePosition = function (effect, scene) {
  40526. if (scene._forcedViewPosition) {
  40527. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40528. return;
  40529. }
  40530. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40531. };
  40532. /**
  40533. * Helps preparing the defines values about the UVs in used in the effect.
  40534. * UVs are shared as much as we can accross chanels in the shaders.
  40535. * @param texture The texture we are preparing the UVs for
  40536. * @param defines The defines to update
  40537. * @param key The chanel key "diffuse", "specular"... used in the shader
  40538. */
  40539. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40540. defines._needUVs = true;
  40541. defines[key] = true;
  40542. if (texture.getTextureMatrix().isIdentity(true)) {
  40543. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40544. if (texture.coordinatesIndex === 0) {
  40545. defines["MAINUV1"] = true;
  40546. }
  40547. else {
  40548. defines["MAINUV2"] = true;
  40549. }
  40550. }
  40551. else {
  40552. defines[key + "DIRECTUV"] = 0;
  40553. }
  40554. };
  40555. /**
  40556. * Binds a texture matrix value to its corrsponding uniform
  40557. * @param texture The texture to bind the matrix for
  40558. * @param uniformBuffer The uniform buffer receivin the data
  40559. * @param key The chanel key "diffuse", "specular"... used in the shader
  40560. */
  40561. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40562. var matrix = texture.getTextureMatrix();
  40563. if (!matrix.isIdentity(true)) {
  40564. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40565. }
  40566. };
  40567. /**
  40568. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40569. * @param mesh defines the current mesh
  40570. * @param scene defines the current scene
  40571. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40572. * @param pointsCloud defines if point cloud rendering has to be turned on
  40573. * @param fogEnabled defines if fog has to be turned on
  40574. * @param alphaTest defines if alpha testing has to be turned on
  40575. * @param defines defines the current list of defines
  40576. */
  40577. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40578. if (defines._areMiscDirty) {
  40579. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40580. defines["POINTSIZE"] = pointsCloud;
  40581. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40582. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40583. defines["ALPHATEST"] = alphaTest;
  40584. }
  40585. };
  40586. /**
  40587. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40588. * @param scene defines the current scene
  40589. * @param engine defines the current engine
  40590. * @param defines specifies the list of active defines
  40591. * @param useInstances defines if instances have to be turned on
  40592. * @param useClipPlane defines if clip plane have to be turned on
  40593. */
  40594. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40595. if (useClipPlane === void 0) { useClipPlane = null; }
  40596. var changed = false;
  40597. var useClipPlane1 = false;
  40598. var useClipPlane2 = false;
  40599. var useClipPlane3 = false;
  40600. var useClipPlane4 = false;
  40601. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40602. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40603. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40604. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40605. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40606. defines["CLIPPLANE"] = useClipPlane1;
  40607. changed = true;
  40608. }
  40609. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40610. defines["CLIPPLANE2"] = useClipPlane2;
  40611. changed = true;
  40612. }
  40613. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40614. defines["CLIPPLANE3"] = useClipPlane3;
  40615. changed = true;
  40616. }
  40617. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40618. defines["CLIPPLANE4"] = useClipPlane4;
  40619. changed = true;
  40620. }
  40621. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40622. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40623. changed = true;
  40624. }
  40625. if (defines["INSTANCES"] !== useInstances) {
  40626. defines["INSTANCES"] = useInstances;
  40627. changed = true;
  40628. }
  40629. if (changed) {
  40630. defines.markAsUnprocessed();
  40631. }
  40632. };
  40633. /**
  40634. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40635. * @param mesh The mesh containing the geometry data we will draw
  40636. * @param defines The defines to update
  40637. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40638. * @param useBones Precise whether bones should be used or not (override mesh info)
  40639. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40640. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40641. * @returns false if defines are considered not dirty and have not been checked
  40642. */
  40643. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40644. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40645. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40646. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40647. return false;
  40648. }
  40649. defines._normals = defines._needNormals;
  40650. defines._uvs = defines._needUVs;
  40651. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40652. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40653. defines["TANGENT"] = true;
  40654. }
  40655. if (defines._needUVs) {
  40656. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40657. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40658. }
  40659. else {
  40660. defines["UV1"] = false;
  40661. defines["UV2"] = false;
  40662. }
  40663. if (useVertexColor) {
  40664. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40665. defines["VERTEXCOLOR"] = hasVertexColors;
  40666. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40667. }
  40668. if (useBones) {
  40669. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40670. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40671. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40672. }
  40673. else {
  40674. defines["NUM_BONE_INFLUENCERS"] = 0;
  40675. defines["BonesPerMesh"] = 0;
  40676. }
  40677. }
  40678. if (useMorphTargets) {
  40679. var manager = mesh.morphTargetManager;
  40680. if (manager) {
  40681. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40682. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40683. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40684. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40685. }
  40686. else {
  40687. defines["MORPHTARGETS_TANGENT"] = false;
  40688. defines["MORPHTARGETS_NORMAL"] = false;
  40689. defines["MORPHTARGETS"] = false;
  40690. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40691. }
  40692. }
  40693. return true;
  40694. };
  40695. /**
  40696. * Prepares the defines related to the light information passed in parameter
  40697. * @param scene The scene we are intending to draw
  40698. * @param mesh The mesh the effect is compiling for
  40699. * @param defines The defines to update
  40700. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40701. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40702. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40703. * @returns true if normals will be required for the rest of the effect
  40704. */
  40705. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40706. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40707. if (disableLighting === void 0) { disableLighting = false; }
  40708. if (!defines._areLightsDirty) {
  40709. return defines._needNormals;
  40710. }
  40711. var lightIndex = 0;
  40712. var needNormals = false;
  40713. var needRebuild = false;
  40714. var lightmapMode = false;
  40715. var shadowEnabled = false;
  40716. var specularEnabled = false;
  40717. if (scene.lightsEnabled && !disableLighting) {
  40718. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40719. var light = _a[_i];
  40720. needNormals = true;
  40721. if (defines["LIGHT" + lightIndex] === undefined) {
  40722. needRebuild = true;
  40723. }
  40724. defines["LIGHT" + lightIndex] = true;
  40725. defines["SPOTLIGHT" + lightIndex] = false;
  40726. defines["HEMILIGHT" + lightIndex] = false;
  40727. defines["POINTLIGHT" + lightIndex] = false;
  40728. defines["DIRLIGHT" + lightIndex] = false;
  40729. light.prepareLightSpecificDefines(defines, lightIndex);
  40730. // FallOff.
  40731. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40732. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40733. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40734. switch (light.falloffType) {
  40735. case BABYLON.Light.FALLOFF_GLTF:
  40736. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40737. break;
  40738. case BABYLON.Light.FALLOFF_PHYSICAL:
  40739. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40740. break;
  40741. case BABYLON.Light.FALLOFF_STANDARD:
  40742. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40743. break;
  40744. }
  40745. // Specular
  40746. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40747. specularEnabled = true;
  40748. }
  40749. // Shadows
  40750. defines["SHADOW" + lightIndex] = false;
  40751. defines["SHADOWPCF" + lightIndex] = false;
  40752. defines["SHADOWPCSS" + lightIndex] = false;
  40753. defines["SHADOWPOISSON" + lightIndex] = false;
  40754. defines["SHADOWESM" + lightIndex] = false;
  40755. defines["SHADOWCUBE" + lightIndex] = false;
  40756. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40757. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40758. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40759. var shadowGenerator = light.getShadowGenerator();
  40760. if (shadowGenerator) {
  40761. var shadowMap = shadowGenerator.getShadowMap();
  40762. if (shadowMap) {
  40763. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40764. shadowEnabled = true;
  40765. shadowGenerator.prepareDefines(defines, lightIndex);
  40766. }
  40767. }
  40768. }
  40769. }
  40770. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40771. lightmapMode = true;
  40772. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40773. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40774. }
  40775. else {
  40776. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40777. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40778. }
  40779. lightIndex++;
  40780. if (lightIndex === maxSimultaneousLights)
  40781. break;
  40782. }
  40783. }
  40784. defines["SPECULARTERM"] = specularEnabled;
  40785. defines["SHADOWS"] = shadowEnabled;
  40786. // Resetting all other lights if any
  40787. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40788. if (defines["LIGHT" + index] !== undefined) {
  40789. defines["LIGHT" + index] = false;
  40790. defines["HEMILIGHT" + lightIndex] = false;
  40791. defines["POINTLIGHT" + lightIndex] = false;
  40792. defines["DIRLIGHT" + lightIndex] = false;
  40793. defines["SPOTLIGHT" + lightIndex] = false;
  40794. defines["SHADOW" + lightIndex] = false;
  40795. }
  40796. }
  40797. var caps = scene.getEngine().getCaps();
  40798. if (defines["SHADOWFLOAT"] === undefined) {
  40799. needRebuild = true;
  40800. }
  40801. defines["SHADOWFLOAT"] = shadowEnabled &&
  40802. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40803. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40804. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40805. if (needRebuild) {
  40806. defines.rebuild();
  40807. }
  40808. return needNormals;
  40809. };
  40810. /**
  40811. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40812. * that won t be acctive due to defines being turned off.
  40813. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40814. * @param samplersList The samplers list
  40815. * @param defines The defines helping in the list generation
  40816. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40817. */
  40818. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40819. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40820. var uniformsList;
  40821. var uniformBuffersList = null;
  40822. if (uniformsListOrOptions.uniformsNames) {
  40823. var options = uniformsListOrOptions;
  40824. uniformsList = options.uniformsNames;
  40825. uniformBuffersList = options.uniformBuffersNames;
  40826. samplersList = options.samplers;
  40827. defines = options.defines;
  40828. maxSimultaneousLights = options.maxSimultaneousLights;
  40829. }
  40830. else {
  40831. uniformsList = uniformsListOrOptions;
  40832. if (!samplersList) {
  40833. samplersList = [];
  40834. }
  40835. }
  40836. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40837. if (!defines["LIGHT" + lightIndex]) {
  40838. break;
  40839. }
  40840. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40841. if (uniformBuffersList) {
  40842. uniformBuffersList.push("Light" + lightIndex);
  40843. }
  40844. samplersList.push("shadowSampler" + lightIndex);
  40845. samplersList.push("depthSampler" + lightIndex);
  40846. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40847. samplersList.push("projectionLightSampler" + lightIndex);
  40848. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40849. }
  40850. }
  40851. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40852. uniformsList.push("morphTargetInfluences");
  40853. }
  40854. };
  40855. /**
  40856. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40857. * @param defines The defines to update while falling back
  40858. * @param fallbacks The authorized effect fallbacks
  40859. * @param maxSimultaneousLights The maximum number of lights allowed
  40860. * @param rank the current rank of the Effect
  40861. * @returns The newly affected rank
  40862. */
  40863. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40864. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40865. if (rank === void 0) { rank = 0; }
  40866. var lightFallbackRank = 0;
  40867. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40868. if (!defines["LIGHT" + lightIndex]) {
  40869. break;
  40870. }
  40871. if (lightIndex > 0) {
  40872. lightFallbackRank = rank + lightIndex;
  40873. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40874. }
  40875. if (!defines["SHADOWS"]) {
  40876. if (defines["SHADOW" + lightIndex]) {
  40877. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40878. }
  40879. if (defines["SHADOWPCF" + lightIndex]) {
  40880. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40881. }
  40882. if (defines["SHADOWPCSS" + lightIndex]) {
  40883. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40884. }
  40885. if (defines["SHADOWPOISSON" + lightIndex]) {
  40886. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40887. }
  40888. if (defines["SHADOWESM" + lightIndex]) {
  40889. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40890. }
  40891. }
  40892. }
  40893. return lightFallbackRank++;
  40894. };
  40895. /**
  40896. * Prepares the list of attributes required for morph targets according to the effect defines.
  40897. * @param attribs The current list of supported attribs
  40898. * @param mesh The mesh to prepare the morph targets attributes for
  40899. * @param defines The current Defines of the effect
  40900. */
  40901. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40902. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40903. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40904. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40905. var manager = mesh.morphTargetManager;
  40906. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40907. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40908. for (var index = 0; index < influencers; index++) {
  40909. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40910. if (normal) {
  40911. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40912. }
  40913. if (tangent) {
  40914. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40915. }
  40916. if (attribs.length > maxAttributesCount) {
  40917. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40918. }
  40919. }
  40920. }
  40921. };
  40922. /**
  40923. * Prepares the list of attributes required for bones according to the effect defines.
  40924. * @param attribs The current list of supported attribs
  40925. * @param mesh The mesh to prepare the bones attributes for
  40926. * @param defines The current Defines of the effect
  40927. * @param fallbacks The current efffect fallback strategy
  40928. */
  40929. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40930. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40931. fallbacks.addCPUSkinningFallback(0, mesh);
  40932. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40933. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40934. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40937. }
  40938. }
  40939. };
  40940. /**
  40941. * Prepares the list of attributes required for instances according to the effect defines.
  40942. * @param attribs The current list of supported attribs
  40943. * @param defines The current Defines of the effect
  40944. */
  40945. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40946. if (defines["INSTANCES"]) {
  40947. attribs.push("world0");
  40948. attribs.push("world1");
  40949. attribs.push("world2");
  40950. attribs.push("world3");
  40951. }
  40952. };
  40953. /**
  40954. * Binds the light shadow information to the effect for the given mesh.
  40955. * @param light The light containing the generator
  40956. * @param scene The scene the lights belongs to
  40957. * @param mesh The mesh we are binding the information to render
  40958. * @param lightIndex The light index in the effect used to render the mesh
  40959. * @param effect The effect we are binding the data to
  40960. */
  40961. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40962. if (light.shadowEnabled && mesh.receiveShadows) {
  40963. var shadowGenerator = light.getShadowGenerator();
  40964. if (shadowGenerator) {
  40965. shadowGenerator.bindShadowLight(lightIndex, effect);
  40966. }
  40967. }
  40968. };
  40969. /**
  40970. * Binds the light information to the effect.
  40971. * @param light The light containing the generator
  40972. * @param effect The effect we are binding the data to
  40973. * @param lightIndex The light index in the effect used to render
  40974. */
  40975. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40976. light.transferToEffect(effect, lightIndex + "");
  40977. };
  40978. /**
  40979. * Binds the lights information from the scene to the effect for the given mesh.
  40980. * @param scene The scene the lights belongs to
  40981. * @param mesh The mesh we are binding the information to render
  40982. * @param effect The effect we are binding the data to
  40983. * @param defines The generated defines for the effect
  40984. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40985. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40986. */
  40987. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40988. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40989. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40990. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40991. for (var i = 0; i < len; i++) {
  40992. var light = mesh._lightSources[i];
  40993. var iAsString = i.toString();
  40994. var scaledIntensity = light.getScaledIntensity();
  40995. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40996. MaterialHelper.BindLightProperties(light, effect, i);
  40997. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40998. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40999. if (defines["SPECULARTERM"]) {
  41000. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41001. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41002. }
  41003. // Shadows
  41004. if (scene.shadowsEnabled) {
  41005. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41006. }
  41007. light._uniformBuffer.update();
  41008. }
  41009. };
  41010. /**
  41011. * Binds the fog information from the scene to the effect for the given mesh.
  41012. * @param scene The scene the lights belongs to
  41013. * @param mesh The mesh we are binding the information to render
  41014. * @param effect The effect we are binding the data to
  41015. */
  41016. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41017. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41018. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41019. effect.setColor3("vFogColor", scene.fogColor);
  41020. }
  41021. };
  41022. /**
  41023. * Binds the bones information from the mesh to the effect.
  41024. * @param mesh The mesh we are binding the information to render
  41025. * @param effect The effect we are binding the data to
  41026. */
  41027. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41028. if (!effect || !mesh) {
  41029. return;
  41030. }
  41031. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41032. mesh.computeBonesUsingShaders = false;
  41033. }
  41034. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41035. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41036. if (matrices) {
  41037. effect.setMatrices("mBones", matrices);
  41038. }
  41039. }
  41040. };
  41041. /**
  41042. * Binds the morph targets information from the mesh to the effect.
  41043. * @param abstractMesh The mesh we are binding the information to render
  41044. * @param effect The effect we are binding the data to
  41045. */
  41046. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41047. var manager = abstractMesh.morphTargetManager;
  41048. if (!abstractMesh || !manager) {
  41049. return;
  41050. }
  41051. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41052. };
  41053. /**
  41054. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41055. * @param defines The generated defines used in the effect
  41056. * @param effect The effect we are binding the data to
  41057. * @param scene The scene we are willing to render with logarithmic scale for
  41058. */
  41059. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41060. if (defines["LOGARITHMICDEPTH"]) {
  41061. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41062. }
  41063. };
  41064. /**
  41065. * Binds the clip plane information from the scene to the effect.
  41066. * @param scene The scene the clip plane information are extracted from
  41067. * @param effect The effect we are binding the data to
  41068. */
  41069. MaterialHelper.BindClipPlane = function (effect, scene) {
  41070. if (scene.clipPlane) {
  41071. var clipPlane = scene.clipPlane;
  41072. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41073. }
  41074. if (scene.clipPlane2) {
  41075. var clipPlane = scene.clipPlane2;
  41076. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41077. }
  41078. if (scene.clipPlane3) {
  41079. var clipPlane = scene.clipPlane3;
  41080. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41081. }
  41082. if (scene.clipPlane4) {
  41083. var clipPlane = scene.clipPlane4;
  41084. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41085. }
  41086. };
  41087. return MaterialHelper;
  41088. }());
  41089. BABYLON.MaterialHelper = MaterialHelper;
  41090. })(BABYLON || (BABYLON = {}));
  41091. //# sourceMappingURL=babylon.materialHelper.js.map
  41092. var BABYLON;
  41093. (function (BABYLON) {
  41094. var PushMaterial = /** @class */ (function (_super) {
  41095. __extends(PushMaterial, _super);
  41096. function PushMaterial(name, scene) {
  41097. var _this = _super.call(this, name, scene) || this;
  41098. _this._normalMatrix = new BABYLON.Matrix();
  41099. _this.storeEffectOnSubMeshes = true;
  41100. return _this;
  41101. }
  41102. PushMaterial.prototype.getEffect = function () {
  41103. return this._activeEffect;
  41104. };
  41105. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41106. if (!mesh) {
  41107. return false;
  41108. }
  41109. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41110. return true;
  41111. }
  41112. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41113. };
  41114. /**
  41115. * Binds the given world matrix to the active effect
  41116. *
  41117. * @param world the matrix to bind
  41118. */
  41119. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41120. this._activeEffect.setMatrix("world", world);
  41121. };
  41122. /**
  41123. * Binds the given normal matrix to the active effect
  41124. *
  41125. * @param normalMatrix the matrix to bind
  41126. */
  41127. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41128. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41129. };
  41130. PushMaterial.prototype.bind = function (world, mesh) {
  41131. if (!mesh) {
  41132. return;
  41133. }
  41134. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41135. };
  41136. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41137. if (effect === void 0) { effect = null; }
  41138. _super.prototype._afterBind.call(this, mesh);
  41139. this.getScene()._cachedEffect = effect;
  41140. };
  41141. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41142. if (visibility === void 0) { visibility = 1; }
  41143. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41144. };
  41145. return PushMaterial;
  41146. }(BABYLON.Material));
  41147. BABYLON.PushMaterial = PushMaterial;
  41148. })(BABYLON || (BABYLON = {}));
  41149. //# sourceMappingURL=babylon.pushMaterial.js.map
  41150. var BABYLON;
  41151. (function (BABYLON) {
  41152. /** @hidden */
  41153. var StandardMaterialDefines = /** @class */ (function (_super) {
  41154. __extends(StandardMaterialDefines, _super);
  41155. function StandardMaterialDefines() {
  41156. var _this = _super.call(this) || this;
  41157. _this.MAINUV1 = false;
  41158. _this.MAINUV2 = false;
  41159. _this.DIFFUSE = false;
  41160. _this.DIFFUSEDIRECTUV = 0;
  41161. _this.AMBIENT = false;
  41162. _this.AMBIENTDIRECTUV = 0;
  41163. _this.OPACITY = false;
  41164. _this.OPACITYDIRECTUV = 0;
  41165. _this.OPACITYRGB = false;
  41166. _this.REFLECTION = false;
  41167. _this.EMISSIVE = false;
  41168. _this.EMISSIVEDIRECTUV = 0;
  41169. _this.SPECULAR = false;
  41170. _this.SPECULARDIRECTUV = 0;
  41171. _this.BUMP = false;
  41172. _this.BUMPDIRECTUV = 0;
  41173. _this.PARALLAX = false;
  41174. _this.PARALLAXOCCLUSION = false;
  41175. _this.SPECULAROVERALPHA = false;
  41176. _this.CLIPPLANE = false;
  41177. _this.CLIPPLANE2 = false;
  41178. _this.CLIPPLANE3 = false;
  41179. _this.CLIPPLANE4 = false;
  41180. _this.ALPHATEST = false;
  41181. _this.DEPTHPREPASS = false;
  41182. _this.ALPHAFROMDIFFUSE = false;
  41183. _this.POINTSIZE = false;
  41184. _this.FOG = false;
  41185. _this.SPECULARTERM = false;
  41186. _this.DIFFUSEFRESNEL = false;
  41187. _this.OPACITYFRESNEL = false;
  41188. _this.REFLECTIONFRESNEL = false;
  41189. _this.REFRACTIONFRESNEL = false;
  41190. _this.EMISSIVEFRESNEL = false;
  41191. _this.FRESNEL = false;
  41192. _this.NORMAL = false;
  41193. _this.UV1 = false;
  41194. _this.UV2 = false;
  41195. _this.VERTEXCOLOR = false;
  41196. _this.VERTEXALPHA = false;
  41197. _this.NUM_BONE_INFLUENCERS = 0;
  41198. _this.BonesPerMesh = 0;
  41199. _this.INSTANCES = false;
  41200. _this.GLOSSINESS = false;
  41201. _this.ROUGHNESS = false;
  41202. _this.EMISSIVEASILLUMINATION = false;
  41203. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41204. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41205. _this.LIGHTMAP = false;
  41206. _this.LIGHTMAPDIRECTUV = 0;
  41207. _this.OBJECTSPACE_NORMALMAP = false;
  41208. _this.USELIGHTMAPASSHADOWMAP = false;
  41209. _this.REFLECTIONMAP_3D = false;
  41210. _this.REFLECTIONMAP_SPHERICAL = false;
  41211. _this.REFLECTIONMAP_PLANAR = false;
  41212. _this.REFLECTIONMAP_CUBIC = false;
  41213. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41214. _this.REFLECTIONMAP_PROJECTION = false;
  41215. _this.REFLECTIONMAP_SKYBOX = false;
  41216. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41217. _this.REFLECTIONMAP_EXPLICIT = false;
  41218. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41219. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41220. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41221. _this.INVERTCUBICMAP = false;
  41222. _this.LOGARITHMICDEPTH = false;
  41223. _this.REFRACTION = false;
  41224. _this.REFRACTIONMAP_3D = false;
  41225. _this.REFLECTIONOVERALPHA = false;
  41226. _this.TWOSIDEDLIGHTING = false;
  41227. _this.SHADOWFLOAT = false;
  41228. _this.MORPHTARGETS = false;
  41229. _this.MORPHTARGETS_NORMAL = false;
  41230. _this.MORPHTARGETS_TANGENT = false;
  41231. _this.NUM_MORPH_INFLUENCERS = 0;
  41232. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41233. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41234. _this.IMAGEPROCESSING = false;
  41235. _this.VIGNETTE = false;
  41236. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41237. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41238. _this.TONEMAPPING = false;
  41239. _this.TONEMAPPING_ACES = false;
  41240. _this.CONTRAST = false;
  41241. _this.COLORCURVES = false;
  41242. _this.COLORGRADING = false;
  41243. _this.COLORGRADING3D = false;
  41244. _this.SAMPLER3DGREENDEPTH = false;
  41245. _this.SAMPLER3DBGRMAP = false;
  41246. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41247. /**
  41248. * If the reflection texture on this material is in linear color space
  41249. * @hidden
  41250. */
  41251. _this.IS_REFLECTION_LINEAR = false;
  41252. /**
  41253. * If the refraction texture on this material is in linear color space
  41254. * @hidden
  41255. */
  41256. _this.IS_REFRACTION_LINEAR = false;
  41257. _this.EXPOSURE = false;
  41258. _this.rebuild();
  41259. return _this;
  41260. }
  41261. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41262. var modes = [
  41263. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41264. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41265. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41266. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41267. ];
  41268. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41269. var mode = modes_1[_i];
  41270. this[mode] = (mode === modeToEnable);
  41271. }
  41272. };
  41273. return StandardMaterialDefines;
  41274. }(BABYLON.MaterialDefines));
  41275. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41276. var StandardMaterial = /** @class */ (function (_super) {
  41277. __extends(StandardMaterial, _super);
  41278. function StandardMaterial(name, scene) {
  41279. var _this = _super.call(this, name, scene) || this;
  41280. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41281. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41282. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41283. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41284. _this.specularPower = 64;
  41285. _this._useAlphaFromDiffuseTexture = false;
  41286. _this._useEmissiveAsIllumination = false;
  41287. _this._linkEmissiveWithDiffuse = false;
  41288. _this._useSpecularOverAlpha = false;
  41289. _this._useReflectionOverAlpha = false;
  41290. _this._disableLighting = false;
  41291. _this._useObjectSpaceNormalMap = false;
  41292. _this._useParallax = false;
  41293. _this._useParallaxOcclusion = false;
  41294. _this.parallaxScaleBias = 0.05;
  41295. _this._roughness = 0;
  41296. _this.indexOfRefraction = 0.98;
  41297. _this.invertRefractionY = true;
  41298. /**
  41299. * Defines the alpha limits in alpha test mode
  41300. */
  41301. _this.alphaCutOff = 0.4;
  41302. _this._useLightmapAsShadowmap = false;
  41303. _this._useReflectionFresnelFromSpecular = false;
  41304. _this._useGlossinessFromSpecularMapAlpha = false;
  41305. _this._maxSimultaneousLights = 4;
  41306. /**
  41307. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41308. */
  41309. _this._invertNormalMapX = false;
  41310. /**
  41311. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41312. */
  41313. _this._invertNormalMapY = false;
  41314. /**
  41315. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41316. */
  41317. _this._twoSidedLighting = false;
  41318. _this._renderTargets = new BABYLON.SmartArray(16);
  41319. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41320. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41321. // Setup the default processing configuration to the scene.
  41322. _this._attachImageProcessingConfiguration(null);
  41323. _this.getRenderTargetTextures = function () {
  41324. _this._renderTargets.reset();
  41325. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41326. _this._renderTargets.push(_this._reflectionTexture);
  41327. }
  41328. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41329. _this._renderTargets.push(_this._refractionTexture);
  41330. }
  41331. return _this._renderTargets;
  41332. };
  41333. return _this;
  41334. }
  41335. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41336. /**
  41337. * Gets the image processing configuration used either in this material.
  41338. */
  41339. get: function () {
  41340. return this._imageProcessingConfiguration;
  41341. },
  41342. /**
  41343. * Sets the Default image processing configuration used either in the this material.
  41344. *
  41345. * If sets to null, the scene one is in use.
  41346. */
  41347. set: function (value) {
  41348. this._attachImageProcessingConfiguration(value);
  41349. // Ensure the effect will be rebuilt.
  41350. this._markAllSubMeshesAsTexturesDirty();
  41351. },
  41352. enumerable: true,
  41353. configurable: true
  41354. });
  41355. /**
  41356. * Attaches a new image processing configuration to the Standard Material.
  41357. * @param configuration
  41358. */
  41359. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41360. var _this = this;
  41361. if (configuration === this._imageProcessingConfiguration) {
  41362. return;
  41363. }
  41364. // Detaches observer.
  41365. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41366. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41367. }
  41368. // Pick the scene configuration if needed.
  41369. if (!configuration) {
  41370. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41371. }
  41372. else {
  41373. this._imageProcessingConfiguration = configuration;
  41374. }
  41375. // Attaches observer.
  41376. if (this._imageProcessingConfiguration) {
  41377. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41378. _this._markAllSubMeshesAsImageProcessingDirty();
  41379. });
  41380. }
  41381. };
  41382. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41383. /**
  41384. * Gets wether the color curves effect is enabled.
  41385. */
  41386. get: function () {
  41387. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41388. },
  41389. /**
  41390. * Sets wether the color curves effect is enabled.
  41391. */
  41392. set: function (value) {
  41393. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41394. },
  41395. enumerable: true,
  41396. configurable: true
  41397. });
  41398. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41399. /**
  41400. * Gets wether the color grading effect is enabled.
  41401. */
  41402. get: function () {
  41403. return this.imageProcessingConfiguration.colorGradingEnabled;
  41404. },
  41405. /**
  41406. * Gets wether the color grading effect is enabled.
  41407. */
  41408. set: function (value) {
  41409. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41415. /**
  41416. * Gets wether tonemapping is enabled or not.
  41417. */
  41418. get: function () {
  41419. return this._imageProcessingConfiguration.toneMappingEnabled;
  41420. },
  41421. /**
  41422. * Sets wether tonemapping is enabled or not
  41423. */
  41424. set: function (value) {
  41425. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41426. },
  41427. enumerable: true,
  41428. configurable: true
  41429. });
  41430. ;
  41431. ;
  41432. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41433. /**
  41434. * The camera exposure used on this material.
  41435. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41436. * This corresponds to a photographic exposure.
  41437. */
  41438. get: function () {
  41439. return this._imageProcessingConfiguration.exposure;
  41440. },
  41441. /**
  41442. * The camera exposure used on this material.
  41443. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41444. * This corresponds to a photographic exposure.
  41445. */
  41446. set: function (value) {
  41447. this._imageProcessingConfiguration.exposure = value;
  41448. },
  41449. enumerable: true,
  41450. configurable: true
  41451. });
  41452. ;
  41453. ;
  41454. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41455. /**
  41456. * Gets The camera contrast used on this material.
  41457. */
  41458. get: function () {
  41459. return this._imageProcessingConfiguration.contrast;
  41460. },
  41461. /**
  41462. * Sets The camera contrast used on this material.
  41463. */
  41464. set: function (value) {
  41465. this._imageProcessingConfiguration.contrast = value;
  41466. },
  41467. enumerable: true,
  41468. configurable: true
  41469. });
  41470. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41471. /**
  41472. * Gets the Color Grading 2D Lookup Texture.
  41473. */
  41474. get: function () {
  41475. return this._imageProcessingConfiguration.colorGradingTexture;
  41476. },
  41477. /**
  41478. * Sets the Color Grading 2D Lookup Texture.
  41479. */
  41480. set: function (value) {
  41481. this._imageProcessingConfiguration.colorGradingTexture = value;
  41482. },
  41483. enumerable: true,
  41484. configurable: true
  41485. });
  41486. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41487. /**
  41488. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41489. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41490. * 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;
  41491. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41492. */
  41493. get: function () {
  41494. return this._imageProcessingConfiguration.colorCurves;
  41495. },
  41496. /**
  41497. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41498. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41499. * 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;
  41500. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41501. */
  41502. set: function (value) {
  41503. this._imageProcessingConfiguration.colorCurves = value;
  41504. },
  41505. enumerable: true,
  41506. configurable: true
  41507. });
  41508. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41509. /**
  41510. * Gets a boolean indicating that current material needs to register RTT
  41511. */
  41512. get: function () {
  41513. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41514. return true;
  41515. }
  41516. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41517. return true;
  41518. }
  41519. return false;
  41520. },
  41521. enumerable: true,
  41522. configurable: true
  41523. });
  41524. StandardMaterial.prototype.getClassName = function () {
  41525. return "StandardMaterial";
  41526. };
  41527. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41528. get: function () {
  41529. return this._useLogarithmicDepth;
  41530. },
  41531. set: function (value) {
  41532. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41533. this._markAllSubMeshesAsMiscDirty();
  41534. },
  41535. enumerable: true,
  41536. configurable: true
  41537. });
  41538. StandardMaterial.prototype.needAlphaBlending = function () {
  41539. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41540. };
  41541. StandardMaterial.prototype.needAlphaTesting = function () {
  41542. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41543. };
  41544. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41545. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41546. };
  41547. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41548. return this._diffuseTexture;
  41549. };
  41550. /**
  41551. * Child classes can use it to update shaders
  41552. */
  41553. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41554. if (useInstances === void 0) { useInstances = false; }
  41555. if (subMesh.effect && this.isFrozen) {
  41556. if (this._wasPreviouslyReady) {
  41557. return true;
  41558. }
  41559. }
  41560. if (!subMesh._materialDefines) {
  41561. subMesh._materialDefines = new StandardMaterialDefines();
  41562. }
  41563. var scene = this.getScene();
  41564. var defines = subMesh._materialDefines;
  41565. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41566. if (defines._renderId === scene.getRenderId()) {
  41567. return true;
  41568. }
  41569. }
  41570. var engine = scene.getEngine();
  41571. // Lights
  41572. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41573. // Textures
  41574. if (defines._areTexturesDirty) {
  41575. defines._needUVs = false;
  41576. defines.MAINUV1 = false;
  41577. defines.MAINUV2 = false;
  41578. if (scene.texturesEnabled) {
  41579. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41580. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41581. return false;
  41582. }
  41583. else {
  41584. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41585. }
  41586. }
  41587. else {
  41588. defines.DIFFUSE = false;
  41589. }
  41590. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41591. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41592. return false;
  41593. }
  41594. else {
  41595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41596. }
  41597. }
  41598. else {
  41599. defines.AMBIENT = false;
  41600. }
  41601. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41602. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41603. return false;
  41604. }
  41605. else {
  41606. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41607. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41608. }
  41609. }
  41610. else {
  41611. defines.OPACITY = false;
  41612. }
  41613. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41614. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41615. return false;
  41616. }
  41617. else {
  41618. defines._needNormals = true;
  41619. defines.REFLECTION = true;
  41620. defines.ROUGHNESS = (this._roughness > 0);
  41621. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41622. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41623. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41624. switch (this._reflectionTexture.coordinatesMode) {
  41625. case BABYLON.Texture.EXPLICIT_MODE:
  41626. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41627. break;
  41628. case BABYLON.Texture.PLANAR_MODE:
  41629. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41630. break;
  41631. case BABYLON.Texture.PROJECTION_MODE:
  41632. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41633. break;
  41634. case BABYLON.Texture.SKYBOX_MODE:
  41635. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41636. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41637. break;
  41638. case BABYLON.Texture.SPHERICAL_MODE:
  41639. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41640. break;
  41641. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41642. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41643. break;
  41644. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41645. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41646. break;
  41647. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41648. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41649. break;
  41650. case BABYLON.Texture.CUBIC_MODE:
  41651. case BABYLON.Texture.INVCUBIC_MODE:
  41652. default:
  41653. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41654. break;
  41655. }
  41656. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41657. }
  41658. }
  41659. else {
  41660. defines.REFLECTION = false;
  41661. }
  41662. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41663. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41664. return false;
  41665. }
  41666. else {
  41667. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41668. }
  41669. }
  41670. else {
  41671. defines.EMISSIVE = false;
  41672. }
  41673. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41674. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41675. return false;
  41676. }
  41677. else {
  41678. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41679. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41680. }
  41681. }
  41682. else {
  41683. defines.LIGHTMAP = false;
  41684. }
  41685. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41686. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41687. return false;
  41688. }
  41689. else {
  41690. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41691. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41692. }
  41693. }
  41694. else {
  41695. defines.SPECULAR = false;
  41696. }
  41697. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41698. // Bump texure can not be not blocking.
  41699. if (!this._bumpTexture.isReady()) {
  41700. return false;
  41701. }
  41702. else {
  41703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41704. defines.PARALLAX = this._useParallax;
  41705. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41706. }
  41707. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41708. }
  41709. else {
  41710. defines.BUMP = false;
  41711. }
  41712. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41713. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41714. return false;
  41715. }
  41716. else {
  41717. defines._needUVs = true;
  41718. defines.REFRACTION = true;
  41719. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41720. }
  41721. }
  41722. else {
  41723. defines.REFRACTION = false;
  41724. }
  41725. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41726. }
  41727. else {
  41728. defines.DIFFUSE = false;
  41729. defines.AMBIENT = false;
  41730. defines.OPACITY = false;
  41731. defines.REFLECTION = false;
  41732. defines.EMISSIVE = false;
  41733. defines.LIGHTMAP = false;
  41734. defines.BUMP = false;
  41735. defines.REFRACTION = false;
  41736. }
  41737. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41738. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41739. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41740. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41741. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41742. }
  41743. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41744. if (!this._imageProcessingConfiguration.isReady()) {
  41745. return false;
  41746. }
  41747. this._imageProcessingConfiguration.prepareDefines(defines);
  41748. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41749. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41750. }
  41751. if (defines._areFresnelDirty) {
  41752. if (StandardMaterial.FresnelEnabled) {
  41753. // Fresnel
  41754. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41755. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41756. this._reflectionFresnelParameters) {
  41757. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41758. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41759. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41760. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41761. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41762. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41763. defines._needNormals = true;
  41764. defines.FRESNEL = true;
  41765. }
  41766. }
  41767. else {
  41768. defines.FRESNEL = false;
  41769. }
  41770. }
  41771. // Misc.
  41772. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41773. // Attribs
  41774. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41775. // Values that need to be evaluated on every frame
  41776. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41777. // Get correct effect
  41778. if (defines.isDirty) {
  41779. defines.markAsProcessed();
  41780. scene.resetCachedMaterial();
  41781. // Fallbacks
  41782. var fallbacks = new BABYLON.EffectFallbacks();
  41783. if (defines.REFLECTION) {
  41784. fallbacks.addFallback(0, "REFLECTION");
  41785. }
  41786. if (defines.SPECULAR) {
  41787. fallbacks.addFallback(0, "SPECULAR");
  41788. }
  41789. if (defines.BUMP) {
  41790. fallbacks.addFallback(0, "BUMP");
  41791. }
  41792. if (defines.PARALLAX) {
  41793. fallbacks.addFallback(1, "PARALLAX");
  41794. }
  41795. if (defines.PARALLAXOCCLUSION) {
  41796. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41797. }
  41798. if (defines.SPECULAROVERALPHA) {
  41799. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41800. }
  41801. if (defines.FOG) {
  41802. fallbacks.addFallback(1, "FOG");
  41803. }
  41804. if (defines.POINTSIZE) {
  41805. fallbacks.addFallback(0, "POINTSIZE");
  41806. }
  41807. if (defines.LOGARITHMICDEPTH) {
  41808. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41809. }
  41810. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41811. if (defines.SPECULARTERM) {
  41812. fallbacks.addFallback(0, "SPECULARTERM");
  41813. }
  41814. if (defines.DIFFUSEFRESNEL) {
  41815. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41816. }
  41817. if (defines.OPACITYFRESNEL) {
  41818. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41819. }
  41820. if (defines.REFLECTIONFRESNEL) {
  41821. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41822. }
  41823. if (defines.EMISSIVEFRESNEL) {
  41824. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41825. }
  41826. if (defines.FRESNEL) {
  41827. fallbacks.addFallback(4, "FRESNEL");
  41828. }
  41829. //Attributes
  41830. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41831. if (defines.NORMAL) {
  41832. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41833. }
  41834. if (defines.UV1) {
  41835. attribs.push(BABYLON.VertexBuffer.UVKind);
  41836. }
  41837. if (defines.UV2) {
  41838. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41839. }
  41840. if (defines.VERTEXCOLOR) {
  41841. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41842. }
  41843. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41844. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41845. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41846. var shaderName = "default";
  41847. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41848. "vFogInfos", "vFogColor", "pointSize",
  41849. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41850. "mBones",
  41851. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41852. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41853. "vReflectionPosition", "vReflectionSize",
  41854. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41855. ];
  41856. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41857. var uniformBuffers = ["Material", "Scene"];
  41858. if (BABYLON.ImageProcessingConfiguration) {
  41859. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41860. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41861. }
  41862. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41863. uniformsNames: uniforms,
  41864. uniformBuffersNames: uniformBuffers,
  41865. samplers: samplers,
  41866. defines: defines,
  41867. maxSimultaneousLights: this._maxSimultaneousLights
  41868. });
  41869. if (this.customShaderNameResolve) {
  41870. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41871. }
  41872. var join = defines.toString();
  41873. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41874. attributes: attribs,
  41875. uniformsNames: uniforms,
  41876. uniformBuffersNames: uniformBuffers,
  41877. samplers: samplers,
  41878. defines: join,
  41879. fallbacks: fallbacks,
  41880. onCompiled: this.onCompiled,
  41881. onError: this.onError,
  41882. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41883. }, engine), defines);
  41884. this.buildUniformLayout();
  41885. }
  41886. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41887. return false;
  41888. }
  41889. defines._renderId = scene.getRenderId();
  41890. this._wasPreviouslyReady = true;
  41891. return true;
  41892. };
  41893. StandardMaterial.prototype.buildUniformLayout = function () {
  41894. // Order is important !
  41895. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41896. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41897. this._uniformBuffer.addUniform("opacityParts", 4);
  41898. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41899. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41900. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41901. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41902. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41903. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41904. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41905. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41906. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41907. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41908. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41909. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41910. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41911. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41912. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41913. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41914. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41915. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41916. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41917. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41918. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41919. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41920. this._uniformBuffer.addUniform("specularMatrix", 16);
  41921. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41922. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41923. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41924. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41925. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41926. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41927. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41928. this._uniformBuffer.addUniform("pointSize", 1);
  41929. this._uniformBuffer.create();
  41930. };
  41931. StandardMaterial.prototype.unbind = function () {
  41932. if (this._activeEffect) {
  41933. var needFlag = false;
  41934. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41935. this._activeEffect.setTexture("reflection2DSampler", null);
  41936. needFlag = true;
  41937. }
  41938. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41939. this._activeEffect.setTexture("refraction2DSampler", null);
  41940. needFlag = true;
  41941. }
  41942. if (needFlag) {
  41943. this._markAllSubMeshesAsTexturesDirty();
  41944. }
  41945. }
  41946. _super.prototype.unbind.call(this);
  41947. };
  41948. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41949. var scene = this.getScene();
  41950. var defines = subMesh._materialDefines;
  41951. if (!defines) {
  41952. return;
  41953. }
  41954. var effect = subMesh.effect;
  41955. if (!effect) {
  41956. return;
  41957. }
  41958. this._activeEffect = effect;
  41959. // Matrices
  41960. this.bindOnlyWorldMatrix(world);
  41961. // Normal Matrix
  41962. if (defines.OBJECTSPACE_NORMALMAP) {
  41963. world.toNormalMatrix(this._normalMatrix);
  41964. this.bindOnlyNormalMatrix(this._normalMatrix);
  41965. }
  41966. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41967. // Bones
  41968. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41969. if (mustRebind) {
  41970. this._uniformBuffer.bindToEffect(effect, "Material");
  41971. this.bindViewProjection(effect);
  41972. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41973. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41974. // Fresnel
  41975. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41976. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41977. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41978. }
  41979. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41980. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41981. }
  41982. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41983. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41984. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41985. }
  41986. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41987. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41988. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41989. }
  41990. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41991. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41992. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41993. }
  41994. }
  41995. // Textures
  41996. if (scene.texturesEnabled) {
  41997. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41998. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41999. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42000. if (this._diffuseTexture.hasAlpha) {
  42001. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42002. }
  42003. }
  42004. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42005. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42006. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42007. }
  42008. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42009. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42010. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42011. }
  42012. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42013. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42014. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42015. if (this._reflectionTexture.boundingBoxSize) {
  42016. var cubeTexture = this._reflectionTexture;
  42017. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42018. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42019. }
  42020. }
  42021. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42022. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42023. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42024. }
  42025. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42026. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42027. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42028. }
  42029. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42030. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42031. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42032. }
  42033. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42034. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42035. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42036. if (scene._mirroredCameraPosition) {
  42037. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42038. }
  42039. else {
  42040. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42041. }
  42042. }
  42043. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42044. var depth = 1.0;
  42045. if (!this._refractionTexture.isCube) {
  42046. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42047. if (this._refractionTexture.depth) {
  42048. depth = this._refractionTexture.depth;
  42049. }
  42050. }
  42051. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42052. }
  42053. }
  42054. // Point size
  42055. if (this.pointsCloud) {
  42056. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42057. }
  42058. if (defines.SPECULARTERM) {
  42059. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42060. }
  42061. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42062. // Diffuse
  42063. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42064. }
  42065. // Textures
  42066. if (scene.texturesEnabled) {
  42067. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42068. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42069. }
  42070. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42071. effect.setTexture("ambientSampler", this._ambientTexture);
  42072. }
  42073. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42074. effect.setTexture("opacitySampler", this._opacityTexture);
  42075. }
  42076. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42077. if (this._reflectionTexture.isCube) {
  42078. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42079. }
  42080. else {
  42081. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42082. }
  42083. }
  42084. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42085. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42086. }
  42087. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42088. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42089. }
  42090. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42091. effect.setTexture("specularSampler", this._specularTexture);
  42092. }
  42093. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42094. effect.setTexture("bumpSampler", this._bumpTexture);
  42095. }
  42096. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42097. var depth = 1.0;
  42098. if (this._refractionTexture.isCube) {
  42099. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42100. }
  42101. else {
  42102. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42103. }
  42104. }
  42105. }
  42106. // Clip plane
  42107. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42108. // Colors
  42109. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42110. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42111. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42112. }
  42113. if (mustRebind || !this.isFrozen) {
  42114. // Lights
  42115. if (scene.lightsEnabled && !this._disableLighting) {
  42116. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42117. }
  42118. // View
  42119. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42120. this.bindView(effect);
  42121. }
  42122. // Fog
  42123. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42124. // Morph targets
  42125. if (defines.NUM_MORPH_INFLUENCERS) {
  42126. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42127. }
  42128. // Log. depth
  42129. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42130. // image processing
  42131. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42132. this._imageProcessingConfiguration.bind(this._activeEffect);
  42133. }
  42134. }
  42135. this._uniformBuffer.update();
  42136. this._afterBind(mesh, this._activeEffect);
  42137. };
  42138. StandardMaterial.prototype.getAnimatables = function () {
  42139. var results = [];
  42140. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42141. results.push(this._diffuseTexture);
  42142. }
  42143. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42144. results.push(this._ambientTexture);
  42145. }
  42146. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42147. results.push(this._opacityTexture);
  42148. }
  42149. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42150. results.push(this._reflectionTexture);
  42151. }
  42152. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42153. results.push(this._emissiveTexture);
  42154. }
  42155. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42156. results.push(this._specularTexture);
  42157. }
  42158. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42159. results.push(this._bumpTexture);
  42160. }
  42161. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42162. results.push(this._lightmapTexture);
  42163. }
  42164. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42165. results.push(this._refractionTexture);
  42166. }
  42167. return results;
  42168. };
  42169. StandardMaterial.prototype.getActiveTextures = function () {
  42170. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42171. if (this._diffuseTexture) {
  42172. activeTextures.push(this._diffuseTexture);
  42173. }
  42174. if (this._ambientTexture) {
  42175. activeTextures.push(this._ambientTexture);
  42176. }
  42177. if (this._opacityTexture) {
  42178. activeTextures.push(this._opacityTexture);
  42179. }
  42180. if (this._reflectionTexture) {
  42181. activeTextures.push(this._reflectionTexture);
  42182. }
  42183. if (this._emissiveTexture) {
  42184. activeTextures.push(this._emissiveTexture);
  42185. }
  42186. if (this._specularTexture) {
  42187. activeTextures.push(this._specularTexture);
  42188. }
  42189. if (this._bumpTexture) {
  42190. activeTextures.push(this._bumpTexture);
  42191. }
  42192. if (this._lightmapTexture) {
  42193. activeTextures.push(this._lightmapTexture);
  42194. }
  42195. if (this._refractionTexture) {
  42196. activeTextures.push(this._refractionTexture);
  42197. }
  42198. return activeTextures;
  42199. };
  42200. StandardMaterial.prototype.hasTexture = function (texture) {
  42201. if (_super.prototype.hasTexture.call(this, texture)) {
  42202. return true;
  42203. }
  42204. if (this._diffuseTexture === texture) {
  42205. return true;
  42206. }
  42207. if (this._ambientTexture === texture) {
  42208. return true;
  42209. }
  42210. if (this._opacityTexture === texture) {
  42211. return true;
  42212. }
  42213. if (this._reflectionTexture === texture) {
  42214. return true;
  42215. }
  42216. if (this._emissiveTexture === texture) {
  42217. return true;
  42218. }
  42219. if (this._specularTexture === texture) {
  42220. return true;
  42221. }
  42222. if (this._bumpTexture === texture) {
  42223. return true;
  42224. }
  42225. if (this._lightmapTexture === texture) {
  42226. return true;
  42227. }
  42228. if (this._refractionTexture === texture) {
  42229. return true;
  42230. }
  42231. return false;
  42232. };
  42233. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42234. if (forceDisposeTextures) {
  42235. if (this._diffuseTexture) {
  42236. this._diffuseTexture.dispose();
  42237. }
  42238. if (this._ambientTexture) {
  42239. this._ambientTexture.dispose();
  42240. }
  42241. if (this._opacityTexture) {
  42242. this._opacityTexture.dispose();
  42243. }
  42244. if (this._reflectionTexture) {
  42245. this._reflectionTexture.dispose();
  42246. }
  42247. if (this._emissiveTexture) {
  42248. this._emissiveTexture.dispose();
  42249. }
  42250. if (this._specularTexture) {
  42251. this._specularTexture.dispose();
  42252. }
  42253. if (this._bumpTexture) {
  42254. this._bumpTexture.dispose();
  42255. }
  42256. if (this._lightmapTexture) {
  42257. this._lightmapTexture.dispose();
  42258. }
  42259. if (this._refractionTexture) {
  42260. this._refractionTexture.dispose();
  42261. }
  42262. }
  42263. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42264. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42265. }
  42266. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42267. };
  42268. StandardMaterial.prototype.clone = function (name) {
  42269. var _this = this;
  42270. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42271. result.name = name;
  42272. result.id = name;
  42273. return result;
  42274. };
  42275. StandardMaterial.prototype.serialize = function () {
  42276. return BABYLON.SerializationHelper.Serialize(this);
  42277. };
  42278. // Statics
  42279. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42280. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42281. };
  42282. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42283. get: function () {
  42284. return StandardMaterial._DiffuseTextureEnabled;
  42285. },
  42286. set: function (value) {
  42287. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42288. return;
  42289. }
  42290. StandardMaterial._DiffuseTextureEnabled = value;
  42291. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42292. },
  42293. enumerable: true,
  42294. configurable: true
  42295. });
  42296. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42297. get: function () {
  42298. return StandardMaterial._AmbientTextureEnabled;
  42299. },
  42300. set: function (value) {
  42301. if (StandardMaterial._AmbientTextureEnabled === value) {
  42302. return;
  42303. }
  42304. StandardMaterial._AmbientTextureEnabled = value;
  42305. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42306. },
  42307. enumerable: true,
  42308. configurable: true
  42309. });
  42310. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42311. get: function () {
  42312. return StandardMaterial._OpacityTextureEnabled;
  42313. },
  42314. set: function (value) {
  42315. if (StandardMaterial._OpacityTextureEnabled === value) {
  42316. return;
  42317. }
  42318. StandardMaterial._OpacityTextureEnabled = value;
  42319. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42320. },
  42321. enumerable: true,
  42322. configurable: true
  42323. });
  42324. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42325. get: function () {
  42326. return StandardMaterial._ReflectionTextureEnabled;
  42327. },
  42328. set: function (value) {
  42329. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42330. return;
  42331. }
  42332. StandardMaterial._ReflectionTextureEnabled = value;
  42333. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42334. },
  42335. enumerable: true,
  42336. configurable: true
  42337. });
  42338. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42339. get: function () {
  42340. return StandardMaterial._EmissiveTextureEnabled;
  42341. },
  42342. set: function (value) {
  42343. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42344. return;
  42345. }
  42346. StandardMaterial._EmissiveTextureEnabled = value;
  42347. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42348. },
  42349. enumerable: true,
  42350. configurable: true
  42351. });
  42352. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42353. get: function () {
  42354. return StandardMaterial._SpecularTextureEnabled;
  42355. },
  42356. set: function (value) {
  42357. if (StandardMaterial._SpecularTextureEnabled === value) {
  42358. return;
  42359. }
  42360. StandardMaterial._SpecularTextureEnabled = value;
  42361. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42362. },
  42363. enumerable: true,
  42364. configurable: true
  42365. });
  42366. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42367. get: function () {
  42368. return StandardMaterial._BumpTextureEnabled;
  42369. },
  42370. set: function (value) {
  42371. if (StandardMaterial._BumpTextureEnabled === value) {
  42372. return;
  42373. }
  42374. StandardMaterial._BumpTextureEnabled = value;
  42375. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42376. },
  42377. enumerable: true,
  42378. configurable: true
  42379. });
  42380. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42381. get: function () {
  42382. return StandardMaterial._LightmapTextureEnabled;
  42383. },
  42384. set: function (value) {
  42385. if (StandardMaterial._LightmapTextureEnabled === value) {
  42386. return;
  42387. }
  42388. StandardMaterial._LightmapTextureEnabled = value;
  42389. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42395. get: function () {
  42396. return StandardMaterial._RefractionTextureEnabled;
  42397. },
  42398. set: function (value) {
  42399. if (StandardMaterial._RefractionTextureEnabled === value) {
  42400. return;
  42401. }
  42402. StandardMaterial._RefractionTextureEnabled = value;
  42403. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42404. },
  42405. enumerable: true,
  42406. configurable: true
  42407. });
  42408. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42409. get: function () {
  42410. return StandardMaterial._ColorGradingTextureEnabled;
  42411. },
  42412. set: function (value) {
  42413. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42414. return;
  42415. }
  42416. StandardMaterial._ColorGradingTextureEnabled = value;
  42417. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42418. },
  42419. enumerable: true,
  42420. configurable: true
  42421. });
  42422. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42423. get: function () {
  42424. return StandardMaterial._FresnelEnabled;
  42425. },
  42426. set: function (value) {
  42427. if (StandardMaterial._FresnelEnabled === value) {
  42428. return;
  42429. }
  42430. StandardMaterial._FresnelEnabled = value;
  42431. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42432. },
  42433. enumerable: true,
  42434. configurable: true
  42435. });
  42436. // Flags used to enable or disable a type of texture for all Standard Materials
  42437. StandardMaterial._DiffuseTextureEnabled = true;
  42438. StandardMaterial._AmbientTextureEnabled = true;
  42439. StandardMaterial._OpacityTextureEnabled = true;
  42440. StandardMaterial._ReflectionTextureEnabled = true;
  42441. StandardMaterial._EmissiveTextureEnabled = true;
  42442. StandardMaterial._SpecularTextureEnabled = true;
  42443. StandardMaterial._BumpTextureEnabled = true;
  42444. StandardMaterial._LightmapTextureEnabled = true;
  42445. StandardMaterial._RefractionTextureEnabled = true;
  42446. StandardMaterial._ColorGradingTextureEnabled = true;
  42447. StandardMaterial._FresnelEnabled = true;
  42448. __decorate([
  42449. BABYLON.serializeAsTexture("diffuseTexture")
  42450. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42451. __decorate([
  42452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42453. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42454. __decorate([
  42455. BABYLON.serializeAsTexture("ambientTexture")
  42456. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42457. __decorate([
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42460. __decorate([
  42461. BABYLON.serializeAsTexture("opacityTexture")
  42462. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42463. __decorate([
  42464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42465. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42466. __decorate([
  42467. BABYLON.serializeAsTexture("reflectionTexture")
  42468. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42469. __decorate([
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serializeAsTexture("emissiveTexture")
  42474. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42475. __decorate([
  42476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42477. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42478. __decorate([
  42479. BABYLON.serializeAsTexture("specularTexture")
  42480. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42481. __decorate([
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42483. ], StandardMaterial.prototype, "specularTexture", void 0);
  42484. __decorate([
  42485. BABYLON.serializeAsTexture("bumpTexture")
  42486. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42487. __decorate([
  42488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42489. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42490. __decorate([
  42491. BABYLON.serializeAsTexture("lightmapTexture")
  42492. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42493. __decorate([
  42494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42495. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42496. __decorate([
  42497. BABYLON.serializeAsTexture("refractionTexture")
  42498. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42499. __decorate([
  42500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42501. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42502. __decorate([
  42503. BABYLON.serializeAsColor3("ambient")
  42504. ], StandardMaterial.prototype, "ambientColor", void 0);
  42505. __decorate([
  42506. BABYLON.serializeAsColor3("diffuse")
  42507. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42508. __decorate([
  42509. BABYLON.serializeAsColor3("specular")
  42510. ], StandardMaterial.prototype, "specularColor", void 0);
  42511. __decorate([
  42512. BABYLON.serializeAsColor3("emissive")
  42513. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42514. __decorate([
  42515. BABYLON.serialize()
  42516. ], StandardMaterial.prototype, "specularPower", void 0);
  42517. __decorate([
  42518. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42519. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42520. __decorate([
  42521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42522. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42523. __decorate([
  42524. BABYLON.serialize("useEmissiveAsIllumination")
  42525. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42526. __decorate([
  42527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42528. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42529. __decorate([
  42530. BABYLON.serialize("linkEmissiveWithDiffuse")
  42531. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42532. __decorate([
  42533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42534. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42535. __decorate([
  42536. BABYLON.serialize("useSpecularOverAlpha")
  42537. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42538. __decorate([
  42539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42540. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42541. __decorate([
  42542. BABYLON.serialize("useReflectionOverAlpha")
  42543. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42544. __decorate([
  42545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42546. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42547. __decorate([
  42548. BABYLON.serialize("disableLighting")
  42549. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42550. __decorate([
  42551. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42552. ], StandardMaterial.prototype, "disableLighting", void 0);
  42553. __decorate([
  42554. BABYLON.serialize("useObjectSpaceNormalMap")
  42555. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42556. __decorate([
  42557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42558. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42559. __decorate([
  42560. BABYLON.serialize("useParallax")
  42561. ], StandardMaterial.prototype, "_useParallax", void 0);
  42562. __decorate([
  42563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42564. ], StandardMaterial.prototype, "useParallax", void 0);
  42565. __decorate([
  42566. BABYLON.serialize("useParallaxOcclusion")
  42567. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42568. __decorate([
  42569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42570. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42571. __decorate([
  42572. BABYLON.serialize()
  42573. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42574. __decorate([
  42575. BABYLON.serialize("roughness")
  42576. ], StandardMaterial.prototype, "_roughness", void 0);
  42577. __decorate([
  42578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42579. ], StandardMaterial.prototype, "roughness", void 0);
  42580. __decorate([
  42581. BABYLON.serialize()
  42582. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42583. __decorate([
  42584. BABYLON.serialize()
  42585. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42586. __decorate([
  42587. BABYLON.serialize()
  42588. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42589. __decorate([
  42590. BABYLON.serialize("useLightmapAsShadowmap")
  42591. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42592. __decorate([
  42593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42594. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42595. __decorate([
  42596. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42597. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42598. __decorate([
  42599. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42600. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42601. __decorate([
  42602. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42603. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42604. __decorate([
  42605. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42606. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42607. __decorate([
  42608. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42609. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42610. __decorate([
  42611. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42612. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42613. __decorate([
  42614. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42615. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42616. __decorate([
  42617. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42618. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42619. __decorate([
  42620. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42621. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42622. __decorate([
  42623. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42624. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42625. __decorate([
  42626. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42627. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42628. __decorate([
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42630. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42631. __decorate([
  42632. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42633. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42634. __decorate([
  42635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42636. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42637. __decorate([
  42638. BABYLON.serialize("maxSimultaneousLights")
  42639. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42640. __decorate([
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42642. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42643. __decorate([
  42644. BABYLON.serialize("invertNormalMapX")
  42645. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42646. __decorate([
  42647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42648. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42649. __decorate([
  42650. BABYLON.serialize("invertNormalMapY")
  42651. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42652. __decorate([
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42654. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42655. __decorate([
  42656. BABYLON.serialize("twoSidedLighting")
  42657. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42658. __decorate([
  42659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42660. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42661. __decorate([
  42662. BABYLON.serialize()
  42663. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42664. return StandardMaterial;
  42665. }(BABYLON.PushMaterial));
  42666. BABYLON.StandardMaterial = StandardMaterial;
  42667. })(BABYLON || (BABYLON = {}));
  42668. //# sourceMappingURL=babylon.standardMaterial.js.map
  42669. var BABYLON;
  42670. (function (BABYLON) {
  42671. /**
  42672. * Class representing spherical polynomial coefficients to the 3rd degree
  42673. */
  42674. var SphericalPolynomial = /** @class */ (function () {
  42675. function SphericalPolynomial() {
  42676. /**
  42677. * The x coefficients of the spherical polynomial
  42678. */
  42679. this.x = BABYLON.Vector3.Zero();
  42680. /**
  42681. * The y coefficients of the spherical polynomial
  42682. */
  42683. this.y = BABYLON.Vector3.Zero();
  42684. /**
  42685. * The z coefficients of the spherical polynomial
  42686. */
  42687. this.z = BABYLON.Vector3.Zero();
  42688. /**
  42689. * The xx coefficients of the spherical polynomial
  42690. */
  42691. this.xx = BABYLON.Vector3.Zero();
  42692. /**
  42693. * The yy coefficients of the spherical polynomial
  42694. */
  42695. this.yy = BABYLON.Vector3.Zero();
  42696. /**
  42697. * The zz coefficients of the spherical polynomial
  42698. */
  42699. this.zz = BABYLON.Vector3.Zero();
  42700. /**
  42701. * The xy coefficients of the spherical polynomial
  42702. */
  42703. this.xy = BABYLON.Vector3.Zero();
  42704. /**
  42705. * The yz coefficients of the spherical polynomial
  42706. */
  42707. this.yz = BABYLON.Vector3.Zero();
  42708. /**
  42709. * The zx coefficients of the spherical polynomial
  42710. */
  42711. this.zx = BABYLON.Vector3.Zero();
  42712. }
  42713. /**
  42714. * Adds an ambient color to the spherical polynomial
  42715. * @param color the color to add
  42716. */
  42717. SphericalPolynomial.prototype.addAmbient = function (color) {
  42718. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42719. this.xx = this.xx.add(colorVector);
  42720. this.yy = this.yy.add(colorVector);
  42721. this.zz = this.zz.add(colorVector);
  42722. };
  42723. /**
  42724. * Scales the spherical polynomial by the given amount
  42725. * @param scale the amount to scale
  42726. */
  42727. SphericalPolynomial.prototype.scale = function (scale) {
  42728. this.x = this.x.scale(scale);
  42729. this.y = this.y.scale(scale);
  42730. this.z = this.z.scale(scale);
  42731. this.xx = this.xx.scale(scale);
  42732. this.yy = this.yy.scale(scale);
  42733. this.zz = this.zz.scale(scale);
  42734. this.yz = this.yz.scale(scale);
  42735. this.zx = this.zx.scale(scale);
  42736. this.xy = this.xy.scale(scale);
  42737. };
  42738. /**
  42739. * Gets the spherical polynomial from harmonics
  42740. * @param harmonics the spherical harmonics
  42741. * @returns the spherical polynomial
  42742. */
  42743. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42744. var result = new SphericalPolynomial();
  42745. result.x = harmonics.l11.scale(1.02333);
  42746. result.y = harmonics.l1_1.scale(1.02333);
  42747. result.z = harmonics.l10.scale(1.02333);
  42748. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42749. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42750. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42751. result.yz = harmonics.l2_1.scale(0.858086);
  42752. result.zx = harmonics.l21.scale(0.858086);
  42753. result.xy = harmonics.l2_2.scale(0.858086);
  42754. result.scale(1.0 / Math.PI);
  42755. return result;
  42756. };
  42757. /**
  42758. * Constructs a spherical polynomial from an array.
  42759. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42760. * @returns the spherical polynomial
  42761. */
  42762. SphericalPolynomial.FromArray = function (data) {
  42763. var sp = new SphericalPolynomial();
  42764. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42765. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42766. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42767. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42768. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42769. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42770. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42771. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42772. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42773. return sp;
  42774. };
  42775. return SphericalPolynomial;
  42776. }());
  42777. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42778. /**
  42779. * Class representing spherical harmonics coefficients to the 3rd degree
  42780. */
  42781. var SphericalHarmonics = /** @class */ (function () {
  42782. function SphericalHarmonics() {
  42783. /**
  42784. * The l0,0 coefficients of the spherical harmonics
  42785. */
  42786. this.l00 = BABYLON.Vector3.Zero();
  42787. /**
  42788. * The l1,-1 coefficients of the spherical harmonics
  42789. */
  42790. this.l1_1 = BABYLON.Vector3.Zero();
  42791. /**
  42792. * The l1,0 coefficients of the spherical harmonics
  42793. */
  42794. this.l10 = BABYLON.Vector3.Zero();
  42795. /**
  42796. * The l1,1 coefficients of the spherical harmonics
  42797. */
  42798. this.l11 = BABYLON.Vector3.Zero();
  42799. /**
  42800. * The l2,-2 coefficients of the spherical harmonics
  42801. */
  42802. this.l2_2 = BABYLON.Vector3.Zero();
  42803. /**
  42804. * The l2,-1 coefficients of the spherical harmonics
  42805. */
  42806. this.l2_1 = BABYLON.Vector3.Zero();
  42807. /**
  42808. * The l2,0 coefficients of the spherical harmonics
  42809. */
  42810. this.l20 = BABYLON.Vector3.Zero();
  42811. /**
  42812. * The l2,1 coefficients of the spherical harmonics
  42813. */
  42814. this.l21 = BABYLON.Vector3.Zero();
  42815. /**
  42816. * The l2,2 coefficients of the spherical harmonics
  42817. */
  42818. this.lL22 = BABYLON.Vector3.Zero();
  42819. }
  42820. /**
  42821. * Adds a light to the spherical harmonics
  42822. * @param direction the direction of the light
  42823. * @param color the color of the light
  42824. * @param deltaSolidAngle the delta solid angle of the light
  42825. */
  42826. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42827. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42828. var c = colorVector.scale(deltaSolidAngle);
  42829. this.l00 = this.l00.add(c.scale(0.282095));
  42830. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42831. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42832. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42833. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42834. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42835. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42836. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42837. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42838. };
  42839. /**
  42840. * Scales the spherical harmonics by the given amount
  42841. * @param scale the amount to scale
  42842. */
  42843. SphericalHarmonics.prototype.scale = function (scale) {
  42844. this.l00 = this.l00.scale(scale);
  42845. this.l1_1 = this.l1_1.scale(scale);
  42846. this.l10 = this.l10.scale(scale);
  42847. this.l11 = this.l11.scale(scale);
  42848. this.l2_2 = this.l2_2.scale(scale);
  42849. this.l2_1 = this.l2_1.scale(scale);
  42850. this.l20 = this.l20.scale(scale);
  42851. this.l21 = this.l21.scale(scale);
  42852. this.lL22 = this.lL22.scale(scale);
  42853. };
  42854. /**
  42855. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42856. *
  42857. * ```
  42858. * E_lm = A_l * L_lm
  42859. * ```
  42860. *
  42861. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42862. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42863. * the scaling factors are given in equation 9.
  42864. */
  42865. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42866. // Constant (Band 0)
  42867. this.l00 = this.l00.scale(3.141593);
  42868. // Linear (Band 1)
  42869. this.l1_1 = this.l1_1.scale(2.094395);
  42870. this.l10 = this.l10.scale(2.094395);
  42871. this.l11 = this.l11.scale(2.094395);
  42872. // Quadratic (Band 2)
  42873. this.l2_2 = this.l2_2.scale(0.785398);
  42874. this.l2_1 = this.l2_1.scale(0.785398);
  42875. this.l20 = this.l20.scale(0.785398);
  42876. this.l21 = this.l21.scale(0.785398);
  42877. this.lL22 = this.lL22.scale(0.785398);
  42878. };
  42879. /**
  42880. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42881. *
  42882. * ```
  42883. * L = (1/pi) * E * rho
  42884. * ```
  42885. *
  42886. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42887. */
  42888. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42889. this.scale(1.0 / Math.PI);
  42890. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42891. // (The pixel shader must apply albedo after texture fetches, etc).
  42892. };
  42893. /**
  42894. * Gets the spherical harmonics from polynomial
  42895. * @param polynomial the spherical polynomial
  42896. * @returns the spherical harmonics
  42897. */
  42898. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42899. var result = new SphericalHarmonics();
  42900. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42901. result.l1_1 = polynomial.y.scale(0.977204);
  42902. result.l10 = polynomial.z.scale(0.977204);
  42903. result.l11 = polynomial.x.scale(0.977204);
  42904. result.l2_2 = polynomial.xy.scale(1.16538);
  42905. result.l2_1 = polynomial.yz.scale(1.16538);
  42906. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42907. result.l21 = polynomial.zx.scale(1.16538);
  42908. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42909. result.scale(Math.PI);
  42910. return result;
  42911. };
  42912. /**
  42913. * Constructs a spherical harmonics from an array.
  42914. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42915. * @returns the spherical harmonics
  42916. */
  42917. SphericalHarmonics.FromArray = function (data) {
  42918. var sh = new SphericalHarmonics();
  42919. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42920. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42921. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42922. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42923. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42924. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42925. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42926. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42927. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42928. return sh;
  42929. };
  42930. return SphericalHarmonics;
  42931. }());
  42932. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42933. })(BABYLON || (BABYLON = {}));
  42934. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42935. var BABYLON;
  42936. (function (BABYLON) {
  42937. var FileFaceOrientation = /** @class */ (function () {
  42938. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42939. this.name = name;
  42940. this.worldAxisForNormal = worldAxisForNormal;
  42941. this.worldAxisForFileX = worldAxisForFileX;
  42942. this.worldAxisForFileY = worldAxisForFileY;
  42943. }
  42944. return FileFaceOrientation;
  42945. }());
  42946. ;
  42947. /**
  42948. * Helper class dealing with the extraction of spherical polynomial dataArray
  42949. * from a cube map.
  42950. */
  42951. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42952. function CubeMapToSphericalPolynomialTools() {
  42953. }
  42954. /**
  42955. * Converts a texture to the according Spherical Polynomial data.
  42956. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42957. *
  42958. * @param texture The texture to extract the information from.
  42959. * @return The Spherical Polynomial data.
  42960. */
  42961. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42962. if (!texture.isCube) {
  42963. // Only supports cube Textures currently.
  42964. return null;
  42965. }
  42966. var size = texture.getSize().width;
  42967. var right = texture.readPixels(0);
  42968. var left = texture.readPixels(1);
  42969. var up;
  42970. var down;
  42971. if (texture.isRenderTarget) {
  42972. up = texture.readPixels(3);
  42973. down = texture.readPixels(2);
  42974. }
  42975. else {
  42976. up = texture.readPixels(2);
  42977. down = texture.readPixels(3);
  42978. }
  42979. var front = texture.readPixels(4);
  42980. var back = texture.readPixels(5);
  42981. var gammaSpace = texture.gammaSpace;
  42982. // Always read as RGBA.
  42983. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42984. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42985. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42986. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42987. }
  42988. var cubeInfo = {
  42989. size: size,
  42990. right: right,
  42991. left: left,
  42992. up: up,
  42993. down: down,
  42994. front: front,
  42995. back: back,
  42996. format: format,
  42997. type: type,
  42998. gammaSpace: gammaSpace,
  42999. };
  43000. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43001. };
  43002. /**
  43003. * Converts a cubemap to the according Spherical Polynomial data.
  43004. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43005. *
  43006. * @param cubeInfo The Cube map to extract the information from.
  43007. * @return The Spherical Polynomial data.
  43008. */
  43009. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43010. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43011. var totalSolidAngle = 0.0;
  43012. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43013. var du = 2.0 / cubeInfo.size;
  43014. var dv = du;
  43015. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43016. var minUV = du * 0.5 - 1.0;
  43017. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43018. var fileFace = this.FileFaces[faceIndex];
  43019. var dataArray = cubeInfo[fileFace.name];
  43020. var v = minUV;
  43021. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43022. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43023. // Because SP is still linear, so summation is fine in that basis.
  43024. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43025. for (var y = 0; y < cubeInfo.size; y++) {
  43026. var u = minUV;
  43027. for (var x = 0; x < cubeInfo.size; x++) {
  43028. // World direction (not normalised)
  43029. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43030. worldDirection.normalize();
  43031. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43032. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43033. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43034. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43035. // Handle Integer types.
  43036. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43037. r /= 255;
  43038. g /= 255;
  43039. b /= 255;
  43040. }
  43041. // Handle Gamma space textures.
  43042. if (cubeInfo.gammaSpace) {
  43043. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43044. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43045. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43046. }
  43047. var color = new BABYLON.Color3(r, g, b);
  43048. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43049. totalSolidAngle += deltaSolidAngle;
  43050. u += du;
  43051. }
  43052. v += dv;
  43053. }
  43054. }
  43055. // Solid angle for entire sphere is 4*pi
  43056. var sphereSolidAngle = 4.0 * Math.PI;
  43057. // Adjust the solid angle to allow for how many faces we processed.
  43058. var facesProcessed = 6.0;
  43059. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43060. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43061. // This is needed because the numerical integration over the cube uses a
  43062. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43063. // and also to compensate for accumulative error due to float precision in the summation.
  43064. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43065. sphericalHarmonics.scale(correctionFactor);
  43066. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43067. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43068. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43069. };
  43070. CubeMapToSphericalPolynomialTools.FileFaces = [
  43071. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43072. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43073. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43074. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43075. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43076. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43077. ];
  43078. return CubeMapToSphericalPolynomialTools;
  43079. }());
  43080. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43081. })(BABYLON || (BABYLON = {}));
  43082. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43083. var BABYLON;
  43084. (function (BABYLON) {
  43085. /**
  43086. * Manages the defines for the PBR Material.
  43087. * @hiddenChildren
  43088. */
  43089. var PBRMaterialDefines = /** @class */ (function (_super) {
  43090. __extends(PBRMaterialDefines, _super);
  43091. /**
  43092. * Initializes the PBR Material defines.
  43093. */
  43094. function PBRMaterialDefines() {
  43095. var _this = _super.call(this) || this;
  43096. _this.PBR = true;
  43097. _this.MAINUV1 = false;
  43098. _this.MAINUV2 = false;
  43099. _this.UV1 = false;
  43100. _this.UV2 = false;
  43101. _this.ALBEDO = false;
  43102. _this.ALBEDODIRECTUV = 0;
  43103. _this.VERTEXCOLOR = false;
  43104. _this.AMBIENT = false;
  43105. _this.AMBIENTDIRECTUV = 0;
  43106. _this.AMBIENTINGRAYSCALE = false;
  43107. _this.OPACITY = false;
  43108. _this.VERTEXALPHA = false;
  43109. _this.OPACITYDIRECTUV = 0;
  43110. _this.OPACITYRGB = false;
  43111. _this.ALPHATEST = false;
  43112. _this.DEPTHPREPASS = false;
  43113. _this.ALPHABLEND = false;
  43114. _this.ALPHAFROMALBEDO = false;
  43115. _this.ALPHATESTVALUE = "0.5";
  43116. _this.SPECULAROVERALPHA = false;
  43117. _this.RADIANCEOVERALPHA = false;
  43118. _this.ALPHAFRESNEL = false;
  43119. _this.LINEARALPHAFRESNEL = false;
  43120. _this.PREMULTIPLYALPHA = false;
  43121. _this.EMISSIVE = false;
  43122. _this.EMISSIVEDIRECTUV = 0;
  43123. _this.REFLECTIVITY = false;
  43124. _this.REFLECTIVITYDIRECTUV = 0;
  43125. _this.SPECULARTERM = false;
  43126. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43127. _this.MICROSURFACEAUTOMATIC = false;
  43128. _this.LODBASEDMICROSFURACE = false;
  43129. _this.MICROSURFACEMAP = false;
  43130. _this.MICROSURFACEMAPDIRECTUV = 0;
  43131. _this.METALLICWORKFLOW = false;
  43132. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43133. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43134. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43135. _this.AOSTOREINMETALMAPRED = false;
  43136. _this.ENVIRONMENTBRDF = false;
  43137. _this.NORMAL = false;
  43138. _this.TANGENT = false;
  43139. _this.BUMP = false;
  43140. _this.BUMPDIRECTUV = 0;
  43141. _this.OBJECTSPACE_NORMALMAP = false;
  43142. _this.PARALLAX = false;
  43143. _this.PARALLAXOCCLUSION = false;
  43144. _this.NORMALXYSCALE = true;
  43145. _this.LIGHTMAP = false;
  43146. _this.LIGHTMAPDIRECTUV = 0;
  43147. _this.USELIGHTMAPASSHADOWMAP = false;
  43148. _this.GAMMALIGHTMAP = false;
  43149. _this.REFLECTION = false;
  43150. _this.REFLECTIONMAP_3D = false;
  43151. _this.REFLECTIONMAP_SPHERICAL = false;
  43152. _this.REFLECTIONMAP_PLANAR = false;
  43153. _this.REFLECTIONMAP_CUBIC = false;
  43154. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43155. _this.REFLECTIONMAP_PROJECTION = false;
  43156. _this.REFLECTIONMAP_SKYBOX = false;
  43157. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43158. _this.REFLECTIONMAP_EXPLICIT = false;
  43159. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43160. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43161. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43162. _this.INVERTCUBICMAP = false;
  43163. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43164. _this.USESPHERICALINVERTEX = false;
  43165. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43166. _this.LODINREFLECTIONALPHA = false;
  43167. _this.GAMMAREFLECTION = false;
  43168. _this.RGBDREFLECTION = false;
  43169. _this.RADIANCEOCCLUSION = false;
  43170. _this.HORIZONOCCLUSION = false;
  43171. _this.REFRACTION = false;
  43172. _this.REFRACTIONMAP_3D = false;
  43173. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43174. _this.LODINREFRACTIONALPHA = false;
  43175. _this.GAMMAREFRACTION = false;
  43176. _this.RGBDREFRACTION = false;
  43177. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43178. _this.INSTANCES = false;
  43179. _this.NUM_BONE_INFLUENCERS = 0;
  43180. _this.BonesPerMesh = 0;
  43181. _this.NONUNIFORMSCALING = false;
  43182. _this.MORPHTARGETS = false;
  43183. _this.MORPHTARGETS_NORMAL = false;
  43184. _this.MORPHTARGETS_TANGENT = false;
  43185. _this.NUM_MORPH_INFLUENCERS = 0;
  43186. _this.IMAGEPROCESSING = false;
  43187. _this.VIGNETTE = false;
  43188. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43189. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43190. _this.TONEMAPPING = false;
  43191. _this.TONEMAPPING_ACES = false;
  43192. _this.CONTRAST = false;
  43193. _this.COLORCURVES = false;
  43194. _this.COLORGRADING = false;
  43195. _this.COLORGRADING3D = false;
  43196. _this.SAMPLER3DGREENDEPTH = false;
  43197. _this.SAMPLER3DBGRMAP = false;
  43198. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43199. _this.EXPOSURE = false;
  43200. _this.USEPHYSICALLIGHTFALLOFF = false;
  43201. _this.USEGLTFLIGHTFALLOFF = false;
  43202. _this.TWOSIDEDLIGHTING = false;
  43203. _this.SHADOWFLOAT = false;
  43204. _this.CLIPPLANE = false;
  43205. _this.CLIPPLANE2 = false;
  43206. _this.CLIPPLANE3 = false;
  43207. _this.CLIPPLANE4 = false;
  43208. _this.POINTSIZE = false;
  43209. _this.FOG = false;
  43210. _this.LOGARITHMICDEPTH = false;
  43211. _this.FORCENORMALFORWARD = false;
  43212. _this.SPECULARAA = false;
  43213. _this.UNLIT = false;
  43214. _this.rebuild();
  43215. return _this;
  43216. }
  43217. /**
  43218. * Resets the PBR Material defines.
  43219. */
  43220. PBRMaterialDefines.prototype.reset = function () {
  43221. _super.prototype.reset.call(this);
  43222. this.ALPHATESTVALUE = "0.5";
  43223. this.PBR = true;
  43224. };
  43225. return PBRMaterialDefines;
  43226. }(BABYLON.MaterialDefines));
  43227. /**
  43228. * The Physically based material base class of BJS.
  43229. *
  43230. * This offers the main features of a standard PBR material.
  43231. * For more information, please refer to the documentation :
  43232. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43233. */
  43234. var PBRBaseMaterial = /** @class */ (function (_super) {
  43235. __extends(PBRBaseMaterial, _super);
  43236. /**
  43237. * Instantiates a new PBRMaterial instance.
  43238. *
  43239. * @param name The material name
  43240. * @param scene The scene the material will be use in.
  43241. */
  43242. function PBRBaseMaterial(name, scene) {
  43243. var _this = _super.call(this, name, scene) || this;
  43244. /**
  43245. * Intensity of the direct lights e.g. the four lights available in your scene.
  43246. * This impacts both the direct diffuse and specular highlights.
  43247. */
  43248. _this._directIntensity = 1.0;
  43249. /**
  43250. * Intensity of the emissive part of the material.
  43251. * This helps controlling the emissive effect without modifying the emissive color.
  43252. */
  43253. _this._emissiveIntensity = 1.0;
  43254. /**
  43255. * Intensity of the environment e.g. how much the environment will light the object
  43256. * either through harmonics for rough material or through the refelction for shiny ones.
  43257. */
  43258. _this._environmentIntensity = 1.0;
  43259. /**
  43260. * This is a special control allowing the reduction of the specular highlights coming from the
  43261. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43262. */
  43263. _this._specularIntensity = 1.0;
  43264. /**
  43265. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43266. */
  43267. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43268. /**
  43269. * Debug Control allowing disabling the bump map on this material.
  43270. */
  43271. _this._disableBumpMap = false;
  43272. /**
  43273. * AKA Occlusion Texture Intensity in other nomenclature.
  43274. */
  43275. _this._ambientTextureStrength = 1.0;
  43276. /**
  43277. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43278. * 1 means it completely occludes it
  43279. * 0 mean it has no impact
  43280. */
  43281. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43282. /**
  43283. * The color of a material in ambient lighting.
  43284. */
  43285. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43286. /**
  43287. * AKA Diffuse Color in other nomenclature.
  43288. */
  43289. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43290. /**
  43291. * AKA Specular Color in other nomenclature.
  43292. */
  43293. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43294. /**
  43295. * The color applied when light is reflected from a material.
  43296. */
  43297. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43298. /**
  43299. * The color applied when light is emitted from a material.
  43300. */
  43301. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43302. /**
  43303. * AKA Glossiness in other nomenclature.
  43304. */
  43305. _this._microSurface = 0.9;
  43306. /**
  43307. * source material index of refraction (IOR)' / 'destination material IOR.
  43308. */
  43309. _this._indexOfRefraction = 0.66;
  43310. /**
  43311. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43312. */
  43313. _this._invertRefractionY = false;
  43314. /**
  43315. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43316. * Materials half opaque for instance using refraction could benefit from this control.
  43317. */
  43318. _this._linkRefractionWithTransparency = false;
  43319. /**
  43320. * Specifies that the material will use the light map as a show map.
  43321. */
  43322. _this._useLightmapAsShadowmap = false;
  43323. /**
  43324. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43325. * makes the reflect vector face the model (under horizon).
  43326. */
  43327. _this._useHorizonOcclusion = true;
  43328. /**
  43329. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43330. * too much the area relying on ambient texture to define their ambient occlusion.
  43331. */
  43332. _this._useRadianceOcclusion = true;
  43333. /**
  43334. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43335. */
  43336. _this._useAlphaFromAlbedoTexture = false;
  43337. /**
  43338. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43339. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43340. */
  43341. _this._useSpecularOverAlpha = true;
  43342. /**
  43343. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43344. */
  43345. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43346. /**
  43347. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43348. */
  43349. _this._useRoughnessFromMetallicTextureAlpha = true;
  43350. /**
  43351. * Specifies if the metallic texture contains the roughness information in its green channel.
  43352. */
  43353. _this._useRoughnessFromMetallicTextureGreen = false;
  43354. /**
  43355. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43356. */
  43357. _this._useMetallnessFromMetallicTextureBlue = false;
  43358. /**
  43359. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43360. */
  43361. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43362. /**
  43363. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43364. */
  43365. _this._useAmbientInGrayScale = false;
  43366. /**
  43367. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43368. * The material will try to infer what glossiness each pixel should be.
  43369. */
  43370. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43371. /**
  43372. * Defines the falloff type used in this material.
  43373. * It by default is Physical.
  43374. */
  43375. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43376. /**
  43377. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43378. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43379. */
  43380. _this._useRadianceOverAlpha = true;
  43381. /**
  43382. * Allows using an object space normal map (instead of tangent space).
  43383. */
  43384. _this._useObjectSpaceNormalMap = false;
  43385. /**
  43386. * Allows using the bump map in parallax mode.
  43387. */
  43388. _this._useParallax = false;
  43389. /**
  43390. * Allows using the bump map in parallax occlusion mode.
  43391. */
  43392. _this._useParallaxOcclusion = false;
  43393. /**
  43394. * Controls the scale bias of the parallax mode.
  43395. */
  43396. _this._parallaxScaleBias = 0.05;
  43397. /**
  43398. * If sets to true, disables all the lights affecting the material.
  43399. */
  43400. _this._disableLighting = false;
  43401. /**
  43402. * Number of Simultaneous lights allowed on the material.
  43403. */
  43404. _this._maxSimultaneousLights = 4;
  43405. /**
  43406. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43407. */
  43408. _this._invertNormalMapX = false;
  43409. /**
  43410. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43411. */
  43412. _this._invertNormalMapY = false;
  43413. /**
  43414. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43415. */
  43416. _this._twoSidedLighting = false;
  43417. /**
  43418. * Defines the alpha limits in alpha test mode.
  43419. */
  43420. _this._alphaCutOff = 0.4;
  43421. /**
  43422. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43423. */
  43424. _this._forceAlphaTest = false;
  43425. /**
  43426. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43427. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43428. */
  43429. _this._useAlphaFresnel = false;
  43430. /**
  43431. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43432. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43433. */
  43434. _this._useLinearAlphaFresnel = false;
  43435. /**
  43436. * The transparency mode of the material.
  43437. */
  43438. _this._transparencyMode = null;
  43439. /**
  43440. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43441. * from cos thetav and roughness:
  43442. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43443. */
  43444. _this._environmentBRDFTexture = null;
  43445. /**
  43446. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43447. */
  43448. _this._forceIrradianceInFragment = false;
  43449. /**
  43450. * Force normal to face away from face.
  43451. */
  43452. _this._forceNormalForward = false;
  43453. /**
  43454. * Enables specular anti aliasing in the PBR shader.
  43455. * It will both interacts on the Geometry for analytical and IBL lighting.
  43456. * It also prefilter the roughness map based on the bump values.
  43457. */
  43458. _this._enableSpecularAntiAliasing = false;
  43459. /**
  43460. * Stores the available render targets.
  43461. */
  43462. _this._renderTargets = new BABYLON.SmartArray(16);
  43463. /**
  43464. * Sets the global ambient color for the material used in lighting calculations.
  43465. */
  43466. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43467. /**
  43468. * If set to true, no lighting calculations will be applied.
  43469. */
  43470. _this._unlit = false;
  43471. // Setup the default processing configuration to the scene.
  43472. _this._attachImageProcessingConfiguration(null);
  43473. _this.getRenderTargetTextures = function () {
  43474. _this._renderTargets.reset();
  43475. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43476. _this._renderTargets.push(_this._reflectionTexture);
  43477. }
  43478. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43479. _this._renderTargets.push(_this._refractionTexture);
  43480. }
  43481. return _this._renderTargets;
  43482. };
  43483. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43484. return _this;
  43485. }
  43486. /**
  43487. * Attaches a new image processing configuration to the PBR Material.
  43488. * @param configuration
  43489. */
  43490. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43491. var _this = this;
  43492. if (configuration === this._imageProcessingConfiguration) {
  43493. return;
  43494. }
  43495. // Detaches observer.
  43496. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43497. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43498. }
  43499. // Pick the scene configuration if needed.
  43500. if (!configuration) {
  43501. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43502. }
  43503. else {
  43504. this._imageProcessingConfiguration = configuration;
  43505. }
  43506. // Attaches observer.
  43507. if (this._imageProcessingConfiguration) {
  43508. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43509. _this._markAllSubMeshesAsImageProcessingDirty();
  43510. });
  43511. }
  43512. };
  43513. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43514. /**
  43515. * Gets a boolean indicating that current material needs to register RTT
  43516. */
  43517. get: function () {
  43518. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43519. return true;
  43520. }
  43521. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43522. return true;
  43523. }
  43524. return false;
  43525. },
  43526. enumerable: true,
  43527. configurable: true
  43528. });
  43529. /**
  43530. * Gets the name of the material class.
  43531. */
  43532. PBRBaseMaterial.prototype.getClassName = function () {
  43533. return "PBRBaseMaterial";
  43534. };
  43535. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43536. /**
  43537. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43538. */
  43539. get: function () {
  43540. return this._useLogarithmicDepth;
  43541. },
  43542. /**
  43543. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43544. */
  43545. set: function (value) {
  43546. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43547. },
  43548. enumerable: true,
  43549. configurable: true
  43550. });
  43551. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43552. /**
  43553. * Gets the current transparency mode.
  43554. */
  43555. get: function () {
  43556. return this._transparencyMode;
  43557. },
  43558. /**
  43559. * Sets the transparency mode of the material.
  43560. *
  43561. * | Value | Type | Description |
  43562. * | ----- | ----------------------------------- | ----------- |
  43563. * | 0 | OPAQUE | |
  43564. * | 1 | ALPHATEST | |
  43565. * | 2 | ALPHABLEND | |
  43566. * | 3 | ALPHATESTANDBLEND | |
  43567. *
  43568. */
  43569. set: function (value) {
  43570. if (this._transparencyMode === value) {
  43571. return;
  43572. }
  43573. this._transparencyMode = value;
  43574. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43575. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43576. },
  43577. enumerable: true,
  43578. configurable: true
  43579. });
  43580. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43581. /**
  43582. * Returns true if alpha blending should be disabled.
  43583. */
  43584. get: function () {
  43585. return (this._linkRefractionWithTransparency ||
  43586. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43587. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43588. },
  43589. enumerable: true,
  43590. configurable: true
  43591. });
  43592. /**
  43593. * Specifies whether or not this material should be rendered in alpha blend mode.
  43594. */
  43595. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43596. if (this._disableAlphaBlending) {
  43597. return false;
  43598. }
  43599. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43600. };
  43601. /**
  43602. * Specifies if the mesh will require alpha blending.
  43603. * @param mesh - BJS mesh.
  43604. */
  43605. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43606. if (this._disableAlphaBlending) {
  43607. return false;
  43608. }
  43609. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43610. };
  43611. /**
  43612. * Specifies whether or not this material should be rendered in alpha test mode.
  43613. */
  43614. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43615. if (this._forceAlphaTest) {
  43616. return true;
  43617. }
  43618. if (this._linkRefractionWithTransparency) {
  43619. return false;
  43620. }
  43621. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43622. };
  43623. /**
  43624. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43625. */
  43626. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43627. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43628. };
  43629. /**
  43630. * Gets the texture used for the alpha test.
  43631. */
  43632. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43633. return this._albedoTexture;
  43634. };
  43635. /**
  43636. * Specifies that the submesh is ready to be used.
  43637. * @param mesh - BJS mesh.
  43638. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43639. * @param useInstances - Specifies that instances should be used.
  43640. * @returns - boolean indicating that the submesh is ready or not.
  43641. */
  43642. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43643. if (subMesh.effect && this.isFrozen) {
  43644. if (this._wasPreviouslyReady) {
  43645. return true;
  43646. }
  43647. }
  43648. if (!subMesh._materialDefines) {
  43649. subMesh._materialDefines = new PBRMaterialDefines();
  43650. }
  43651. var defines = subMesh._materialDefines;
  43652. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43653. if (defines._renderId === this.getScene().getRenderId()) {
  43654. return true;
  43655. }
  43656. }
  43657. var scene = this.getScene();
  43658. var engine = scene.getEngine();
  43659. if (defines._areTexturesDirty) {
  43660. if (scene.texturesEnabled) {
  43661. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43662. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43663. return false;
  43664. }
  43665. }
  43666. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43667. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43668. return false;
  43669. }
  43670. }
  43671. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43672. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43673. return false;
  43674. }
  43675. }
  43676. var reflectionTexture = this._getReflectionTexture();
  43677. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43678. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43679. return false;
  43680. }
  43681. }
  43682. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43683. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43684. return false;
  43685. }
  43686. }
  43687. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43688. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43689. return false;
  43690. }
  43691. }
  43692. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43693. if (this._metallicTexture) {
  43694. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43695. return false;
  43696. }
  43697. }
  43698. else if (this._reflectivityTexture) {
  43699. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43700. return false;
  43701. }
  43702. }
  43703. if (this._microSurfaceTexture) {
  43704. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43705. return false;
  43706. }
  43707. }
  43708. }
  43709. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43710. // Bump texture cannot be not blocking.
  43711. if (!this._bumpTexture.isReady()) {
  43712. return false;
  43713. }
  43714. }
  43715. var refractionTexture = this._getRefractionTexture();
  43716. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43717. if (!refractionTexture.isReadyOrNotBlocking()) {
  43718. return false;
  43719. }
  43720. }
  43721. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43722. // This is blocking.
  43723. if (!this._environmentBRDFTexture.isReady()) {
  43724. return false;
  43725. }
  43726. }
  43727. }
  43728. }
  43729. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43730. if (!this._imageProcessingConfiguration.isReady()) {
  43731. return false;
  43732. }
  43733. }
  43734. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43735. mesh.createNormals(true);
  43736. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43737. }
  43738. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43739. if (effect) {
  43740. scene.resetCachedMaterial();
  43741. subMesh.setEffect(effect, defines);
  43742. this.buildUniformLayout();
  43743. }
  43744. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43745. return false;
  43746. }
  43747. defines._renderId = scene.getRenderId();
  43748. this._wasPreviouslyReady = true;
  43749. return true;
  43750. };
  43751. /**
  43752. * Specifies if the material uses metallic roughness workflow.
  43753. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43754. */
  43755. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43756. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43757. return true;
  43758. }
  43759. return false;
  43760. };
  43761. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43762. if (onCompiled === void 0) { onCompiled = null; }
  43763. if (onError === void 0) { onError = null; }
  43764. if (useInstances === void 0) { useInstances = null; }
  43765. if (useClipPlane === void 0) { useClipPlane = null; }
  43766. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43767. if (!defines.isDirty) {
  43768. return null;
  43769. }
  43770. defines.markAsProcessed();
  43771. var scene = this.getScene();
  43772. var engine = scene.getEngine();
  43773. // Fallbacks
  43774. var fallbacks = new BABYLON.EffectFallbacks();
  43775. var fallbackRank = 0;
  43776. if (defines.USESPHERICALINVERTEX) {
  43777. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43778. }
  43779. if (defines.FOG) {
  43780. fallbacks.addFallback(fallbackRank, "FOG");
  43781. }
  43782. if (defines.SPECULARAA) {
  43783. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43784. }
  43785. if (defines.POINTSIZE) {
  43786. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43787. }
  43788. if (defines.LOGARITHMICDEPTH) {
  43789. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43790. }
  43791. if (defines.PARALLAX) {
  43792. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43793. }
  43794. if (defines.PARALLAXOCCLUSION) {
  43795. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43796. }
  43797. if (defines.ENVIRONMENTBRDF) {
  43798. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43799. }
  43800. if (defines.TANGENT) {
  43801. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43802. }
  43803. if (defines.BUMP) {
  43804. fallbacks.addFallback(fallbackRank++, "BUMP");
  43805. }
  43806. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43807. if (defines.SPECULARTERM) {
  43808. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43809. }
  43810. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43811. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43812. }
  43813. if (defines.LIGHTMAP) {
  43814. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43815. }
  43816. if (defines.NORMAL) {
  43817. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43818. }
  43819. if (defines.AMBIENT) {
  43820. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43821. }
  43822. if (defines.EMISSIVE) {
  43823. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43824. }
  43825. if (defines.VERTEXCOLOR) {
  43826. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43827. }
  43828. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43829. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43830. }
  43831. if (defines.MORPHTARGETS) {
  43832. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43833. }
  43834. //Attributes
  43835. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43836. if (defines.NORMAL) {
  43837. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43838. }
  43839. if (defines.TANGENT) {
  43840. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43841. }
  43842. if (defines.UV1) {
  43843. attribs.push(BABYLON.VertexBuffer.UVKind);
  43844. }
  43845. if (defines.UV2) {
  43846. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43847. }
  43848. if (defines.VERTEXCOLOR) {
  43849. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43850. }
  43851. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43852. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43853. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43854. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43855. "vFogInfos", "vFogColor", "pointSize",
  43856. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43857. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43858. "mBones",
  43859. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43860. "vLightingIntensity",
  43861. "logarithmicDepthConstant",
  43862. "vSphericalX", "vSphericalY", "vSphericalZ",
  43863. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43864. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43865. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43866. "vTangentSpaceParams"
  43867. ];
  43868. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43869. "bumpSampler", "lightmapSampler", "opacitySampler",
  43870. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43871. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43872. "microSurfaceSampler", "environmentBrdfSampler"];
  43873. var uniformBuffers = ["Material", "Scene"];
  43874. if (BABYLON.ImageProcessingConfiguration) {
  43875. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43876. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43877. }
  43878. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43879. uniformsNames: uniforms,
  43880. uniformBuffersNames: uniformBuffers,
  43881. samplers: samplers,
  43882. defines: defines,
  43883. maxSimultaneousLights: this._maxSimultaneousLights
  43884. });
  43885. var join = defines.toString();
  43886. return engine.createEffect("pbr", {
  43887. attributes: attribs,
  43888. uniformsNames: uniforms,
  43889. uniformBuffersNames: uniformBuffers,
  43890. samplers: samplers,
  43891. defines: join,
  43892. fallbacks: fallbacks,
  43893. onCompiled: onCompiled,
  43894. onError: onError,
  43895. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43896. }, engine);
  43897. };
  43898. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43899. if (useInstances === void 0) { useInstances = null; }
  43900. if (useClipPlane === void 0) { useClipPlane = null; }
  43901. var scene = this.getScene();
  43902. var engine = scene.getEngine();
  43903. // Lights
  43904. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43905. defines._needNormals = true;
  43906. // Textures
  43907. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43908. if (defines._areTexturesDirty) {
  43909. defines._needUVs = false;
  43910. if (scene.texturesEnabled) {
  43911. if (scene.getEngine().getCaps().textureLOD) {
  43912. defines.LODBASEDMICROSFURACE = true;
  43913. }
  43914. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43915. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43916. }
  43917. else {
  43918. defines.ALBEDO = false;
  43919. }
  43920. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43921. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43922. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43923. }
  43924. else {
  43925. defines.AMBIENT = false;
  43926. }
  43927. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43928. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43929. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43930. }
  43931. else {
  43932. defines.OPACITY = false;
  43933. }
  43934. var reflectionTexture = this._getReflectionTexture();
  43935. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43936. defines.REFLECTION = true;
  43937. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43938. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43939. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43940. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43941. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43942. defines.INVERTCUBICMAP = true;
  43943. }
  43944. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43945. switch (reflectionTexture.coordinatesMode) {
  43946. case BABYLON.Texture.EXPLICIT_MODE:
  43947. defines.REFLECTIONMAP_EXPLICIT = true;
  43948. break;
  43949. case BABYLON.Texture.PLANAR_MODE:
  43950. defines.REFLECTIONMAP_PLANAR = true;
  43951. break;
  43952. case BABYLON.Texture.PROJECTION_MODE:
  43953. defines.REFLECTIONMAP_PROJECTION = true;
  43954. break;
  43955. case BABYLON.Texture.SKYBOX_MODE:
  43956. defines.REFLECTIONMAP_SKYBOX = true;
  43957. break;
  43958. case BABYLON.Texture.SPHERICAL_MODE:
  43959. defines.REFLECTIONMAP_SPHERICAL = true;
  43960. break;
  43961. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43962. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43963. break;
  43964. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43965. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43966. break;
  43967. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43968. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43969. break;
  43970. case BABYLON.Texture.CUBIC_MODE:
  43971. case BABYLON.Texture.INVCUBIC_MODE:
  43972. default:
  43973. defines.REFLECTIONMAP_CUBIC = true;
  43974. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43975. break;
  43976. }
  43977. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43978. if (reflectionTexture.sphericalPolynomial) {
  43979. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43980. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43981. defines.USESPHERICALINVERTEX = false;
  43982. }
  43983. else {
  43984. defines.USESPHERICALINVERTEX = true;
  43985. }
  43986. }
  43987. }
  43988. else {
  43989. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43990. }
  43991. }
  43992. else {
  43993. defines.REFLECTION = false;
  43994. defines.REFLECTIONMAP_3D = false;
  43995. defines.REFLECTIONMAP_SPHERICAL = false;
  43996. defines.REFLECTIONMAP_PLANAR = false;
  43997. defines.REFLECTIONMAP_CUBIC = false;
  43998. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43999. defines.REFLECTIONMAP_PROJECTION = false;
  44000. defines.REFLECTIONMAP_SKYBOX = false;
  44001. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44002. defines.REFLECTIONMAP_EXPLICIT = false;
  44003. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44004. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44005. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44006. defines.INVERTCUBICMAP = false;
  44007. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44008. defines.USESPHERICALINVERTEX = false;
  44009. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44010. defines.LODINREFLECTIONALPHA = false;
  44011. defines.GAMMAREFLECTION = false;
  44012. defines.RGBDREFLECTION = false;
  44013. }
  44014. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44015. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44016. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44017. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44018. }
  44019. else {
  44020. defines.LIGHTMAP = false;
  44021. }
  44022. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44024. }
  44025. else {
  44026. defines.EMISSIVE = false;
  44027. }
  44028. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44029. if (this._metallicTexture) {
  44030. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44031. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44032. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44033. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44034. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44035. }
  44036. else if (this._reflectivityTexture) {
  44037. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44038. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44039. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44040. }
  44041. else {
  44042. defines.REFLECTIVITY = false;
  44043. }
  44044. if (this._microSurfaceTexture) {
  44045. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44046. }
  44047. else {
  44048. defines.MICROSURFACEMAP = false;
  44049. }
  44050. }
  44051. else {
  44052. defines.REFLECTIVITY = false;
  44053. defines.MICROSURFACEMAP = false;
  44054. }
  44055. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44056. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44057. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44058. defines.PARALLAX = true;
  44059. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44060. }
  44061. else {
  44062. defines.PARALLAX = false;
  44063. }
  44064. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44065. }
  44066. else {
  44067. defines.BUMP = false;
  44068. }
  44069. var refractionTexture = this._getRefractionTexture();
  44070. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44071. defines.REFRACTION = true;
  44072. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44073. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44074. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44075. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44076. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44077. if (this._linkRefractionWithTransparency) {
  44078. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44079. }
  44080. }
  44081. else {
  44082. defines.REFRACTION = false;
  44083. }
  44084. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44085. defines.ENVIRONMENTBRDF = true;
  44086. }
  44087. else {
  44088. defines.ENVIRONMENTBRDF = false;
  44089. }
  44090. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44091. defines.ALPHAFROMALBEDO = true;
  44092. }
  44093. else {
  44094. defines.ALPHAFROMALBEDO = false;
  44095. }
  44096. }
  44097. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44098. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44099. defines.USEPHYSICALLIGHTFALLOFF = false;
  44100. defines.USEGLTFLIGHTFALLOFF = false;
  44101. }
  44102. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44103. defines.USEPHYSICALLIGHTFALLOFF = false;
  44104. defines.USEGLTFLIGHTFALLOFF = true;
  44105. }
  44106. else {
  44107. defines.USEPHYSICALLIGHTFALLOFF = true;
  44108. defines.USEGLTFLIGHTFALLOFF = false;
  44109. }
  44110. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44111. if (!this.backFaceCulling && this._twoSidedLighting) {
  44112. defines.TWOSIDEDLIGHTING = true;
  44113. }
  44114. else {
  44115. defines.TWOSIDEDLIGHTING = false;
  44116. }
  44117. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44118. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44119. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44120. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44121. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44122. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44123. }
  44124. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44125. this._imageProcessingConfiguration.prepareDefines(defines);
  44126. }
  44127. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44128. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44129. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44130. // Misc.
  44131. if (defines._areMiscDirty) {
  44132. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44133. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44134. }
  44135. // Values that need to be evaluated on every frame
  44136. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44137. // Attribs
  44138. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44139. };
  44140. /**
  44141. * Force shader compilation
  44142. */
  44143. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44144. var _this = this;
  44145. var localOptions = __assign({ clipPlane: false }, options);
  44146. var defines = new PBRMaterialDefines();
  44147. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44148. if (effect.isReady()) {
  44149. if (onCompiled) {
  44150. onCompiled(this);
  44151. }
  44152. }
  44153. else {
  44154. effect.onCompileObservable.add(function () {
  44155. if (onCompiled) {
  44156. onCompiled(_this);
  44157. }
  44158. });
  44159. }
  44160. };
  44161. /**
  44162. * Initializes the uniform buffer layout for the shader.
  44163. */
  44164. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44165. // Order is important !
  44166. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44167. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44168. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44169. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44170. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44171. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44172. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44173. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44174. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44175. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44176. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44177. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44178. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44179. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44180. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44181. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44182. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44183. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44184. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44185. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44186. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44187. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44188. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44189. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44190. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44191. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44192. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44193. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44194. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44195. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44196. this._uniformBuffer.addUniform("pointSize", 1);
  44197. this._uniformBuffer.create();
  44198. };
  44199. /**
  44200. * Unbinds the textures.
  44201. */
  44202. PBRBaseMaterial.prototype.unbind = function () {
  44203. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44204. this._uniformBuffer.setTexture("reflectionSampler", null);
  44205. }
  44206. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44207. this._uniformBuffer.setTexture("refractionSampler", null);
  44208. }
  44209. _super.prototype.unbind.call(this);
  44210. };
  44211. /**
  44212. * Binds the submesh data.
  44213. * @param world - The world matrix.
  44214. * @param mesh - The BJS mesh.
  44215. * @param subMesh - A submesh of the BJS mesh.
  44216. */
  44217. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44218. var scene = this.getScene();
  44219. var defines = subMesh._materialDefines;
  44220. if (!defines) {
  44221. return;
  44222. }
  44223. var effect = subMesh.effect;
  44224. if (!effect) {
  44225. return;
  44226. }
  44227. this._activeEffect = effect;
  44228. // Matrices
  44229. this.bindOnlyWorldMatrix(world);
  44230. // Normal Matrix
  44231. if (defines.OBJECTSPACE_NORMALMAP) {
  44232. world.toNormalMatrix(this._normalMatrix);
  44233. this.bindOnlyNormalMatrix(this._normalMatrix);
  44234. }
  44235. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44236. // Bones
  44237. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44238. var reflectionTexture = null;
  44239. if (mustRebind) {
  44240. this._uniformBuffer.bindToEffect(effect, "Material");
  44241. this.bindViewProjection(effect);
  44242. reflectionTexture = this._getReflectionTexture();
  44243. var refractionTexture = this._getRefractionTexture();
  44244. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44245. // Texture uniforms
  44246. if (scene.texturesEnabled) {
  44247. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44248. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44249. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44250. }
  44251. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44252. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44253. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44254. }
  44255. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44256. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44257. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44258. }
  44259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44260. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44261. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44262. if (reflectionTexture.boundingBoxSize) {
  44263. var cubeTexture = reflectionTexture;
  44264. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44265. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44266. }
  44267. var polynomials = reflectionTexture.sphericalPolynomial;
  44268. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44269. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44270. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44271. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44272. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44273. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44274. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44275. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44276. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44277. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44278. }
  44279. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44280. }
  44281. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44282. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44283. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44284. }
  44285. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44286. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44287. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44288. }
  44289. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44290. if (this._metallicTexture) {
  44291. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44292. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44293. }
  44294. else if (this._reflectivityTexture) {
  44295. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44296. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44297. }
  44298. if (this._microSurfaceTexture) {
  44299. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44300. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44301. }
  44302. }
  44303. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44304. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44305. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44306. if (scene._mirroredCameraPosition) {
  44307. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44308. }
  44309. else {
  44310. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44311. }
  44312. }
  44313. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44314. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44315. var depth = 1.0;
  44316. if (!refractionTexture.isCube) {
  44317. if (refractionTexture.depth) {
  44318. depth = refractionTexture.depth;
  44319. }
  44320. }
  44321. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44322. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44323. }
  44324. }
  44325. // Point size
  44326. if (this.pointsCloud) {
  44327. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44328. }
  44329. // Colors
  44330. if (defines.METALLICWORKFLOW) {
  44331. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44332. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44333. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44334. }
  44335. else {
  44336. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44337. }
  44338. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44339. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44340. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44341. // Misc
  44342. this._lightingInfos.x = this._directIntensity;
  44343. this._lightingInfos.y = this._emissiveIntensity;
  44344. this._lightingInfos.z = this._environmentIntensity;
  44345. this._lightingInfos.w = this._specularIntensity;
  44346. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44347. }
  44348. // Textures
  44349. if (scene.texturesEnabled) {
  44350. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44351. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44352. }
  44353. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44354. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44355. }
  44356. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44357. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44358. }
  44359. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44360. if (defines.LODBASEDMICROSFURACE) {
  44361. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44362. }
  44363. else {
  44364. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44365. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44366. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44367. }
  44368. }
  44369. if (defines.ENVIRONMENTBRDF) {
  44370. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44371. }
  44372. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44373. if (defines.LODBASEDMICROSFURACE) {
  44374. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44375. }
  44376. else {
  44377. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44378. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44379. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44380. }
  44381. }
  44382. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44383. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44384. }
  44385. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44386. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44387. }
  44388. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44389. if (this._metallicTexture) {
  44390. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44391. }
  44392. else if (this._reflectivityTexture) {
  44393. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44394. }
  44395. if (this._microSurfaceTexture) {
  44396. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44397. }
  44398. }
  44399. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44400. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44401. }
  44402. }
  44403. // Clip plane
  44404. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44405. // Colors
  44406. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44407. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44408. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44409. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44410. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44411. }
  44412. if (mustRebind || !this.isFrozen) {
  44413. // Lights
  44414. if (scene.lightsEnabled && !this._disableLighting) {
  44415. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44416. }
  44417. // View
  44418. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44419. this.bindView(effect);
  44420. }
  44421. // Fog
  44422. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44423. // Morph targets
  44424. if (defines.NUM_MORPH_INFLUENCERS) {
  44425. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44426. }
  44427. // image processing
  44428. this._imageProcessingConfiguration.bind(this._activeEffect);
  44429. // Log. depth
  44430. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44431. }
  44432. this._uniformBuffer.update();
  44433. this._afterBind(mesh, this._activeEffect);
  44434. };
  44435. /**
  44436. * Returns the animatable textures.
  44437. * @returns - Array of animatable textures.
  44438. */
  44439. PBRBaseMaterial.prototype.getAnimatables = function () {
  44440. var results = [];
  44441. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44442. results.push(this._albedoTexture);
  44443. }
  44444. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44445. results.push(this._ambientTexture);
  44446. }
  44447. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44448. results.push(this._opacityTexture);
  44449. }
  44450. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44451. results.push(this._reflectionTexture);
  44452. }
  44453. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44454. results.push(this._emissiveTexture);
  44455. }
  44456. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44457. results.push(this._metallicTexture);
  44458. }
  44459. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44460. results.push(this._reflectivityTexture);
  44461. }
  44462. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44463. results.push(this._bumpTexture);
  44464. }
  44465. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44466. results.push(this._lightmapTexture);
  44467. }
  44468. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44469. results.push(this._refractionTexture);
  44470. }
  44471. return results;
  44472. };
  44473. /**
  44474. * Returns the texture used for reflections.
  44475. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44476. */
  44477. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44478. if (this._reflectionTexture) {
  44479. return this._reflectionTexture;
  44480. }
  44481. return this.getScene().environmentTexture;
  44482. };
  44483. /**
  44484. * Returns the texture used for refraction or null if none is used.
  44485. * @returns - Refection texture if present. If no refraction texture and refraction
  44486. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44487. */
  44488. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44489. if (this._refractionTexture) {
  44490. return this._refractionTexture;
  44491. }
  44492. if (this._linkRefractionWithTransparency) {
  44493. return this.getScene().environmentTexture;
  44494. }
  44495. return null;
  44496. };
  44497. /**
  44498. * Disposes the resources of the material.
  44499. * @param forceDisposeEffect - Forces the disposal of effects.
  44500. * @param forceDisposeTextures - Forces the disposal of all textures.
  44501. */
  44502. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44503. if (forceDisposeTextures) {
  44504. if (this._albedoTexture) {
  44505. this._albedoTexture.dispose();
  44506. }
  44507. if (this._ambientTexture) {
  44508. this._ambientTexture.dispose();
  44509. }
  44510. if (this._opacityTexture) {
  44511. this._opacityTexture.dispose();
  44512. }
  44513. if (this._reflectionTexture) {
  44514. this._reflectionTexture.dispose();
  44515. }
  44516. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44517. this._environmentBRDFTexture.dispose();
  44518. }
  44519. if (this._emissiveTexture) {
  44520. this._emissiveTexture.dispose();
  44521. }
  44522. if (this._metallicTexture) {
  44523. this._metallicTexture.dispose();
  44524. }
  44525. if (this._reflectivityTexture) {
  44526. this._reflectivityTexture.dispose();
  44527. }
  44528. if (this._bumpTexture) {
  44529. this._bumpTexture.dispose();
  44530. }
  44531. if (this._lightmapTexture) {
  44532. this._lightmapTexture.dispose();
  44533. }
  44534. if (this._refractionTexture) {
  44535. this._refractionTexture.dispose();
  44536. }
  44537. }
  44538. this._renderTargets.dispose();
  44539. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44540. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44541. }
  44542. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44543. };
  44544. /**
  44545. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44546. */
  44547. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44548. /**
  44549. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44550. * to enhance interoperability with other engines.
  44551. */
  44552. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44553. /**
  44554. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44555. * to enhance interoperability with other materials.
  44556. */
  44557. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44558. /**
  44559. * Stores the reflectivity values based on metallic roughness workflow.
  44560. */
  44561. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44562. __decorate([
  44563. BABYLON.serializeAsImageProcessingConfiguration()
  44564. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44565. __decorate([
  44566. BABYLON.serialize()
  44567. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44568. __decorate([
  44569. BABYLON.serialize()
  44570. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44571. return PBRBaseMaterial;
  44572. }(BABYLON.PushMaterial));
  44573. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44574. })(BABYLON || (BABYLON = {}));
  44575. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44576. var BABYLON;
  44577. (function (BABYLON) {
  44578. /**
  44579. * The Physically based simple base material of BJS.
  44580. *
  44581. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44582. * It is used as the base class for both the specGloss and metalRough conventions.
  44583. */
  44584. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44585. __extends(PBRBaseSimpleMaterial, _super);
  44586. /**
  44587. * Instantiates a new PBRMaterial instance.
  44588. *
  44589. * @param name The material name
  44590. * @param scene The scene the material will be use in.
  44591. */
  44592. function PBRBaseSimpleMaterial(name, scene) {
  44593. var _this = _super.call(this, name, scene) || this;
  44594. /**
  44595. * Number of Simultaneous lights allowed on the material.
  44596. */
  44597. _this.maxSimultaneousLights = 4;
  44598. /**
  44599. * If sets to true, disables all the lights affecting the material.
  44600. */
  44601. _this.disableLighting = false;
  44602. /**
  44603. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44604. */
  44605. _this.invertNormalMapX = false;
  44606. /**
  44607. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44608. */
  44609. _this.invertNormalMapY = false;
  44610. /**
  44611. * Emissivie color used to self-illuminate the model.
  44612. */
  44613. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44614. /**
  44615. * Occlusion Channel Strenght.
  44616. */
  44617. _this.occlusionStrength = 1.0;
  44618. _this.useLightmapAsShadowmap = false;
  44619. _this._useAlphaFromAlbedoTexture = true;
  44620. _this._useAmbientInGrayScale = true;
  44621. return _this;
  44622. }
  44623. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44624. /**
  44625. * Gets the current double sided mode.
  44626. */
  44627. get: function () {
  44628. return this._twoSidedLighting;
  44629. },
  44630. /**
  44631. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44632. */
  44633. set: function (value) {
  44634. if (this._twoSidedLighting === value) {
  44635. return;
  44636. }
  44637. this._twoSidedLighting = value;
  44638. this.backFaceCulling = !value;
  44639. this._markAllSubMeshesAsTexturesDirty();
  44640. },
  44641. enumerable: true,
  44642. configurable: true
  44643. });
  44644. /**
  44645. * Return the active textures of the material.
  44646. */
  44647. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44648. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44649. if (this.environmentTexture) {
  44650. activeTextures.push(this.environmentTexture);
  44651. }
  44652. if (this.normalTexture) {
  44653. activeTextures.push(this.normalTexture);
  44654. }
  44655. if (this.emissiveTexture) {
  44656. activeTextures.push(this.emissiveTexture);
  44657. }
  44658. if (this.occlusionTexture) {
  44659. activeTextures.push(this.occlusionTexture);
  44660. }
  44661. if (this.lightmapTexture) {
  44662. activeTextures.push(this.lightmapTexture);
  44663. }
  44664. return activeTextures;
  44665. };
  44666. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44667. if (_super.prototype.hasTexture.call(this, texture)) {
  44668. return true;
  44669. }
  44670. if (this.lightmapTexture === texture) {
  44671. return true;
  44672. }
  44673. return false;
  44674. };
  44675. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44676. return "PBRBaseSimpleMaterial";
  44677. };
  44678. __decorate([
  44679. BABYLON.serialize(),
  44680. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44681. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44682. __decorate([
  44683. BABYLON.serialize(),
  44684. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44685. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44686. __decorate([
  44687. BABYLON.serializeAsTexture(),
  44688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44689. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44690. __decorate([
  44691. BABYLON.serialize(),
  44692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44693. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44694. __decorate([
  44695. BABYLON.serialize(),
  44696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44697. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44698. __decorate([
  44699. BABYLON.serializeAsTexture(),
  44700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44701. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44702. __decorate([
  44703. BABYLON.serializeAsColor3("emissive"),
  44704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44705. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44706. __decorate([
  44707. BABYLON.serializeAsTexture(),
  44708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44709. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44710. __decorate([
  44711. BABYLON.serialize(),
  44712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44713. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44714. __decorate([
  44715. BABYLON.serializeAsTexture(),
  44716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44717. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44718. __decorate([
  44719. BABYLON.serialize(),
  44720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44721. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44722. __decorate([
  44723. BABYLON.serialize()
  44724. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44725. __decorate([
  44726. BABYLON.serializeAsTexture(),
  44727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44728. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44729. __decorate([
  44730. BABYLON.serialize(),
  44731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44732. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44733. return PBRBaseSimpleMaterial;
  44734. }(BABYLON.PBRBaseMaterial));
  44735. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44736. })(BABYLON || (BABYLON = {}));
  44737. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44738. var BABYLON;
  44739. (function (BABYLON) {
  44740. /**
  44741. * The Physically based material of BJS.
  44742. *
  44743. * This offers the main features of a standard PBR material.
  44744. * For more information, please refer to the documentation :
  44745. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44746. */
  44747. var PBRMaterial = /** @class */ (function (_super) {
  44748. __extends(PBRMaterial, _super);
  44749. /**
  44750. * Instantiates a new PBRMaterial instance.
  44751. *
  44752. * @param name The material name
  44753. * @param scene The scene the material will be use in.
  44754. */
  44755. function PBRMaterial(name, scene) {
  44756. var _this = _super.call(this, name, scene) || this;
  44757. /**
  44758. * Intensity of the direct lights e.g. the four lights available in your scene.
  44759. * This impacts both the direct diffuse and specular highlights.
  44760. */
  44761. _this.directIntensity = 1.0;
  44762. /**
  44763. * Intensity of the emissive part of the material.
  44764. * This helps controlling the emissive effect without modifying the emissive color.
  44765. */
  44766. _this.emissiveIntensity = 1.0;
  44767. /**
  44768. * Intensity of the environment e.g. how much the environment will light the object
  44769. * either through harmonics for rough material or through the refelction for shiny ones.
  44770. */
  44771. _this.environmentIntensity = 1.0;
  44772. /**
  44773. * This is a special control allowing the reduction of the specular highlights coming from the
  44774. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44775. */
  44776. _this.specularIntensity = 1.0;
  44777. /**
  44778. * Debug Control allowing disabling the bump map on this material.
  44779. */
  44780. _this.disableBumpMap = false;
  44781. /**
  44782. * AKA Occlusion Texture Intensity in other nomenclature.
  44783. */
  44784. _this.ambientTextureStrength = 1.0;
  44785. /**
  44786. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44787. * 1 means it completely occludes it
  44788. * 0 mean it has no impact
  44789. */
  44790. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44791. /**
  44792. * The color of a material in ambient lighting.
  44793. */
  44794. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44795. /**
  44796. * AKA Diffuse Color in other nomenclature.
  44797. */
  44798. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44799. /**
  44800. * AKA Specular Color in other nomenclature.
  44801. */
  44802. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44803. /**
  44804. * The color reflected from the material.
  44805. */
  44806. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44807. /**
  44808. * The color emitted from the material.
  44809. */
  44810. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44811. /**
  44812. * AKA Glossiness in other nomenclature.
  44813. */
  44814. _this.microSurface = 1.0;
  44815. /**
  44816. * source material index of refraction (IOR)' / 'destination material IOR.
  44817. */
  44818. _this.indexOfRefraction = 0.66;
  44819. /**
  44820. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44821. */
  44822. _this.invertRefractionY = false;
  44823. /**
  44824. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44825. * Materials half opaque for instance using refraction could benefit from this control.
  44826. */
  44827. _this.linkRefractionWithTransparency = false;
  44828. _this.useLightmapAsShadowmap = false;
  44829. /**
  44830. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44831. */
  44832. _this.useAlphaFromAlbedoTexture = false;
  44833. /**
  44834. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44835. */
  44836. _this.forceAlphaTest = false;
  44837. /**
  44838. * Defines the alpha limits in alpha test mode.
  44839. */
  44840. _this.alphaCutOff = 0.4;
  44841. /**
  44842. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44843. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44844. */
  44845. _this.useSpecularOverAlpha = true;
  44846. /**
  44847. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44848. */
  44849. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44850. /**
  44851. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44852. */
  44853. _this.useRoughnessFromMetallicTextureAlpha = true;
  44854. /**
  44855. * Specifies if the metallic texture contains the roughness information in its green channel.
  44856. */
  44857. _this.useRoughnessFromMetallicTextureGreen = false;
  44858. /**
  44859. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44860. */
  44861. _this.useMetallnessFromMetallicTextureBlue = false;
  44862. /**
  44863. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44864. */
  44865. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44866. /**
  44867. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44868. */
  44869. _this.useAmbientInGrayScale = false;
  44870. /**
  44871. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44872. * The material will try to infer what glossiness each pixel should be.
  44873. */
  44874. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44875. /**
  44876. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44877. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44878. */
  44879. _this.useRadianceOverAlpha = true;
  44880. /**
  44881. * Allows using an object space normal map (instead of tangent space).
  44882. */
  44883. _this.useObjectSpaceNormalMap = false;
  44884. /**
  44885. * Allows using the bump map in parallax mode.
  44886. */
  44887. _this.useParallax = false;
  44888. /**
  44889. * Allows using the bump map in parallax occlusion mode.
  44890. */
  44891. _this.useParallaxOcclusion = false;
  44892. /**
  44893. * Controls the scale bias of the parallax mode.
  44894. */
  44895. _this.parallaxScaleBias = 0.05;
  44896. /**
  44897. * If sets to true, disables all the lights affecting the material.
  44898. */
  44899. _this.disableLighting = false;
  44900. /**
  44901. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44902. */
  44903. _this.forceIrradianceInFragment = false;
  44904. /**
  44905. * Number of Simultaneous lights allowed on the material.
  44906. */
  44907. _this.maxSimultaneousLights = 4;
  44908. /**
  44909. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44910. */
  44911. _this.invertNormalMapX = false;
  44912. /**
  44913. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44914. */
  44915. _this.invertNormalMapY = false;
  44916. /**
  44917. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44918. */
  44919. _this.twoSidedLighting = false;
  44920. /**
  44921. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44922. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44923. */
  44924. _this.useAlphaFresnel = false;
  44925. /**
  44926. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44927. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44928. */
  44929. _this.useLinearAlphaFresnel = false;
  44930. /**
  44931. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44932. * And/Or occlude the blended part.
  44933. */
  44934. _this.environmentBRDFTexture = null;
  44935. /**
  44936. * Force normal to face away from face.
  44937. */
  44938. _this.forceNormalForward = false;
  44939. /**
  44940. * Enables specular anti aliasing in the PBR shader.
  44941. * It will both interacts on the Geometry for analytical and IBL lighting.
  44942. * It also prefilter the roughness map based on the bump values.
  44943. */
  44944. _this.enableSpecularAntiAliasing = false;
  44945. /**
  44946. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44947. * makes the reflect vector face the model (under horizon).
  44948. */
  44949. _this.useHorizonOcclusion = true;
  44950. /**
  44951. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44952. * too much the area relying on ambient texture to define their ambient occlusion.
  44953. */
  44954. _this.useRadianceOcclusion = true;
  44955. /**
  44956. * If set to true, no lighting calculations will be applied.
  44957. */
  44958. _this.unlit = false;
  44959. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44960. return _this;
  44961. }
  44962. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  44963. /**
  44964. * BJS is using an harcoded light falloff based on a manually sets up range.
  44965. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44966. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44967. */
  44968. get: function () {
  44969. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44970. },
  44971. /**
  44972. * BJS is using an harcoded light falloff based on a manually sets up range.
  44973. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44974. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44975. */
  44976. set: function (value) {
  44977. if (value !== this.usePhysicalLightFalloff) {
  44978. // Ensure the effect will be rebuilt.
  44979. this._markAllSubMeshesAsTexturesDirty();
  44980. if (value) {
  44981. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44982. }
  44983. else {
  44984. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44985. }
  44986. }
  44987. },
  44988. enumerable: true,
  44989. configurable: true
  44990. });
  44991. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  44992. /**
  44993. * In order to support the falloff compatibility with gltf, a special mode has been added
  44994. * to reproduce the gltf light falloff.
  44995. */
  44996. get: function () {
  44997. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44998. },
  44999. /**
  45000. * In order to support the falloff compatibility with gltf, a special mode has been added
  45001. * to reproduce the gltf light falloff.
  45002. */
  45003. set: function (value) {
  45004. if (value !== this.useGLTFLightFalloff) {
  45005. // Ensure the effect will be rebuilt.
  45006. this._markAllSubMeshesAsTexturesDirty();
  45007. if (value) {
  45008. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45009. }
  45010. else {
  45011. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45012. }
  45013. }
  45014. },
  45015. enumerable: true,
  45016. configurable: true
  45017. });
  45018. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45019. /**
  45020. * Gets the image processing configuration used either in this material.
  45021. */
  45022. get: function () {
  45023. return this._imageProcessingConfiguration;
  45024. },
  45025. /**
  45026. * Sets the Default image processing configuration used either in the this material.
  45027. *
  45028. * If sets to null, the scene one is in use.
  45029. */
  45030. set: function (value) {
  45031. this._attachImageProcessingConfiguration(value);
  45032. // Ensure the effect will be rebuilt.
  45033. this._markAllSubMeshesAsTexturesDirty();
  45034. },
  45035. enumerable: true,
  45036. configurable: true
  45037. });
  45038. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45039. /**
  45040. * Gets wether the color curves effect is enabled.
  45041. */
  45042. get: function () {
  45043. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45044. },
  45045. /**
  45046. * Sets wether the color curves effect is enabled.
  45047. */
  45048. set: function (value) {
  45049. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45050. },
  45051. enumerable: true,
  45052. configurable: true
  45053. });
  45054. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45055. /**
  45056. * Gets wether the color grading effect is enabled.
  45057. */
  45058. get: function () {
  45059. return this.imageProcessingConfiguration.colorGradingEnabled;
  45060. },
  45061. /**
  45062. * Gets wether the color grading effect is enabled.
  45063. */
  45064. set: function (value) {
  45065. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45066. },
  45067. enumerable: true,
  45068. configurable: true
  45069. });
  45070. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45071. /**
  45072. * Gets wether tonemapping is enabled or not.
  45073. */
  45074. get: function () {
  45075. return this._imageProcessingConfiguration.toneMappingEnabled;
  45076. },
  45077. /**
  45078. * Sets wether tonemapping is enabled or not
  45079. */
  45080. set: function (value) {
  45081. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45082. },
  45083. enumerable: true,
  45084. configurable: true
  45085. });
  45086. ;
  45087. ;
  45088. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45089. /**
  45090. * The camera exposure used on this material.
  45091. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45092. * This corresponds to a photographic exposure.
  45093. */
  45094. get: function () {
  45095. return this._imageProcessingConfiguration.exposure;
  45096. },
  45097. /**
  45098. * The camera exposure used on this material.
  45099. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45100. * This corresponds to a photographic exposure.
  45101. */
  45102. set: function (value) {
  45103. this._imageProcessingConfiguration.exposure = value;
  45104. },
  45105. enumerable: true,
  45106. configurable: true
  45107. });
  45108. ;
  45109. ;
  45110. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45111. /**
  45112. * Gets The camera contrast used on this material.
  45113. */
  45114. get: function () {
  45115. return this._imageProcessingConfiguration.contrast;
  45116. },
  45117. /**
  45118. * Sets The camera contrast used on this material.
  45119. */
  45120. set: function (value) {
  45121. this._imageProcessingConfiguration.contrast = value;
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45127. /**
  45128. * Gets the Color Grading 2D Lookup Texture.
  45129. */
  45130. get: function () {
  45131. return this._imageProcessingConfiguration.colorGradingTexture;
  45132. },
  45133. /**
  45134. * Sets the Color Grading 2D Lookup Texture.
  45135. */
  45136. set: function (value) {
  45137. this._imageProcessingConfiguration.colorGradingTexture = value;
  45138. },
  45139. enumerable: true,
  45140. configurable: true
  45141. });
  45142. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45143. /**
  45144. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45145. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45146. * 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;
  45147. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45148. */
  45149. get: function () {
  45150. return this._imageProcessingConfiguration.colorCurves;
  45151. },
  45152. /**
  45153. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45154. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45155. * 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;
  45156. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45157. */
  45158. set: function (value) {
  45159. this._imageProcessingConfiguration.colorCurves = value;
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. /**
  45165. * Returns the name of this material class.
  45166. */
  45167. PBRMaterial.prototype.getClassName = function () {
  45168. return "PBRMaterial";
  45169. };
  45170. /**
  45171. * Returns an array of the actively used textures.
  45172. * @returns - Array of BaseTextures
  45173. */
  45174. PBRMaterial.prototype.getActiveTextures = function () {
  45175. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45176. if (this._albedoTexture) {
  45177. activeTextures.push(this._albedoTexture);
  45178. }
  45179. if (this._ambientTexture) {
  45180. activeTextures.push(this._ambientTexture);
  45181. }
  45182. if (this._opacityTexture) {
  45183. activeTextures.push(this._opacityTexture);
  45184. }
  45185. if (this._reflectionTexture) {
  45186. activeTextures.push(this._reflectionTexture);
  45187. }
  45188. if (this._emissiveTexture) {
  45189. activeTextures.push(this._emissiveTexture);
  45190. }
  45191. if (this._reflectivityTexture) {
  45192. activeTextures.push(this._reflectivityTexture);
  45193. }
  45194. if (this._metallicTexture) {
  45195. activeTextures.push(this._metallicTexture);
  45196. }
  45197. if (this._microSurfaceTexture) {
  45198. activeTextures.push(this._microSurfaceTexture);
  45199. }
  45200. if (this._bumpTexture) {
  45201. activeTextures.push(this._bumpTexture);
  45202. }
  45203. if (this._lightmapTexture) {
  45204. activeTextures.push(this._lightmapTexture);
  45205. }
  45206. if (this._refractionTexture) {
  45207. activeTextures.push(this._refractionTexture);
  45208. }
  45209. return activeTextures;
  45210. };
  45211. /**
  45212. * Checks to see if a texture is used in the material.
  45213. * @param texture - Base texture to use.
  45214. * @returns - Boolean specifying if a texture is used in the material.
  45215. */
  45216. PBRMaterial.prototype.hasTexture = function (texture) {
  45217. if (_super.prototype.hasTexture.call(this, texture)) {
  45218. return true;
  45219. }
  45220. if (this._albedoTexture === texture) {
  45221. return true;
  45222. }
  45223. if (this._ambientTexture === texture) {
  45224. return true;
  45225. }
  45226. if (this._opacityTexture === texture) {
  45227. return true;
  45228. }
  45229. if (this._reflectionTexture === texture) {
  45230. return true;
  45231. }
  45232. if (this._reflectivityTexture === texture) {
  45233. return true;
  45234. }
  45235. if (this._metallicTexture === texture) {
  45236. return true;
  45237. }
  45238. if (this._microSurfaceTexture === texture) {
  45239. return true;
  45240. }
  45241. if (this._bumpTexture === texture) {
  45242. return true;
  45243. }
  45244. if (this._lightmapTexture === texture) {
  45245. return true;
  45246. }
  45247. if (this._refractionTexture === texture) {
  45248. return true;
  45249. }
  45250. return false;
  45251. };
  45252. /**
  45253. * Makes a duplicate of the current material.
  45254. * @param name - name to use for the new material.
  45255. */
  45256. PBRMaterial.prototype.clone = function (name) {
  45257. var _this = this;
  45258. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45259. clone.id = name;
  45260. clone.name = name;
  45261. return clone;
  45262. };
  45263. /**
  45264. * Serializes this PBR Material.
  45265. * @returns - An object with the serialized material.
  45266. */
  45267. PBRMaterial.prototype.serialize = function () {
  45268. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45269. serializationObject.customType = "BABYLON.PBRMaterial";
  45270. return serializationObject;
  45271. };
  45272. // Statics
  45273. /**
  45274. * Parses a PBR Material from a serialized object.
  45275. * @param source - Serialized object.
  45276. * @param scene - BJS scene instance.
  45277. * @param rootUrl - url for the scene object
  45278. * @returns - PBRMaterial
  45279. */
  45280. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45281. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45282. };
  45283. /**
  45284. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45285. */
  45286. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45287. /**
  45288. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45289. */
  45290. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45291. /**
  45292. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45293. */
  45294. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45295. /**
  45296. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45297. * They are also discarded below the alpha cutoff threshold to improve performances.
  45298. */
  45299. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45300. /**
  45301. * Defines the default value of how much AO map is occluding the analytical lights
  45302. * (point spot...).
  45303. */
  45304. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45305. __decorate([
  45306. BABYLON.serialize(),
  45307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45308. ], PBRMaterial.prototype, "directIntensity", void 0);
  45309. __decorate([
  45310. BABYLON.serialize(),
  45311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45312. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45313. __decorate([
  45314. BABYLON.serialize(),
  45315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45316. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45317. __decorate([
  45318. BABYLON.serialize(),
  45319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45320. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45321. __decorate([
  45322. BABYLON.serialize(),
  45323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45324. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45325. __decorate([
  45326. BABYLON.serializeAsTexture(),
  45327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45328. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45329. __decorate([
  45330. BABYLON.serializeAsTexture(),
  45331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45332. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45333. __decorate([
  45334. BABYLON.serialize(),
  45335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45336. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45337. __decorate([
  45338. BABYLON.serialize(),
  45339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45340. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45341. __decorate([
  45342. BABYLON.serializeAsTexture(),
  45343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45344. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45345. __decorate([
  45346. BABYLON.serializeAsTexture(),
  45347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45348. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45349. __decorate([
  45350. BABYLON.serializeAsTexture(),
  45351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45352. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45353. __decorate([
  45354. BABYLON.serializeAsTexture(),
  45355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45356. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45357. __decorate([
  45358. BABYLON.serializeAsTexture(),
  45359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45360. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45361. __decorate([
  45362. BABYLON.serialize(),
  45363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45364. ], PBRMaterial.prototype, "metallic", void 0);
  45365. __decorate([
  45366. BABYLON.serialize(),
  45367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45368. ], PBRMaterial.prototype, "roughness", void 0);
  45369. __decorate([
  45370. BABYLON.serializeAsTexture(),
  45371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45372. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45373. __decorate([
  45374. BABYLON.serializeAsTexture(),
  45375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45376. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45377. __decorate([
  45378. BABYLON.serializeAsTexture(),
  45379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45380. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45381. __decorate([
  45382. BABYLON.serializeAsTexture(),
  45383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45384. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45385. __decorate([
  45386. BABYLON.serializeAsColor3("ambient"),
  45387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45388. ], PBRMaterial.prototype, "ambientColor", void 0);
  45389. __decorate([
  45390. BABYLON.serializeAsColor3("albedo"),
  45391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45392. ], PBRMaterial.prototype, "albedoColor", void 0);
  45393. __decorate([
  45394. BABYLON.serializeAsColor3("reflectivity"),
  45395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45396. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45397. __decorate([
  45398. BABYLON.serializeAsColor3("reflection"),
  45399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45400. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45401. __decorate([
  45402. BABYLON.serializeAsColor3("emissive"),
  45403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45404. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45405. __decorate([
  45406. BABYLON.serialize(),
  45407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45408. ], PBRMaterial.prototype, "microSurface", void 0);
  45409. __decorate([
  45410. BABYLON.serialize(),
  45411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45412. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45413. __decorate([
  45414. BABYLON.serialize(),
  45415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45416. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45417. __decorate([
  45418. BABYLON.serialize(),
  45419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45420. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45421. __decorate([
  45422. BABYLON.serialize(),
  45423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45424. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45425. __decorate([
  45426. BABYLON.serialize(),
  45427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45428. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45429. __decorate([
  45430. BABYLON.serialize(),
  45431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45432. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45433. __decorate([
  45434. BABYLON.serialize(),
  45435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45436. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45437. __decorate([
  45438. BABYLON.serialize(),
  45439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45440. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45445. __decorate([
  45446. BABYLON.serialize(),
  45447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45448. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45449. __decorate([
  45450. BABYLON.serialize(),
  45451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45452. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45453. __decorate([
  45454. BABYLON.serialize(),
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45456. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45457. __decorate([
  45458. BABYLON.serialize(),
  45459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45460. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45461. __decorate([
  45462. BABYLON.serialize(),
  45463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45464. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45465. __decorate([
  45466. BABYLON.serialize(),
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45469. __decorate([
  45470. BABYLON.serialize()
  45471. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45472. __decorate([
  45473. BABYLON.serialize()
  45474. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "useParallax", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45491. __decorate([
  45492. BABYLON.serialize(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45498. ], PBRMaterial.prototype, "disableLighting", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45506. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45527. __decorate([
  45528. BABYLON.serializeAsTexture(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45550. ], PBRMaterial.prototype, "unlit", void 0);
  45551. return PBRMaterial;
  45552. }(BABYLON.PBRBaseMaterial));
  45553. BABYLON.PBRMaterial = PBRMaterial;
  45554. })(BABYLON || (BABYLON = {}));
  45555. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45556. var BABYLON;
  45557. (function (BABYLON) {
  45558. /**
  45559. * The PBR material of BJS following the metal roughness convention.
  45560. *
  45561. * This fits to the PBR convention in the GLTF definition:
  45562. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45563. */
  45564. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45565. __extends(PBRMetallicRoughnessMaterial, _super);
  45566. /**
  45567. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45568. *
  45569. * @param name The material name
  45570. * @param scene The scene the material will be use in.
  45571. */
  45572. function PBRMetallicRoughnessMaterial(name, scene) {
  45573. var _this = _super.call(this, name, scene) || this;
  45574. _this._useRoughnessFromMetallicTextureAlpha = false;
  45575. _this._useRoughnessFromMetallicTextureGreen = true;
  45576. _this._useMetallnessFromMetallicTextureBlue = true;
  45577. _this.metallic = 1.0;
  45578. _this.roughness = 1.0;
  45579. return _this;
  45580. }
  45581. /**
  45582. * Return the currrent class name of the material.
  45583. */
  45584. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45585. return "PBRMetallicRoughnessMaterial";
  45586. };
  45587. /**
  45588. * Return the active textures of the material.
  45589. */
  45590. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45591. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45592. if (this.baseTexture) {
  45593. activeTextures.push(this.baseTexture);
  45594. }
  45595. if (this.metallicRoughnessTexture) {
  45596. activeTextures.push(this.metallicRoughnessTexture);
  45597. }
  45598. return activeTextures;
  45599. };
  45600. /**
  45601. * Checks to see if a texture is used in the material.
  45602. * @param texture - Base texture to use.
  45603. * @returns - Boolean specifying if a texture is used in the material.
  45604. */
  45605. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45606. if (_super.prototype.hasTexture.call(this, texture)) {
  45607. return true;
  45608. }
  45609. if (this.baseTexture === texture) {
  45610. return true;
  45611. }
  45612. if (this.metallicRoughnessTexture === texture) {
  45613. return true;
  45614. }
  45615. return false;
  45616. };
  45617. /**
  45618. * Makes a duplicate of the current material.
  45619. * @param name - name to use for the new material.
  45620. */
  45621. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45622. var _this = this;
  45623. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45624. clone.id = name;
  45625. clone.name = name;
  45626. return clone;
  45627. };
  45628. /**
  45629. * Serialize the material to a parsable JSON object.
  45630. */
  45631. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45632. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45633. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45634. return serializationObject;
  45635. };
  45636. /**
  45637. * Parses a JSON object correponding to the serialize function.
  45638. */
  45639. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45640. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45641. };
  45642. __decorate([
  45643. BABYLON.serializeAsColor3(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45645. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45646. __decorate([
  45647. BABYLON.serializeAsTexture(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45649. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45658. __decorate([
  45659. BABYLON.serializeAsTexture(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45661. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45662. return PBRMetallicRoughnessMaterial;
  45663. }(BABYLON.PBRBaseSimpleMaterial));
  45664. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45665. })(BABYLON || (BABYLON = {}));
  45666. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45667. var BABYLON;
  45668. (function (BABYLON) {
  45669. /**
  45670. * The PBR material of BJS following the specular glossiness convention.
  45671. *
  45672. * This fits to the PBR convention in the GLTF definition:
  45673. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45674. */
  45675. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45676. __extends(PBRSpecularGlossinessMaterial, _super);
  45677. /**
  45678. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45679. *
  45680. * @param name The material name
  45681. * @param scene The scene the material will be use in.
  45682. */
  45683. function PBRSpecularGlossinessMaterial(name, scene) {
  45684. var _this = _super.call(this, name, scene) || this;
  45685. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45686. return _this;
  45687. }
  45688. /**
  45689. * Return the currrent class name of the material.
  45690. */
  45691. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45692. return "PBRSpecularGlossinessMaterial";
  45693. };
  45694. /**
  45695. * Return the active textures of the material.
  45696. */
  45697. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45698. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45699. if (this.diffuseTexture) {
  45700. activeTextures.push(this.diffuseTexture);
  45701. }
  45702. if (this.specularGlossinessTexture) {
  45703. activeTextures.push(this.specularGlossinessTexture);
  45704. }
  45705. return activeTextures;
  45706. };
  45707. /**
  45708. * Checks to see if a texture is used in the material.
  45709. * @param texture - Base texture to use.
  45710. * @returns - Boolean specifying if a texture is used in the material.
  45711. */
  45712. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45713. if (_super.prototype.hasTexture.call(this, texture)) {
  45714. return true;
  45715. }
  45716. if (this.diffuseTexture === texture) {
  45717. return true;
  45718. }
  45719. if (this.specularGlossinessTexture === texture) {
  45720. return true;
  45721. }
  45722. return false;
  45723. };
  45724. /**
  45725. * Makes a duplicate of the current material.
  45726. * @param name - name to use for the new material.
  45727. */
  45728. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45729. var _this = this;
  45730. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45731. clone.id = name;
  45732. clone.name = name;
  45733. return clone;
  45734. };
  45735. /**
  45736. * Serialize the material to a parsable JSON object.
  45737. */
  45738. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45739. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45740. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45741. return serializationObject;
  45742. };
  45743. /**
  45744. * Parses a JSON object correponding to the serialize function.
  45745. */
  45746. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45747. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45748. };
  45749. __decorate([
  45750. BABYLON.serializeAsColor3("diffuse"),
  45751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45752. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45753. __decorate([
  45754. BABYLON.serializeAsTexture(),
  45755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45756. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45757. __decorate([
  45758. BABYLON.serializeAsColor3("specular"),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45760. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45764. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45765. __decorate([
  45766. BABYLON.serializeAsTexture(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45768. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45769. return PBRSpecularGlossinessMaterial;
  45770. }(BABYLON.PBRBaseSimpleMaterial));
  45771. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45772. })(BABYLON || (BABYLON = {}));
  45773. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45774. var BABYLON;
  45775. (function (BABYLON) {
  45776. BABYLON.CameraInputTypes = {};
  45777. var CameraInputsManager = /** @class */ (function () {
  45778. function CameraInputsManager(camera) {
  45779. this.attached = {};
  45780. this.camera = camera;
  45781. this.checkInputs = function () { };
  45782. }
  45783. /**
  45784. * Add an input method to a camera
  45785. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45786. * @param input camera input method
  45787. */
  45788. CameraInputsManager.prototype.add = function (input) {
  45789. var type = input.getSimpleName();
  45790. if (this.attached[type]) {
  45791. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45792. return;
  45793. }
  45794. this.attached[type] = input;
  45795. input.camera = this.camera;
  45796. //for checkInputs, we are dynamically creating a function
  45797. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45798. if (input.checkInputs) {
  45799. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45800. }
  45801. if (this.attachedElement) {
  45802. input.attachControl(this.attachedElement);
  45803. }
  45804. };
  45805. /**
  45806. * Remove a specific input method from a camera
  45807. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45808. * @param inputToRemove camera input method
  45809. */
  45810. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45811. for (var cam in this.attached) {
  45812. var input = this.attached[cam];
  45813. if (input === inputToRemove) {
  45814. input.detachControl(this.attachedElement);
  45815. input.camera = null;
  45816. delete this.attached[cam];
  45817. this.rebuildInputCheck();
  45818. }
  45819. }
  45820. };
  45821. CameraInputsManager.prototype.removeByType = function (inputType) {
  45822. for (var cam in this.attached) {
  45823. var input = this.attached[cam];
  45824. if (input.getClassName() === inputType) {
  45825. input.detachControl(this.attachedElement);
  45826. input.camera = null;
  45827. delete this.attached[cam];
  45828. this.rebuildInputCheck();
  45829. }
  45830. }
  45831. };
  45832. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45833. var current = this.checkInputs;
  45834. return function () {
  45835. current();
  45836. fn();
  45837. };
  45838. };
  45839. CameraInputsManager.prototype.attachInput = function (input) {
  45840. if (this.attachedElement) {
  45841. input.attachControl(this.attachedElement, this.noPreventDefault);
  45842. }
  45843. };
  45844. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45845. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45846. if (this.attachedElement) {
  45847. return;
  45848. }
  45849. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45850. this.attachedElement = element;
  45851. this.noPreventDefault = noPreventDefault;
  45852. for (var cam in this.attached) {
  45853. this.attached[cam].attachControl(element, noPreventDefault);
  45854. }
  45855. };
  45856. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45857. if (disconnect === void 0) { disconnect = false; }
  45858. if (this.attachedElement !== element) {
  45859. return;
  45860. }
  45861. for (var cam in this.attached) {
  45862. this.attached[cam].detachControl(element);
  45863. if (disconnect) {
  45864. this.attached[cam].camera = null;
  45865. }
  45866. }
  45867. this.attachedElement = null;
  45868. };
  45869. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45870. this.checkInputs = function () { };
  45871. for (var cam in this.attached) {
  45872. var input = this.attached[cam];
  45873. if (input.checkInputs) {
  45874. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45875. }
  45876. }
  45877. };
  45878. /**
  45879. * Remove all attached input methods from a camera
  45880. */
  45881. CameraInputsManager.prototype.clear = function () {
  45882. if (this.attachedElement) {
  45883. this.detachElement(this.attachedElement, true);
  45884. }
  45885. this.attached = {};
  45886. this.attachedElement = null;
  45887. this.checkInputs = function () { };
  45888. };
  45889. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45890. var inputs = {};
  45891. for (var cam in this.attached) {
  45892. var input = this.attached[cam];
  45893. var res = BABYLON.SerializationHelper.Serialize(input);
  45894. inputs[input.getClassName()] = res;
  45895. }
  45896. serializedCamera.inputsmgr = inputs;
  45897. };
  45898. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45899. var parsedInputs = parsedCamera.inputsmgr;
  45900. if (parsedInputs) {
  45901. this.clear();
  45902. for (var n in parsedInputs) {
  45903. var construct = BABYLON.CameraInputTypes[n];
  45904. if (construct) {
  45905. var parsedinput = parsedInputs[n];
  45906. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45907. this.add(input);
  45908. }
  45909. }
  45910. }
  45911. else {
  45912. //2016-03-08 this part is for managing backward compatibility
  45913. for (var n in this.attached) {
  45914. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45915. if (construct) {
  45916. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45917. this.remove(this.attached[n]);
  45918. this.add(input);
  45919. }
  45920. }
  45921. }
  45922. };
  45923. return CameraInputsManager;
  45924. }());
  45925. BABYLON.CameraInputsManager = CameraInputsManager;
  45926. })(BABYLON || (BABYLON = {}));
  45927. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45928. var BABYLON;
  45929. (function (BABYLON) {
  45930. var TargetCamera = /** @class */ (function (_super) {
  45931. __extends(TargetCamera, _super);
  45932. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45933. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45934. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45935. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45936. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45937. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45938. _this.speed = 2.0;
  45939. _this.noRotationConstraint = false;
  45940. _this.lockedTarget = null;
  45941. /** @hidden */
  45942. _this._currentTarget = BABYLON.Vector3.Zero();
  45943. /** @hidden */
  45944. _this._viewMatrix = BABYLON.Matrix.Zero();
  45945. /** @hidden */
  45946. _this._camMatrix = BABYLON.Matrix.Zero();
  45947. /** @hidden */
  45948. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45949. /** @hidden */
  45950. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45951. /** @hidden */
  45952. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45953. /** @hidden */
  45954. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45955. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45956. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45957. _this._defaultUp = BABYLON.Vector3.Up();
  45958. _this._cachedRotationZ = 0;
  45959. return _this;
  45960. }
  45961. TargetCamera.prototype.getFrontPosition = function (distance) {
  45962. this.getWorldMatrix();
  45963. var direction = this.getTarget().subtract(this.position);
  45964. direction.normalize();
  45965. direction.scaleInPlace(distance);
  45966. return this.globalPosition.add(direction);
  45967. };
  45968. /** @hidden */
  45969. TargetCamera.prototype._getLockedTargetPosition = function () {
  45970. if (!this.lockedTarget) {
  45971. return null;
  45972. }
  45973. if (this.lockedTarget.absolutePosition) {
  45974. this.lockedTarget.computeWorldMatrix();
  45975. }
  45976. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45977. };
  45978. TargetCamera.prototype.storeState = function () {
  45979. this._storedPosition = this.position.clone();
  45980. this._storedRotation = this.rotation.clone();
  45981. if (this.rotationQuaternion) {
  45982. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45983. }
  45984. return _super.prototype.storeState.call(this);
  45985. };
  45986. /**
  45987. * Restored camera state. You must call storeState() first
  45988. * @returns whether it was successful or not
  45989. * @hidden
  45990. */
  45991. TargetCamera.prototype._restoreStateValues = function () {
  45992. if (!_super.prototype._restoreStateValues.call(this)) {
  45993. return false;
  45994. }
  45995. this.position = this._storedPosition.clone();
  45996. this.rotation = this._storedRotation.clone();
  45997. if (this.rotationQuaternion) {
  45998. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45999. }
  46000. this.cameraDirection.copyFromFloats(0, 0, 0);
  46001. this.cameraRotation.copyFromFloats(0, 0);
  46002. return true;
  46003. };
  46004. // Cache
  46005. /** @hidden */
  46006. TargetCamera.prototype._initCache = function () {
  46007. _super.prototype._initCache.call(this);
  46008. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46009. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46010. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46011. };
  46012. /** @hidden */
  46013. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46014. if (!ignoreParentClass) {
  46015. _super.prototype._updateCache.call(this);
  46016. }
  46017. var lockedTargetPosition = this._getLockedTargetPosition();
  46018. if (!lockedTargetPosition) {
  46019. this._cache.lockedTarget = null;
  46020. }
  46021. else {
  46022. if (!this._cache.lockedTarget) {
  46023. this._cache.lockedTarget = lockedTargetPosition.clone();
  46024. }
  46025. else {
  46026. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46027. }
  46028. }
  46029. this._cache.rotation.copyFrom(this.rotation);
  46030. if (this.rotationQuaternion)
  46031. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46032. };
  46033. // Synchronized
  46034. /** @hidden */
  46035. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46036. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46037. return false;
  46038. }
  46039. var lockedTargetPosition = this._getLockedTargetPosition();
  46040. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46041. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46042. };
  46043. // Methods
  46044. /** @hidden */
  46045. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46046. var engine = this.getEngine();
  46047. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46048. };
  46049. // Target
  46050. /** @hidden */
  46051. TargetCamera.prototype.setTarget = function (target) {
  46052. this.upVector.normalize();
  46053. if (this.position.z === target.z) {
  46054. this.position.z += BABYLON.Epsilon;
  46055. }
  46056. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46057. this._camMatrix.invert();
  46058. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46059. var vDir = target.subtract(this.position);
  46060. if (vDir.x >= 0.0) {
  46061. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46062. }
  46063. else {
  46064. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46065. }
  46066. this.rotation.z = 0;
  46067. if (isNaN(this.rotation.x)) {
  46068. this.rotation.x = 0;
  46069. }
  46070. if (isNaN(this.rotation.y)) {
  46071. this.rotation.y = 0;
  46072. }
  46073. if (isNaN(this.rotation.z)) {
  46074. this.rotation.z = 0;
  46075. }
  46076. if (this.rotationQuaternion) {
  46077. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46078. }
  46079. };
  46080. /**
  46081. * Return the current target position of the camera. This value is expressed in local space.
  46082. */
  46083. TargetCamera.prototype.getTarget = function () {
  46084. return this._currentTarget;
  46085. };
  46086. /** @hidden */
  46087. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46088. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46089. };
  46090. /** @hidden */
  46091. TargetCamera.prototype._updatePosition = function () {
  46092. if (this.parent) {
  46093. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46094. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46095. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46096. return;
  46097. }
  46098. this.position.addInPlace(this.cameraDirection);
  46099. };
  46100. /** @hidden */
  46101. TargetCamera.prototype._checkInputs = function () {
  46102. var needToMove = this._decideIfNeedsToMove();
  46103. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46104. // Move
  46105. if (needToMove) {
  46106. this._updatePosition();
  46107. }
  46108. // Rotate
  46109. if (needToRotate) {
  46110. this.rotation.x += this.cameraRotation.x;
  46111. this.rotation.y += this.cameraRotation.y;
  46112. //rotate, if quaternion is set and rotation was used
  46113. if (this.rotationQuaternion) {
  46114. var len = this.rotation.lengthSquared();
  46115. if (len) {
  46116. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46117. }
  46118. }
  46119. if (!this.noRotationConstraint) {
  46120. var limit = (Math.PI / 2) * 0.95;
  46121. if (this.rotation.x > limit)
  46122. this.rotation.x = limit;
  46123. if (this.rotation.x < -limit)
  46124. this.rotation.x = -limit;
  46125. }
  46126. }
  46127. // Inertia
  46128. if (needToMove) {
  46129. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46130. this.cameraDirection.x = 0;
  46131. }
  46132. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46133. this.cameraDirection.y = 0;
  46134. }
  46135. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46136. this.cameraDirection.z = 0;
  46137. }
  46138. this.cameraDirection.scaleInPlace(this.inertia);
  46139. }
  46140. if (needToRotate) {
  46141. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46142. this.cameraRotation.x = 0;
  46143. }
  46144. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46145. this.cameraRotation.y = 0;
  46146. }
  46147. this.cameraRotation.scaleInPlace(this.inertia);
  46148. }
  46149. _super.prototype._checkInputs.call(this);
  46150. };
  46151. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46152. if (this.rotationQuaternion) {
  46153. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46154. }
  46155. else {
  46156. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46157. }
  46158. };
  46159. /**
  46160. * 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)
  46161. * @returns the current camera
  46162. */
  46163. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46164. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46165. return this;
  46166. };
  46167. /** @hidden */
  46168. TargetCamera.prototype._getViewMatrix = function () {
  46169. if (this.lockedTarget) {
  46170. this.setTarget(this._getLockedTargetPosition());
  46171. }
  46172. // Compute
  46173. this._updateCameraRotationMatrix();
  46174. // Apply the changed rotation to the upVector.
  46175. if (this._cachedRotationZ != this.rotation.z) {
  46176. this._rotateUpVectorWithCameraRotationMatrix();
  46177. this._cachedRotationZ = this.rotation.z;
  46178. }
  46179. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46180. // Computing target and final matrix
  46181. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46182. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46183. return this._viewMatrix;
  46184. };
  46185. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46186. if (this.parent) {
  46187. var parentWorldMatrix = this.parent.getWorldMatrix();
  46188. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46189. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46190. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46191. this._markSyncedWithParent();
  46192. }
  46193. else {
  46194. this._globalPosition.copyFrom(position);
  46195. this._globalCurrentTarget.copyFrom(target);
  46196. this._globalCurrentUpVector.copyFrom(up);
  46197. }
  46198. if (this.getScene().useRightHandedSystem) {
  46199. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46200. }
  46201. else {
  46202. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46203. }
  46204. };
  46205. /**
  46206. * @override
  46207. * Override Camera.createRigCamera
  46208. */
  46209. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46210. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46211. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46212. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46213. if (!this.rotationQuaternion) {
  46214. this.rotationQuaternion = new BABYLON.Quaternion();
  46215. }
  46216. rigCamera._cameraRigParams = {};
  46217. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46218. }
  46219. return rigCamera;
  46220. }
  46221. return null;
  46222. };
  46223. /**
  46224. * @hidden
  46225. * @override
  46226. * Override Camera._updateRigCameras
  46227. */
  46228. TargetCamera.prototype._updateRigCameras = function () {
  46229. var camLeft = this._rigCameras[0];
  46230. var camRight = this._rigCameras[1];
  46231. switch (this.cameraRigMode) {
  46232. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46233. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46234. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46235. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46236. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46237. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46238. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46239. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46240. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46241. camLeft.setTarget(this.getTarget());
  46242. camRight.setTarget(this.getTarget());
  46243. break;
  46244. case BABYLON.Camera.RIG_MODE_VR:
  46245. if (camLeft.rotationQuaternion) {
  46246. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46247. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46248. }
  46249. else {
  46250. camLeft.rotation.copyFrom(this.rotation);
  46251. camRight.rotation.copyFrom(this.rotation);
  46252. }
  46253. camLeft.position.copyFrom(this.position);
  46254. camRight.position.copyFrom(this.position);
  46255. break;
  46256. }
  46257. _super.prototype._updateRigCameras.call(this);
  46258. };
  46259. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46260. if (!this._rigCamTransformMatrix) {
  46261. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46262. }
  46263. var target = this.getTarget();
  46264. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46265. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46266. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46267. };
  46268. TargetCamera.prototype.getClassName = function () {
  46269. return "TargetCamera";
  46270. };
  46271. __decorate([
  46272. BABYLON.serializeAsVector3()
  46273. ], TargetCamera.prototype, "rotation", void 0);
  46274. __decorate([
  46275. BABYLON.serialize()
  46276. ], TargetCamera.prototype, "speed", void 0);
  46277. __decorate([
  46278. BABYLON.serializeAsMeshReference("lockedTargetId")
  46279. ], TargetCamera.prototype, "lockedTarget", void 0);
  46280. return TargetCamera;
  46281. }(BABYLON.Camera));
  46282. BABYLON.TargetCamera = TargetCamera;
  46283. })(BABYLON || (BABYLON = {}));
  46284. //# sourceMappingURL=babylon.targetCamera.js.map
  46285. var BABYLON;
  46286. (function (BABYLON) {
  46287. var FreeCameraMouseInput = /** @class */ (function () {
  46288. function FreeCameraMouseInput(touchEnabled) {
  46289. if (touchEnabled === void 0) { touchEnabled = true; }
  46290. this.touchEnabled = touchEnabled;
  46291. this.buttons = [0, 1, 2];
  46292. this.angularSensibility = 2000.0;
  46293. this.previousPosition = null;
  46294. }
  46295. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46296. var _this = this;
  46297. var engine = this.camera.getEngine();
  46298. if (!this._pointerInput) {
  46299. this._pointerInput = function (p, s) {
  46300. var evt = p.event;
  46301. if (engine.isInVRExclusivePointerMode) {
  46302. return;
  46303. }
  46304. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46305. return;
  46306. }
  46307. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46308. return;
  46309. }
  46310. var srcElement = (evt.srcElement || evt.target);
  46311. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46312. try {
  46313. srcElement.setPointerCapture(evt.pointerId);
  46314. }
  46315. catch (e) {
  46316. //Nothing to do with the error. Execution will continue.
  46317. }
  46318. _this.previousPosition = {
  46319. x: evt.clientX,
  46320. y: evt.clientY
  46321. };
  46322. if (!noPreventDefault) {
  46323. evt.preventDefault();
  46324. element.focus();
  46325. }
  46326. }
  46327. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46328. try {
  46329. srcElement.releasePointerCapture(evt.pointerId);
  46330. }
  46331. catch (e) {
  46332. //Nothing to do with the error.
  46333. }
  46334. _this.previousPosition = null;
  46335. if (!noPreventDefault) {
  46336. evt.preventDefault();
  46337. }
  46338. }
  46339. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46340. if (!_this.previousPosition || engine.isPointerLock) {
  46341. return;
  46342. }
  46343. var offsetX = evt.clientX - _this.previousPosition.x;
  46344. if (_this.camera.getScene().useRightHandedSystem)
  46345. offsetX *= -1;
  46346. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46347. offsetX *= -1;
  46348. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46349. var offsetY = evt.clientY - _this.previousPosition.y;
  46350. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46351. _this.previousPosition = {
  46352. x: evt.clientX,
  46353. y: evt.clientY
  46354. };
  46355. if (!noPreventDefault) {
  46356. evt.preventDefault();
  46357. }
  46358. }
  46359. };
  46360. }
  46361. this._onMouseMove = function (evt) {
  46362. if (!engine.isPointerLock) {
  46363. return;
  46364. }
  46365. if (engine.isInVRExclusivePointerMode) {
  46366. return;
  46367. }
  46368. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46369. if (_this.camera.getScene().useRightHandedSystem)
  46370. offsetX *= -1;
  46371. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46372. offsetX *= -1;
  46373. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46374. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46375. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46376. _this.previousPosition = null;
  46377. if (!noPreventDefault) {
  46378. evt.preventDefault();
  46379. }
  46380. };
  46381. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46382. element.addEventListener("mousemove", this._onMouseMove, false);
  46383. };
  46384. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46385. if (this._observer && element) {
  46386. this.camera.getScene().onPointerObservable.remove(this._observer);
  46387. if (this._onMouseMove) {
  46388. element.removeEventListener("mousemove", this._onMouseMove);
  46389. }
  46390. this._observer = null;
  46391. this._onMouseMove = null;
  46392. this.previousPosition = null;
  46393. }
  46394. };
  46395. FreeCameraMouseInput.prototype.getClassName = function () {
  46396. return "FreeCameraMouseInput";
  46397. };
  46398. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46399. return "mouse";
  46400. };
  46401. __decorate([
  46402. BABYLON.serialize()
  46403. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46404. __decorate([
  46405. BABYLON.serialize()
  46406. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46407. return FreeCameraMouseInput;
  46408. }());
  46409. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46410. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46411. })(BABYLON || (BABYLON = {}));
  46412. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46413. var BABYLON;
  46414. (function (BABYLON) {
  46415. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46416. function FreeCameraKeyboardMoveInput() {
  46417. this._keys = new Array();
  46418. this.keysUp = [38];
  46419. this.keysDown = [40];
  46420. this.keysLeft = [37];
  46421. this.keysRight = [39];
  46422. }
  46423. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46424. var _this = this;
  46425. if (this._onCanvasBlurObserver) {
  46426. return;
  46427. }
  46428. this._scene = this.camera.getScene();
  46429. this._engine = this._scene.getEngine();
  46430. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46431. _this._keys = [];
  46432. });
  46433. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46434. var evt = info.event;
  46435. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46436. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46437. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46438. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46439. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46440. var index = _this._keys.indexOf(evt.keyCode);
  46441. if (index === -1) {
  46442. _this._keys.push(evt.keyCode);
  46443. }
  46444. if (!noPreventDefault) {
  46445. evt.preventDefault();
  46446. }
  46447. }
  46448. }
  46449. else {
  46450. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46451. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46452. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46453. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46454. var index = _this._keys.indexOf(evt.keyCode);
  46455. if (index >= 0) {
  46456. _this._keys.splice(index, 1);
  46457. }
  46458. if (!noPreventDefault) {
  46459. evt.preventDefault();
  46460. }
  46461. }
  46462. }
  46463. });
  46464. };
  46465. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46466. if (this._scene) {
  46467. if (this._onKeyboardObserver) {
  46468. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46469. }
  46470. if (this._onCanvasBlurObserver) {
  46471. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46472. }
  46473. this._onKeyboardObserver = null;
  46474. this._onCanvasBlurObserver = null;
  46475. }
  46476. this._keys = [];
  46477. };
  46478. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46479. if (this._onKeyboardObserver) {
  46480. var camera = this.camera;
  46481. // Keyboard
  46482. for (var index = 0; index < this._keys.length; index++) {
  46483. var keyCode = this._keys[index];
  46484. var speed = camera._computeLocalCameraSpeed();
  46485. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46486. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46487. }
  46488. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46489. camera._localDirection.copyFromFloats(0, 0, speed);
  46490. }
  46491. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46492. camera._localDirection.copyFromFloats(speed, 0, 0);
  46493. }
  46494. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46495. camera._localDirection.copyFromFloats(0, 0, -speed);
  46496. }
  46497. if (camera.getScene().useRightHandedSystem) {
  46498. camera._localDirection.z *= -1;
  46499. }
  46500. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46501. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46502. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46503. }
  46504. }
  46505. };
  46506. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46507. return "FreeCameraKeyboardMoveInput";
  46508. };
  46509. /** @hidden */
  46510. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46511. this._keys = [];
  46512. };
  46513. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46514. return "keyboard";
  46515. };
  46516. __decorate([
  46517. BABYLON.serialize()
  46518. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46519. __decorate([
  46520. BABYLON.serialize()
  46521. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46522. __decorate([
  46523. BABYLON.serialize()
  46524. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46525. __decorate([
  46526. BABYLON.serialize()
  46527. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46528. return FreeCameraKeyboardMoveInput;
  46529. }());
  46530. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46531. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46532. })(BABYLON || (BABYLON = {}));
  46533. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46534. var BABYLON;
  46535. (function (BABYLON) {
  46536. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46537. __extends(FreeCameraInputsManager, _super);
  46538. function FreeCameraInputsManager(camera) {
  46539. return _super.call(this, camera) || this;
  46540. }
  46541. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46542. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46543. return this;
  46544. };
  46545. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46546. if (touchEnabled === void 0) { touchEnabled = true; }
  46547. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46548. return this;
  46549. };
  46550. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46551. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46552. return this;
  46553. };
  46554. FreeCameraInputsManager.prototype.addTouch = function () {
  46555. this.add(new BABYLON.FreeCameraTouchInput());
  46556. return this;
  46557. };
  46558. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46559. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46560. return this;
  46561. };
  46562. return FreeCameraInputsManager;
  46563. }(BABYLON.CameraInputsManager));
  46564. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46565. })(BABYLON || (BABYLON = {}));
  46566. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46567. var BABYLON;
  46568. (function (BABYLON) {
  46569. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46570. // Forcing to use the Universal camera
  46571. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46572. });
  46573. var FreeCamera = /** @class */ (function (_super) {
  46574. __extends(FreeCamera, _super);
  46575. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46576. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46577. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46578. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46579. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46580. _this.checkCollisions = false;
  46581. _this.applyGravity = false;
  46582. _this._needMoveForGravity = false;
  46583. _this._oldPosition = BABYLON.Vector3.Zero();
  46584. _this._diffPosition = BABYLON.Vector3.Zero();
  46585. _this._newPosition = BABYLON.Vector3.Zero();
  46586. // Collisions
  46587. _this._collisionMask = -1;
  46588. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46589. if (collidedMesh === void 0) { collidedMesh = null; }
  46590. //TODO move this to the collision coordinator!
  46591. if (_this.getScene().workerCollisions)
  46592. newPosition.multiplyInPlace(_this._collider._radius);
  46593. var updatePosition = function (newPos) {
  46594. _this._newPosition.copyFrom(newPos);
  46595. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46596. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46597. _this.position.addInPlace(_this._diffPosition);
  46598. if (_this.onCollide && collidedMesh) {
  46599. _this.onCollide(collidedMesh);
  46600. }
  46601. }
  46602. };
  46603. updatePosition(newPosition);
  46604. };
  46605. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46606. _this.inputs.addKeyboard().addMouse();
  46607. return _this;
  46608. }
  46609. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46610. //-- begin properties for backward compatibility for inputs
  46611. /**
  46612. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46613. * Higher values reduce sensitivity.
  46614. */
  46615. get: function () {
  46616. var mouse = this.inputs.attached["mouse"];
  46617. if (mouse)
  46618. return mouse.angularSensibility;
  46619. return 0;
  46620. },
  46621. /**
  46622. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46623. * Higher values reduce sensitivity.
  46624. */
  46625. set: function (value) {
  46626. var mouse = this.inputs.attached["mouse"];
  46627. if (mouse)
  46628. mouse.angularSensibility = value;
  46629. },
  46630. enumerable: true,
  46631. configurable: true
  46632. });
  46633. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46634. get: function () {
  46635. var keyboard = this.inputs.attached["keyboard"];
  46636. if (keyboard)
  46637. return keyboard.keysUp;
  46638. return [];
  46639. },
  46640. set: function (value) {
  46641. var keyboard = this.inputs.attached["keyboard"];
  46642. if (keyboard)
  46643. keyboard.keysUp = value;
  46644. },
  46645. enumerable: true,
  46646. configurable: true
  46647. });
  46648. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46649. get: function () {
  46650. var keyboard = this.inputs.attached["keyboard"];
  46651. if (keyboard)
  46652. return keyboard.keysDown;
  46653. return [];
  46654. },
  46655. set: function (value) {
  46656. var keyboard = this.inputs.attached["keyboard"];
  46657. if (keyboard)
  46658. keyboard.keysDown = value;
  46659. },
  46660. enumerable: true,
  46661. configurable: true
  46662. });
  46663. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46664. get: function () {
  46665. var keyboard = this.inputs.attached["keyboard"];
  46666. if (keyboard)
  46667. return keyboard.keysLeft;
  46668. return [];
  46669. },
  46670. set: function (value) {
  46671. var keyboard = this.inputs.attached["keyboard"];
  46672. if (keyboard)
  46673. keyboard.keysLeft = value;
  46674. },
  46675. enumerable: true,
  46676. configurable: true
  46677. });
  46678. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46679. get: function () {
  46680. var keyboard = this.inputs.attached["keyboard"];
  46681. if (keyboard)
  46682. return keyboard.keysRight;
  46683. return [];
  46684. },
  46685. set: function (value) {
  46686. var keyboard = this.inputs.attached["keyboard"];
  46687. if (keyboard)
  46688. keyboard.keysRight = value;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. // Controls
  46694. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46695. this.inputs.attachElement(element, noPreventDefault);
  46696. };
  46697. FreeCamera.prototype.detachControl = function (element) {
  46698. this.inputs.detachElement(element);
  46699. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46700. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46701. };
  46702. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46703. get: function () {
  46704. return this._collisionMask;
  46705. },
  46706. set: function (mask) {
  46707. this._collisionMask = !isNaN(mask) ? mask : -1;
  46708. },
  46709. enumerable: true,
  46710. configurable: true
  46711. });
  46712. /** @hidden */
  46713. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46714. var globalPosition;
  46715. if (this.parent) {
  46716. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46717. }
  46718. else {
  46719. globalPosition = this.position;
  46720. }
  46721. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46722. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46723. if (!this._collider) {
  46724. this._collider = new BABYLON.Collider();
  46725. }
  46726. this._collider._radius = this.ellipsoid;
  46727. this._collider.collisionMask = this._collisionMask;
  46728. //no need for clone, as long as gravity is not on.
  46729. var actualDisplacement = displacement;
  46730. //add gravity to the direction to prevent the dual-collision checking
  46731. if (this.applyGravity) {
  46732. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46733. actualDisplacement = displacement.add(this.getScene().gravity);
  46734. }
  46735. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46736. };
  46737. /** @hidden */
  46738. FreeCamera.prototype._checkInputs = function () {
  46739. if (!this._localDirection) {
  46740. this._localDirection = BABYLON.Vector3.Zero();
  46741. this._transformedDirection = BABYLON.Vector3.Zero();
  46742. }
  46743. this.inputs.checkInputs();
  46744. _super.prototype._checkInputs.call(this);
  46745. };
  46746. /** @hidden */
  46747. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46748. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46749. };
  46750. /** @hidden */
  46751. FreeCamera.prototype._updatePosition = function () {
  46752. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46753. this._collideWithWorld(this.cameraDirection);
  46754. }
  46755. else {
  46756. _super.prototype._updatePosition.call(this);
  46757. }
  46758. };
  46759. FreeCamera.prototype.dispose = function () {
  46760. this.inputs.clear();
  46761. _super.prototype.dispose.call(this);
  46762. };
  46763. FreeCamera.prototype.getClassName = function () {
  46764. return "FreeCamera";
  46765. };
  46766. __decorate([
  46767. BABYLON.serializeAsVector3()
  46768. ], FreeCamera.prototype, "ellipsoid", void 0);
  46769. __decorate([
  46770. BABYLON.serializeAsVector3()
  46771. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46772. __decorate([
  46773. BABYLON.serialize()
  46774. ], FreeCamera.prototype, "checkCollisions", void 0);
  46775. __decorate([
  46776. BABYLON.serialize()
  46777. ], FreeCamera.prototype, "applyGravity", void 0);
  46778. return FreeCamera;
  46779. }(BABYLON.TargetCamera));
  46780. BABYLON.FreeCamera = FreeCamera;
  46781. })(BABYLON || (BABYLON = {}));
  46782. //# sourceMappingURL=babylon.freeCamera.js.map
  46783. var BABYLON;
  46784. (function (BABYLON) {
  46785. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46786. function ArcRotateCameraKeyboardMoveInput() {
  46787. this._keys = new Array();
  46788. this.keysUp = [38];
  46789. this.keysDown = [40];
  46790. this.keysLeft = [37];
  46791. this.keysRight = [39];
  46792. this.keysReset = [220];
  46793. this.panningSensibility = 50.0;
  46794. this.zoomingSensibility = 25.0;
  46795. this.useAltToZoom = true;
  46796. }
  46797. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46798. var _this = this;
  46799. if (this._onCanvasBlurObserver) {
  46800. return;
  46801. }
  46802. this._scene = this.camera.getScene();
  46803. this._engine = this._scene.getEngine();
  46804. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46805. _this._keys = [];
  46806. });
  46807. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46808. var evt = info.event;
  46809. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46810. _this._ctrlPressed = evt.ctrlKey;
  46811. _this._altPressed = evt.altKey;
  46812. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46813. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46814. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46815. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46816. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46817. var index = _this._keys.indexOf(evt.keyCode);
  46818. if (index === -1) {
  46819. _this._keys.push(evt.keyCode);
  46820. }
  46821. if (evt.preventDefault) {
  46822. if (!noPreventDefault) {
  46823. evt.preventDefault();
  46824. }
  46825. }
  46826. }
  46827. }
  46828. else {
  46829. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46830. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46831. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46832. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46833. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46834. var index = _this._keys.indexOf(evt.keyCode);
  46835. if (index >= 0) {
  46836. _this._keys.splice(index, 1);
  46837. }
  46838. if (evt.preventDefault) {
  46839. if (!noPreventDefault) {
  46840. evt.preventDefault();
  46841. }
  46842. }
  46843. }
  46844. }
  46845. });
  46846. };
  46847. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46848. if (this._scene) {
  46849. if (this._onKeyboardObserver) {
  46850. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46851. }
  46852. if (this._onCanvasBlurObserver) {
  46853. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46854. }
  46855. this._onKeyboardObserver = null;
  46856. this._onCanvasBlurObserver = null;
  46857. }
  46858. this._keys = [];
  46859. };
  46860. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46861. if (this._onKeyboardObserver) {
  46862. var camera = this.camera;
  46863. for (var index = 0; index < this._keys.length; index++) {
  46864. var keyCode = this._keys[index];
  46865. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46866. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46867. camera.inertialPanningX -= 1 / this.panningSensibility;
  46868. }
  46869. else {
  46870. camera.inertialAlphaOffset -= 0.01;
  46871. }
  46872. }
  46873. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46874. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46875. camera.inertialPanningY += 1 / this.panningSensibility;
  46876. }
  46877. else if (this._altPressed && this.useAltToZoom) {
  46878. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46879. }
  46880. else {
  46881. camera.inertialBetaOffset -= 0.01;
  46882. }
  46883. }
  46884. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46885. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46886. camera.inertialPanningX += 1 / this.panningSensibility;
  46887. }
  46888. else {
  46889. camera.inertialAlphaOffset += 0.01;
  46890. }
  46891. }
  46892. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46893. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46894. camera.inertialPanningY -= 1 / this.panningSensibility;
  46895. }
  46896. else if (this._altPressed && this.useAltToZoom) {
  46897. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46898. }
  46899. else {
  46900. camera.inertialBetaOffset += 0.01;
  46901. }
  46902. }
  46903. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46904. camera.restoreState();
  46905. }
  46906. }
  46907. }
  46908. };
  46909. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46910. return "ArcRotateCameraKeyboardMoveInput";
  46911. };
  46912. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46913. return "keyboard";
  46914. };
  46915. __decorate([
  46916. BABYLON.serialize()
  46917. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46918. __decorate([
  46919. BABYLON.serialize()
  46920. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46924. __decorate([
  46925. BABYLON.serialize()
  46926. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46927. __decorate([
  46928. BABYLON.serialize()
  46929. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46930. __decorate([
  46931. BABYLON.serialize()
  46932. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46933. __decorate([
  46934. BABYLON.serialize()
  46935. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46936. __decorate([
  46937. BABYLON.serialize()
  46938. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46939. return ArcRotateCameraKeyboardMoveInput;
  46940. }());
  46941. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46942. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46943. })(BABYLON || (BABYLON = {}));
  46944. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46945. var BABYLON;
  46946. (function (BABYLON) {
  46947. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46948. function ArcRotateCameraMouseWheelInput() {
  46949. this.wheelPrecision = 3.0;
  46950. /**
  46951. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46952. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46953. */
  46954. this.wheelDeltaPercentage = 0;
  46955. }
  46956. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46957. var _this = this;
  46958. this._wheel = function (p, s) {
  46959. //sanity check - this should be a PointerWheel event.
  46960. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46961. return;
  46962. var event = p.event;
  46963. var delta = 0;
  46964. if (event.wheelDelta) {
  46965. if (_this.wheelDeltaPercentage) {
  46966. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46967. if (event.wheelDelta > 0) {
  46968. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46969. }
  46970. else {
  46971. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46972. }
  46973. }
  46974. else {
  46975. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46976. }
  46977. }
  46978. else if (event.detail) {
  46979. delta = -event.detail / _this.wheelPrecision;
  46980. }
  46981. if (delta)
  46982. _this.camera.inertialRadiusOffset += delta;
  46983. if (event.preventDefault) {
  46984. if (!noPreventDefault) {
  46985. event.preventDefault();
  46986. }
  46987. }
  46988. };
  46989. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46990. };
  46991. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46992. if (this._observer && element) {
  46993. this.camera.getScene().onPointerObservable.remove(this._observer);
  46994. this._observer = null;
  46995. this._wheel = null;
  46996. }
  46997. };
  46998. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46999. return "ArcRotateCameraMouseWheelInput";
  47000. };
  47001. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47002. return "mousewheel";
  47003. };
  47004. __decorate([
  47005. BABYLON.serialize()
  47006. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47007. __decorate([
  47008. BABYLON.serialize()
  47009. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47010. return ArcRotateCameraMouseWheelInput;
  47011. }());
  47012. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47013. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47014. })(BABYLON || (BABYLON = {}));
  47015. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47016. var BABYLON;
  47017. (function (BABYLON) {
  47018. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47019. function ArcRotateCameraPointersInput() {
  47020. this.buttons = [0, 1, 2];
  47021. this.angularSensibilityX = 1000.0;
  47022. this.angularSensibilityY = 1000.0;
  47023. this.pinchPrecision = 12.0;
  47024. /**
  47025. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47026. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47027. */
  47028. this.pinchDeltaPercentage = 0;
  47029. this.panningSensibility = 1000.0;
  47030. this.multiTouchPanning = true;
  47031. this.multiTouchPanAndZoom = true;
  47032. this._isPanClick = false;
  47033. this.pinchInwards = true;
  47034. }
  47035. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47036. var _this = this;
  47037. var engine = this.camera.getEngine();
  47038. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47039. var pointA = null;
  47040. var pointB = null;
  47041. var previousPinchSquaredDistance = 0;
  47042. var initialDistance = 0;
  47043. var twoFingerActivityCount = 0;
  47044. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47045. this._pointerInput = function (p, s) {
  47046. var evt = p.event;
  47047. var isTouch = p.event.pointerType === "touch";
  47048. if (engine.isInVRExclusivePointerMode) {
  47049. return;
  47050. }
  47051. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47052. return;
  47053. }
  47054. var srcElement = (evt.srcElement || evt.target);
  47055. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47056. try {
  47057. srcElement.setPointerCapture(evt.pointerId);
  47058. }
  47059. catch (e) {
  47060. //Nothing to do with the error. Execution will continue.
  47061. }
  47062. // Manage panning with pan button click
  47063. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47064. // manage pointers
  47065. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47066. if (pointA === null) {
  47067. pointA = cacheSoloPointer;
  47068. }
  47069. else if (pointB === null) {
  47070. pointB = cacheSoloPointer;
  47071. }
  47072. if (!noPreventDefault) {
  47073. evt.preventDefault();
  47074. element.focus();
  47075. }
  47076. }
  47077. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47078. _this.camera.restoreState();
  47079. }
  47080. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47081. try {
  47082. srcElement.releasePointerCapture(evt.pointerId);
  47083. }
  47084. catch (e) {
  47085. //Nothing to do with the error.
  47086. }
  47087. cacheSoloPointer = null;
  47088. previousPinchSquaredDistance = 0;
  47089. previousMultiTouchPanPosition.isPaning = false;
  47090. previousMultiTouchPanPosition.isPinching = false;
  47091. twoFingerActivityCount = 0;
  47092. initialDistance = 0;
  47093. if (!isTouch) {
  47094. pointB = null; // Mouse and pen are mono pointer
  47095. }
  47096. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47097. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47098. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47099. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47100. if (engine._badOS) {
  47101. pointA = pointB = null;
  47102. }
  47103. else {
  47104. //only remove the impacted pointer in case of multitouch allowing on most
  47105. //platforms switching from rotate to zoom and pan seamlessly.
  47106. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47107. pointA = pointB;
  47108. pointB = null;
  47109. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47110. }
  47111. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47112. pointB = null;
  47113. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47114. }
  47115. else {
  47116. pointA = pointB = null;
  47117. }
  47118. }
  47119. if (!noPreventDefault) {
  47120. evt.preventDefault();
  47121. }
  47122. }
  47123. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47124. if (!noPreventDefault) {
  47125. evt.preventDefault();
  47126. }
  47127. // One button down
  47128. if (pointA && pointB === null && cacheSoloPointer) {
  47129. if (_this.panningSensibility !== 0 &&
  47130. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47131. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47132. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47133. }
  47134. else {
  47135. var offsetX = evt.clientX - cacheSoloPointer.x;
  47136. var offsetY = evt.clientY - cacheSoloPointer.y;
  47137. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47138. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47139. }
  47140. cacheSoloPointer.x = evt.clientX;
  47141. cacheSoloPointer.y = evt.clientY;
  47142. }
  47143. // Two buttons down: pinch/pan
  47144. else if (pointA && pointB) {
  47145. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47146. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47147. ed.x = evt.clientX;
  47148. ed.y = evt.clientY;
  47149. var direction = _this.pinchInwards ? 1 : -1;
  47150. var distX = pointA.x - pointB.x;
  47151. var distY = pointA.y - pointB.y;
  47152. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47153. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47154. if (previousPinchSquaredDistance === 0) {
  47155. initialDistance = pinchDistance;
  47156. previousPinchSquaredDistance = pinchSquaredDistance;
  47157. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47158. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47159. return;
  47160. }
  47161. if (_this.multiTouchPanAndZoom) {
  47162. if (_this.pinchDeltaPercentage) {
  47163. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47164. }
  47165. else {
  47166. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47167. (_this.pinchPrecision *
  47168. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47169. direction);
  47170. }
  47171. if (_this.panningSensibility !== 0) {
  47172. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47173. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47174. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47175. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47176. previousMultiTouchPanPosition.x = pointersCenterX;
  47177. previousMultiTouchPanPosition.y = pointersCenterY;
  47178. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47179. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47180. }
  47181. }
  47182. else {
  47183. twoFingerActivityCount++;
  47184. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47185. if (_this.pinchDeltaPercentage) {
  47186. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47187. }
  47188. else {
  47189. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47190. (_this.pinchPrecision *
  47191. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47192. direction);
  47193. }
  47194. previousMultiTouchPanPosition.isPaning = false;
  47195. previousMultiTouchPanPosition.isPinching = true;
  47196. }
  47197. else {
  47198. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47199. if (!previousMultiTouchPanPosition.isPaning) {
  47200. previousMultiTouchPanPosition.isPaning = true;
  47201. previousMultiTouchPanPosition.isPinching = false;
  47202. previousMultiTouchPanPosition.x = ed.x;
  47203. previousMultiTouchPanPosition.y = ed.y;
  47204. return;
  47205. }
  47206. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47207. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47208. }
  47209. }
  47210. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47211. previousMultiTouchPanPosition.x = ed.x;
  47212. previousMultiTouchPanPosition.y = ed.y;
  47213. }
  47214. }
  47215. previousPinchSquaredDistance = pinchSquaredDistance;
  47216. }
  47217. }
  47218. };
  47219. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47220. this._onContextMenu = function (evt) {
  47221. evt.preventDefault();
  47222. };
  47223. if (!this.camera._useCtrlForPanning) {
  47224. element.addEventListener("contextmenu", this._onContextMenu, false);
  47225. }
  47226. this._onLostFocus = function () {
  47227. //this._keys = [];
  47228. pointA = pointB = null;
  47229. previousPinchSquaredDistance = 0;
  47230. previousMultiTouchPanPosition.isPaning = false;
  47231. previousMultiTouchPanPosition.isPinching = false;
  47232. twoFingerActivityCount = 0;
  47233. cacheSoloPointer = null;
  47234. initialDistance = 0;
  47235. };
  47236. this._onMouseMove = function (evt) {
  47237. if (!engine.isPointerLock) {
  47238. return;
  47239. }
  47240. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47241. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47242. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47243. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47244. if (!noPreventDefault) {
  47245. evt.preventDefault();
  47246. }
  47247. };
  47248. this._onGestureStart = function (e) {
  47249. if (window.MSGesture === undefined) {
  47250. return;
  47251. }
  47252. if (!_this._MSGestureHandler) {
  47253. _this._MSGestureHandler = new MSGesture();
  47254. _this._MSGestureHandler.target = element;
  47255. }
  47256. _this._MSGestureHandler.addPointer(e.pointerId);
  47257. };
  47258. this._onGesture = function (e) {
  47259. _this.camera.radius *= e.scale;
  47260. if (e.preventDefault) {
  47261. if (!noPreventDefault) {
  47262. e.stopPropagation();
  47263. e.preventDefault();
  47264. }
  47265. }
  47266. };
  47267. element.addEventListener("mousemove", this._onMouseMove, false);
  47268. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47269. element.addEventListener("MSGestureChange", this._onGesture, false);
  47270. BABYLON.Tools.RegisterTopRootEvents([
  47271. { name: "blur", handler: this._onLostFocus }
  47272. ]);
  47273. };
  47274. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47275. if (this._onLostFocus) {
  47276. BABYLON.Tools.UnregisterTopRootEvents([
  47277. { name: "blur", handler: this._onLostFocus }
  47278. ]);
  47279. }
  47280. if (element && this._observer) {
  47281. this.camera.getScene().onPointerObservable.remove(this._observer);
  47282. this._observer = null;
  47283. if (this._onContextMenu) {
  47284. element.removeEventListener("contextmenu", this._onContextMenu);
  47285. }
  47286. if (this._onMouseMove) {
  47287. element.removeEventListener("mousemove", this._onMouseMove);
  47288. }
  47289. if (this._onGestureStart) {
  47290. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47291. }
  47292. if (this._onGesture) {
  47293. element.removeEventListener("MSGestureChange", this._onGesture);
  47294. }
  47295. this._isPanClick = false;
  47296. this.pinchInwards = true;
  47297. this._onMouseMove = null;
  47298. this._onGestureStart = null;
  47299. this._onGesture = null;
  47300. this._MSGestureHandler = null;
  47301. this._onLostFocus = null;
  47302. this._onContextMenu = null;
  47303. }
  47304. };
  47305. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47306. return "ArcRotateCameraPointersInput";
  47307. };
  47308. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47309. return "pointers";
  47310. };
  47311. __decorate([
  47312. BABYLON.serialize()
  47313. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47314. __decorate([
  47315. BABYLON.serialize()
  47316. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47317. __decorate([
  47318. BABYLON.serialize()
  47319. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47320. __decorate([
  47321. BABYLON.serialize()
  47322. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47323. __decorate([
  47324. BABYLON.serialize()
  47325. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47326. __decorate([
  47327. BABYLON.serialize()
  47328. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47329. __decorate([
  47330. BABYLON.serialize()
  47331. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47332. __decorate([
  47333. BABYLON.serialize()
  47334. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47335. return ArcRotateCameraPointersInput;
  47336. }());
  47337. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47338. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47339. })(BABYLON || (BABYLON = {}));
  47340. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47341. var BABYLON;
  47342. (function (BABYLON) {
  47343. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47344. __extends(ArcRotateCameraInputsManager, _super);
  47345. function ArcRotateCameraInputsManager(camera) {
  47346. return _super.call(this, camera) || this;
  47347. }
  47348. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47349. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47350. return this;
  47351. };
  47352. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47353. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47354. return this;
  47355. };
  47356. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47357. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47358. return this;
  47359. };
  47360. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47361. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47362. return this;
  47363. };
  47364. return ArcRotateCameraInputsManager;
  47365. }(BABYLON.CameraInputsManager));
  47366. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47367. })(BABYLON || (BABYLON = {}));
  47368. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47369. var BABYLON;
  47370. (function (BABYLON) {
  47371. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47372. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47373. });
  47374. /**
  47375. * This represents an orbital type of camera.
  47376. *
  47377. * 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.
  47378. * 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.
  47379. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  47380. */
  47381. var ArcRotateCamera = /** @class */ (function (_super) {
  47382. __extends(ArcRotateCamera, _super);
  47383. /**
  47384. * Instantiates a new ArcRotateCamera in a given scene
  47385. * @param name Defines the name of the camera
  47386. * @param alpha Defines the camera rotation along the logitudinal axis
  47387. * @param beta Defines the camera rotation along the latitudinal axis
  47388. * @param radius Defines the camera distance from its target
  47389. * @param target Defines the camera target
  47390. * @param scene Defines the scene the camera belongs to
  47391. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47392. */
  47393. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47394. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47395. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47396. /**
  47397. * Current inertia value on the longitudinal axis.
  47398. * The bigger this number the longer it will take for the camera to stop.
  47399. */
  47400. _this.inertialAlphaOffset = 0;
  47401. /**
  47402. * Current inertia value on the latitudinal axis.
  47403. * The bigger this number the longer it will take for the camera to stop.
  47404. */
  47405. _this.inertialBetaOffset = 0;
  47406. /**
  47407. * Current inertia value on the radius axis.
  47408. * The bigger this number the longer it will take for the camera to stop.
  47409. */
  47410. _this.inertialRadiusOffset = 0;
  47411. /**
  47412. * Minimum allowed angle on the longitudinal axis.
  47413. * This can help limiting how the Camera is able to move in the scene.
  47414. */
  47415. _this.lowerAlphaLimit = null;
  47416. /**
  47417. * Maximum allowed angle on the longitudinal axis.
  47418. * This can help limiting how the Camera is able to move in the scene.
  47419. */
  47420. _this.upperAlphaLimit = null;
  47421. /**
  47422. * Minimum allowed angle on the latitudinal axis.
  47423. * This can help limiting how the Camera is able to move in the scene.
  47424. */
  47425. _this.lowerBetaLimit = 0.01;
  47426. /**
  47427. * Maximum allowed angle on the latitudinal axis.
  47428. * This can help limiting how the Camera is able to move in the scene.
  47429. */
  47430. _this.upperBetaLimit = Math.PI;
  47431. /**
  47432. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  47433. * This can help limiting how the Camera is able to move in the scene.
  47434. */
  47435. _this.lowerRadiusLimit = null;
  47436. /**
  47437. * Maximum allowed distance of the camera to the target (The camera can not get further).
  47438. * This can help limiting how the Camera is able to move in the scene.
  47439. */
  47440. _this.upperRadiusLimit = null;
  47441. /**
  47442. * Defines the current inertia value used during panning of the camera along the X axis.
  47443. */
  47444. _this.inertialPanningX = 0;
  47445. /**
  47446. * Defines the current inertia value used during panning of the camera along the Y axis.
  47447. */
  47448. _this.inertialPanningY = 0;
  47449. /**
  47450. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  47451. * Basically if your fingers moves away from more than this distance you will be considered
  47452. * in pinch mode.
  47453. */
  47454. _this.pinchToPanMaxDistance = 20;
  47455. /**
  47456. * Defines the maximum distance the camera can pan.
  47457. * This could help keeping the cammera always in your scene.
  47458. */
  47459. _this.panningDistanceLimit = null;
  47460. /**
  47461. * Defines the target of the camera before paning.
  47462. */
  47463. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47464. /**
  47465. * Defines the value of the inertia used during panning.
  47466. * 0 would mean stop inertia and one would mean no decelleration at all.
  47467. */
  47468. _this.panningInertia = 0.9;
  47469. //-- end properties for backward compatibility for inputs
  47470. /**
  47471. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  47472. */
  47473. _this.zoomOnFactor = 1;
  47474. /**
  47475. * Defines a screen offset for the camera position.
  47476. */
  47477. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47478. /**
  47479. * Allows the camera to be completely reversed.
  47480. * If false the camera can not arrive upside down.
  47481. */
  47482. _this.allowUpsideDown = true;
  47483. /** @hidden */
  47484. _this._viewMatrix = new BABYLON.Matrix();
  47485. /**
  47486. * Defines the allowed panning axis.
  47487. */
  47488. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47489. /**
  47490. * Observable triggered when the mesh target has been changed on the camera.
  47491. */
  47492. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47493. /**
  47494. * Defines whether the camera should check collision with the objects oh the scene.
  47495. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  47496. */
  47497. _this.checkCollisions = false;
  47498. /**
  47499. * Defines the collision radius of the camera.
  47500. * This simulates a sphere around the camera.
  47501. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47502. */
  47503. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47504. _this._previousPosition = BABYLON.Vector3.Zero();
  47505. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47506. _this._newPosition = BABYLON.Vector3.Zero();
  47507. _this._computationVector = BABYLON.Vector3.Zero();
  47508. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47509. if (collidedMesh === void 0) { collidedMesh = null; }
  47510. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47511. newPosition.multiplyInPlace(_this._collider._radius);
  47512. }
  47513. if (!collidedMesh) {
  47514. _this._previousPosition.copyFrom(_this.position);
  47515. }
  47516. else {
  47517. _this.setPosition(newPosition);
  47518. if (_this.onCollide) {
  47519. _this.onCollide(collidedMesh);
  47520. }
  47521. }
  47522. // Recompute because of constraints
  47523. var cosa = Math.cos(_this.alpha);
  47524. var sina = Math.sin(_this.alpha);
  47525. var cosb = Math.cos(_this.beta);
  47526. var sinb = Math.sin(_this.beta);
  47527. if (sinb === 0) {
  47528. sinb = 0.0001;
  47529. }
  47530. var target = _this._getTargetPosition();
  47531. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47532. target.addToRef(_this._computationVector, _this._newPosition);
  47533. _this.position.copyFrom(_this._newPosition);
  47534. var up = _this.upVector;
  47535. if (_this.allowUpsideDown && _this.beta < 0) {
  47536. up = up.clone();
  47537. up = up.negate();
  47538. }
  47539. _this._computeViewMatrix(_this.position, target, up);
  47540. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47541. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47542. _this._collisionTriggered = false;
  47543. };
  47544. _this._target = BABYLON.Vector3.Zero();
  47545. if (target) {
  47546. _this.setTarget(target);
  47547. }
  47548. _this.alpha = alpha;
  47549. _this.beta = beta;
  47550. _this.radius = radius;
  47551. _this.getViewMatrix();
  47552. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47553. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47554. return _this;
  47555. }
  47556. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47557. /**
  47558. * Defines the target point of the camera.
  47559. * The camera looks towards it form the radius distance.
  47560. */
  47561. get: function () {
  47562. return this._target;
  47563. },
  47564. set: function (value) {
  47565. this.setTarget(value);
  47566. },
  47567. enumerable: true,
  47568. configurable: true
  47569. });
  47570. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47571. //-- begin properties for backward compatibility for inputs
  47572. /**
  47573. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47574. */
  47575. get: function () {
  47576. var pointers = this.inputs.attached["pointers"];
  47577. if (pointers)
  47578. return pointers.angularSensibilityX;
  47579. return 0;
  47580. },
  47581. set: function (value) {
  47582. var pointers = this.inputs.attached["pointers"];
  47583. if (pointers) {
  47584. pointers.angularSensibilityX = value;
  47585. }
  47586. },
  47587. enumerable: true,
  47588. configurable: true
  47589. });
  47590. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47591. /**
  47592. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47593. */
  47594. get: function () {
  47595. var pointers = this.inputs.attached["pointers"];
  47596. if (pointers)
  47597. return pointers.angularSensibilityY;
  47598. return 0;
  47599. },
  47600. set: function (value) {
  47601. var pointers = this.inputs.attached["pointers"];
  47602. if (pointers) {
  47603. pointers.angularSensibilityY = value;
  47604. }
  47605. },
  47606. enumerable: true,
  47607. configurable: true
  47608. });
  47609. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47610. /**
  47611. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  47612. */
  47613. get: function () {
  47614. var pointers = this.inputs.attached["pointers"];
  47615. if (pointers)
  47616. return pointers.pinchPrecision;
  47617. return 0;
  47618. },
  47619. set: function (value) {
  47620. var pointers = this.inputs.attached["pointers"];
  47621. if (pointers) {
  47622. pointers.pinchPrecision = value;
  47623. }
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47629. /**
  47630. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  47631. * It will be used instead of pinchDeltaPrecision if different from 0.
  47632. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47633. */
  47634. get: function () {
  47635. var pointers = this.inputs.attached["pointers"];
  47636. if (pointers)
  47637. return pointers.pinchDeltaPercentage;
  47638. return 0;
  47639. },
  47640. set: function (value) {
  47641. var pointers = this.inputs.attached["pointers"];
  47642. if (pointers) {
  47643. pointers.pinchDeltaPercentage = value;
  47644. }
  47645. },
  47646. enumerable: true,
  47647. configurable: true
  47648. });
  47649. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47650. /**
  47651. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  47652. */
  47653. get: function () {
  47654. var pointers = this.inputs.attached["pointers"];
  47655. if (pointers)
  47656. return pointers.panningSensibility;
  47657. return 0;
  47658. },
  47659. set: function (value) {
  47660. var pointers = this.inputs.attached["pointers"];
  47661. if (pointers) {
  47662. pointers.panningSensibility = value;
  47663. }
  47664. },
  47665. enumerable: true,
  47666. configurable: true
  47667. });
  47668. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47669. /**
  47670. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  47671. */
  47672. get: function () {
  47673. var keyboard = this.inputs.attached["keyboard"];
  47674. if (keyboard)
  47675. return keyboard.keysUp;
  47676. return [];
  47677. },
  47678. set: function (value) {
  47679. var keyboard = this.inputs.attached["keyboard"];
  47680. if (keyboard)
  47681. keyboard.keysUp = value;
  47682. },
  47683. enumerable: true,
  47684. configurable: true
  47685. });
  47686. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47687. /**
  47688. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  47689. */
  47690. get: function () {
  47691. var keyboard = this.inputs.attached["keyboard"];
  47692. if (keyboard)
  47693. return keyboard.keysDown;
  47694. return [];
  47695. },
  47696. set: function (value) {
  47697. var keyboard = this.inputs.attached["keyboard"];
  47698. if (keyboard)
  47699. keyboard.keysDown = value;
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47705. /**
  47706. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  47707. */
  47708. get: function () {
  47709. var keyboard = this.inputs.attached["keyboard"];
  47710. if (keyboard)
  47711. return keyboard.keysLeft;
  47712. return [];
  47713. },
  47714. set: function (value) {
  47715. var keyboard = this.inputs.attached["keyboard"];
  47716. if (keyboard)
  47717. keyboard.keysLeft = value;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47723. /**
  47724. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  47725. */
  47726. get: function () {
  47727. var keyboard = this.inputs.attached["keyboard"];
  47728. if (keyboard)
  47729. return keyboard.keysRight;
  47730. return [];
  47731. },
  47732. set: function (value) {
  47733. var keyboard = this.inputs.attached["keyboard"];
  47734. if (keyboard)
  47735. keyboard.keysRight = value;
  47736. },
  47737. enumerable: true,
  47738. configurable: true
  47739. });
  47740. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47741. /**
  47742. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47743. */
  47744. get: function () {
  47745. var mousewheel = this.inputs.attached["mousewheel"];
  47746. if (mousewheel)
  47747. return mousewheel.wheelPrecision;
  47748. return 0;
  47749. },
  47750. set: function (value) {
  47751. var mousewheel = this.inputs.attached["mousewheel"];
  47752. if (mousewheel)
  47753. mousewheel.wheelPrecision = value;
  47754. },
  47755. enumerable: true,
  47756. configurable: true
  47757. });
  47758. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47759. /**
  47760. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  47761. * It will be used instead of pinchDeltaPrecision if different from 0.
  47762. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47763. */
  47764. get: function () {
  47765. var mousewheel = this.inputs.attached["mousewheel"];
  47766. if (mousewheel)
  47767. return mousewheel.wheelDeltaPercentage;
  47768. return 0;
  47769. },
  47770. set: function (value) {
  47771. var mousewheel = this.inputs.attached["mousewheel"];
  47772. if (mousewheel)
  47773. mousewheel.wheelDeltaPercentage = value;
  47774. },
  47775. enumerable: true,
  47776. configurable: true
  47777. });
  47778. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47779. /**
  47780. * Gets the bouncing behavior of the camera if it has been enabled.
  47781. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  47782. */
  47783. get: function () {
  47784. return this._bouncingBehavior;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47790. /**
  47791. * Defines if the bouncing behavior of the camera is enabled on the camera.
  47792. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  47793. */
  47794. get: function () {
  47795. return this._bouncingBehavior != null;
  47796. },
  47797. set: function (value) {
  47798. if (value === this.useBouncingBehavior) {
  47799. return;
  47800. }
  47801. if (value) {
  47802. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47803. this.addBehavior(this._bouncingBehavior);
  47804. }
  47805. else if (this._bouncingBehavior) {
  47806. this.removeBehavior(this._bouncingBehavior);
  47807. this._bouncingBehavior = null;
  47808. }
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47814. /**
  47815. * Gets the framing behavior of the camera if it has been enabled.
  47816. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  47817. */
  47818. get: function () {
  47819. return this._framingBehavior;
  47820. },
  47821. enumerable: true,
  47822. configurable: true
  47823. });
  47824. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47825. /**
  47826. * Defines if the framing behavior of the camera is enabled on the camera.
  47827. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  47828. */
  47829. get: function () {
  47830. return this._framingBehavior != null;
  47831. },
  47832. set: function (value) {
  47833. if (value === this.useFramingBehavior) {
  47834. return;
  47835. }
  47836. if (value) {
  47837. this._framingBehavior = new BABYLON.FramingBehavior();
  47838. this.addBehavior(this._framingBehavior);
  47839. }
  47840. else if (this._framingBehavior) {
  47841. this.removeBehavior(this._framingBehavior);
  47842. this._framingBehavior = null;
  47843. }
  47844. },
  47845. enumerable: true,
  47846. configurable: true
  47847. });
  47848. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47849. /**
  47850. * Gets the auto rotation behavior of the camera if it has been enabled.
  47851. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  47852. */
  47853. get: function () {
  47854. return this._autoRotationBehavior;
  47855. },
  47856. enumerable: true,
  47857. configurable: true
  47858. });
  47859. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47860. /**
  47861. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  47862. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  47863. */
  47864. get: function () {
  47865. return this._autoRotationBehavior != null;
  47866. },
  47867. set: function (value) {
  47868. if (value === this.useAutoRotationBehavior) {
  47869. return;
  47870. }
  47871. if (value) {
  47872. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47873. this.addBehavior(this._autoRotationBehavior);
  47874. }
  47875. else if (this._autoRotationBehavior) {
  47876. this.removeBehavior(this._autoRotationBehavior);
  47877. this._autoRotationBehavior = null;
  47878. }
  47879. },
  47880. enumerable: true,
  47881. configurable: true
  47882. });
  47883. // Cache
  47884. /** @hidden */
  47885. ArcRotateCamera.prototype._initCache = function () {
  47886. _super.prototype._initCache.call(this);
  47887. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47888. this._cache.alpha = undefined;
  47889. this._cache.beta = undefined;
  47890. this._cache.radius = undefined;
  47891. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47892. };
  47893. /** @hidden */
  47894. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47895. if (!ignoreParentClass) {
  47896. _super.prototype._updateCache.call(this);
  47897. }
  47898. this._cache._target.copyFrom(this._getTargetPosition());
  47899. this._cache.alpha = this.alpha;
  47900. this._cache.beta = this.beta;
  47901. this._cache.radius = this.radius;
  47902. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47903. };
  47904. ArcRotateCamera.prototype._getTargetPosition = function () {
  47905. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47906. var pos = this._targetHost.getAbsolutePosition();
  47907. if (this._targetBoundingCenter) {
  47908. pos.addToRef(this._targetBoundingCenter, this._target);
  47909. }
  47910. else {
  47911. this._target.copyFrom(pos);
  47912. }
  47913. }
  47914. var lockedTargetPosition = this._getLockedTargetPosition();
  47915. if (lockedTargetPosition) {
  47916. return lockedTargetPosition;
  47917. }
  47918. return this._target;
  47919. };
  47920. /**
  47921. * Stores the current state of the camera (alpha, beta, radius and target)
  47922. * @returns the camera itself
  47923. */
  47924. ArcRotateCamera.prototype.storeState = function () {
  47925. this._storedAlpha = this.alpha;
  47926. this._storedBeta = this.beta;
  47927. this._storedRadius = this.radius;
  47928. this._storedTarget = this._getTargetPosition().clone();
  47929. return _super.prototype.storeState.call(this);
  47930. };
  47931. /**
  47932. * @hidden
  47933. * Restored camera state. You must call storeState() first
  47934. */
  47935. ArcRotateCamera.prototype._restoreStateValues = function () {
  47936. if (!_super.prototype._restoreStateValues.call(this)) {
  47937. return false;
  47938. }
  47939. this.alpha = this._storedAlpha;
  47940. this.beta = this._storedBeta;
  47941. this.radius = this._storedRadius;
  47942. this.setTarget(this._storedTarget.clone());
  47943. this.inertialAlphaOffset = 0;
  47944. this.inertialBetaOffset = 0;
  47945. this.inertialRadiusOffset = 0;
  47946. this.inertialPanningX = 0;
  47947. this.inertialPanningY = 0;
  47948. return true;
  47949. };
  47950. // Synchronized
  47951. /** @hidden */
  47952. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47953. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47954. return false;
  47955. return this._cache._target.equals(this._getTargetPosition())
  47956. && this._cache.alpha === this.alpha
  47957. && this._cache.beta === this.beta
  47958. && this._cache.radius === this.radius
  47959. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47960. };
  47961. /**
  47962. * Attached controls to the current camera.
  47963. * @param element Defines the element the controls should be listened from
  47964. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47965. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  47966. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  47967. */
  47968. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47969. var _this = this;
  47970. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47971. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47972. this._useCtrlForPanning = useCtrlForPanning;
  47973. this._panningMouseButton = panningMouseButton;
  47974. this.inputs.attachElement(element, noPreventDefault);
  47975. this._reset = function () {
  47976. _this.inertialAlphaOffset = 0;
  47977. _this.inertialBetaOffset = 0;
  47978. _this.inertialRadiusOffset = 0;
  47979. _this.inertialPanningX = 0;
  47980. _this.inertialPanningY = 0;
  47981. };
  47982. };
  47983. /**
  47984. * Detach the current controls from the camera.
  47985. * The camera will stop reacting to inputs.
  47986. * @param element Defines the element to stop listening the inputs from
  47987. */
  47988. ArcRotateCamera.prototype.detachControl = function (element) {
  47989. this.inputs.detachElement(element);
  47990. if (this._reset) {
  47991. this._reset();
  47992. }
  47993. };
  47994. /** @hidden */
  47995. ArcRotateCamera.prototype._checkInputs = function () {
  47996. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47997. if (this._collisionTriggered) {
  47998. return;
  47999. }
  48000. this.inputs.checkInputs();
  48001. // Inertia
  48002. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48003. var inertialAlphaOffset = this.inertialAlphaOffset;
  48004. if (this.beta <= 0)
  48005. inertialAlphaOffset *= -1;
  48006. if (this.getScene().useRightHandedSystem)
  48007. inertialAlphaOffset *= -1;
  48008. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48009. inertialAlphaOffset *= -1;
  48010. this.alpha += inertialAlphaOffset;
  48011. this.beta += this.inertialBetaOffset;
  48012. this.radius -= this.inertialRadiusOffset;
  48013. this.inertialAlphaOffset *= this.inertia;
  48014. this.inertialBetaOffset *= this.inertia;
  48015. this.inertialRadiusOffset *= this.inertia;
  48016. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48017. this.inertialAlphaOffset = 0;
  48018. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48019. this.inertialBetaOffset = 0;
  48020. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48021. this.inertialRadiusOffset = 0;
  48022. }
  48023. // Panning inertia
  48024. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48025. if (!this._localDirection) {
  48026. this._localDirection = BABYLON.Vector3.Zero();
  48027. this._transformedDirection = BABYLON.Vector3.Zero();
  48028. }
  48029. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48030. this._localDirection.multiplyInPlace(this.panningAxis);
  48031. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48032. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48033. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48034. if (!this.panningAxis.y) {
  48035. this._transformedDirection.y = 0;
  48036. }
  48037. if (!this._targetHost) {
  48038. if (this.panningDistanceLimit) {
  48039. this._transformedDirection.addInPlace(this._target);
  48040. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48041. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48042. this._target.copyFrom(this._transformedDirection);
  48043. }
  48044. }
  48045. else {
  48046. this._target.addInPlace(this._transformedDirection);
  48047. }
  48048. }
  48049. this.inertialPanningX *= this.panningInertia;
  48050. this.inertialPanningY *= this.panningInertia;
  48051. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48052. this.inertialPanningX = 0;
  48053. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48054. this.inertialPanningY = 0;
  48055. }
  48056. // Limits
  48057. this._checkLimits();
  48058. _super.prototype._checkInputs.call(this);
  48059. };
  48060. ArcRotateCamera.prototype._checkLimits = function () {
  48061. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48062. if (this.allowUpsideDown && this.beta > Math.PI) {
  48063. this.beta = this.beta - (2 * Math.PI);
  48064. }
  48065. }
  48066. else {
  48067. if (this.beta < this.lowerBetaLimit) {
  48068. this.beta = this.lowerBetaLimit;
  48069. }
  48070. }
  48071. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48072. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48073. this.beta = this.beta + (2 * Math.PI);
  48074. }
  48075. }
  48076. else {
  48077. if (this.beta > this.upperBetaLimit) {
  48078. this.beta = this.upperBetaLimit;
  48079. }
  48080. }
  48081. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48082. this.alpha = this.lowerAlphaLimit;
  48083. }
  48084. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48085. this.alpha = this.upperAlphaLimit;
  48086. }
  48087. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48088. this.radius = this.lowerRadiusLimit;
  48089. }
  48090. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48091. this.radius = this.upperRadiusLimit;
  48092. }
  48093. };
  48094. /**
  48095. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48096. */
  48097. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48098. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48099. this.radius = this._computationVector.length();
  48100. if (this.radius === 0) {
  48101. this.radius = 0.0001; // Just to avoid division by zero
  48102. }
  48103. // Alpha
  48104. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48105. if (this._computationVector.z < 0) {
  48106. this.alpha = 2 * Math.PI - this.alpha;
  48107. }
  48108. // Beta
  48109. this.beta = Math.acos(this._computationVector.y / this.radius);
  48110. this._checkLimits();
  48111. };
  48112. /**
  48113. * Use a position to define the current camera related information like aplha, beta and radius
  48114. * @param position Defines the position to set the camera at
  48115. */
  48116. ArcRotateCamera.prototype.setPosition = function (position) {
  48117. if (this.position.equals(position)) {
  48118. return;
  48119. }
  48120. this.position.copyFrom(position);
  48121. this.rebuildAnglesAndRadius();
  48122. };
  48123. /**
  48124. * Defines the target the camera should look at.
  48125. * This will automatically adapt alpha beta and radius to fit within the new target.
  48126. * @param target Defines the new target as a Vector or a mesh
  48127. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48128. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48129. */
  48130. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48131. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48132. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48133. if (target.getBoundingInfo) {
  48134. if (toBoundingCenter) {
  48135. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48136. }
  48137. else {
  48138. this._targetBoundingCenter = null;
  48139. }
  48140. this._targetHost = target;
  48141. this._target = this._getTargetPosition();
  48142. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48143. }
  48144. else {
  48145. var newTarget = target;
  48146. var currentTarget = this._getTargetPosition();
  48147. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48148. return;
  48149. }
  48150. this._targetHost = null;
  48151. this._target = newTarget;
  48152. this._targetBoundingCenter = null;
  48153. this.onMeshTargetChangedObservable.notifyObservers(null);
  48154. }
  48155. this.rebuildAnglesAndRadius();
  48156. };
  48157. /** @hidden */
  48158. ArcRotateCamera.prototype._getViewMatrix = function () {
  48159. // Compute
  48160. var cosa = Math.cos(this.alpha);
  48161. var sina = Math.sin(this.alpha);
  48162. var cosb = Math.cos(this.beta);
  48163. var sinb = Math.sin(this.beta);
  48164. if (sinb === 0) {
  48165. sinb = 0.0001;
  48166. }
  48167. var target = this._getTargetPosition();
  48168. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48169. target.addToRef(this._computationVector, this._newPosition);
  48170. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48171. if (!this._collider) {
  48172. this._collider = new BABYLON.Collider();
  48173. }
  48174. this._collider._radius = this.collisionRadius;
  48175. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48176. this._collisionTriggered = true;
  48177. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48178. }
  48179. else {
  48180. this.position.copyFrom(this._newPosition);
  48181. var up = this.upVector;
  48182. if (this.allowUpsideDown && sinb < 0) {
  48183. up = up.clone();
  48184. up = up.negate();
  48185. }
  48186. this._computeViewMatrix(this.position, target, up);
  48187. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48188. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48189. }
  48190. this._currentTarget = target;
  48191. return this._viewMatrix;
  48192. };
  48193. /**
  48194. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48195. * @param meshes Defines the mesh to zoom on
  48196. * @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)
  48197. */
  48198. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48199. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48200. meshes = meshes || this.getScene().meshes;
  48201. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48202. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48203. this.radius = distance * this.zoomOnFactor;
  48204. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48205. };
  48206. /**
  48207. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48208. * The target will be changed but the radius
  48209. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48210. * @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)
  48211. */
  48212. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48213. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48214. var meshesOrMinMaxVector;
  48215. var distance;
  48216. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48217. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48218. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48219. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48220. }
  48221. else { //minMaxVector and distance
  48222. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48223. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48224. distance = minMaxVectorAndDistance.distance;
  48225. }
  48226. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48227. if (!doNotUpdateMaxZ) {
  48228. this.maxZ = distance * 2;
  48229. }
  48230. };
  48231. /**
  48232. * @override
  48233. * Override Camera.createRigCamera
  48234. */
  48235. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48236. var alphaShift = 0;
  48237. switch (this.cameraRigMode) {
  48238. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48239. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48240. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48241. case BABYLON.Camera.RIG_MODE_VR:
  48242. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48243. break;
  48244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48245. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48246. break;
  48247. }
  48248. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48249. rigCam._cameraRigParams = {};
  48250. return rigCam;
  48251. };
  48252. /**
  48253. * @hidden
  48254. * @override
  48255. * Override Camera._updateRigCameras
  48256. */
  48257. ArcRotateCamera.prototype._updateRigCameras = function () {
  48258. var camLeft = this._rigCameras[0];
  48259. var camRight = this._rigCameras[1];
  48260. camLeft.beta = camRight.beta = this.beta;
  48261. camLeft.radius = camRight.radius = this.radius;
  48262. switch (this.cameraRigMode) {
  48263. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48264. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48265. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48266. case BABYLON.Camera.RIG_MODE_VR:
  48267. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48268. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48269. break;
  48270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48271. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48272. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48273. break;
  48274. }
  48275. _super.prototype._updateRigCameras.call(this);
  48276. };
  48277. /**
  48278. * Destroy the camera and release the current resources hold by it.
  48279. */
  48280. ArcRotateCamera.prototype.dispose = function () {
  48281. this.inputs.clear();
  48282. _super.prototype.dispose.call(this);
  48283. };
  48284. /**
  48285. * Gets the current object class name.
  48286. * @return the class name
  48287. */
  48288. ArcRotateCamera.prototype.getClassName = function () {
  48289. return "ArcRotateCamera";
  48290. };
  48291. __decorate([
  48292. BABYLON.serialize()
  48293. ], ArcRotateCamera.prototype, "alpha", void 0);
  48294. __decorate([
  48295. BABYLON.serialize()
  48296. ], ArcRotateCamera.prototype, "beta", void 0);
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCamera.prototype, "radius", void 0);
  48300. __decorate([
  48301. BABYLON.serializeAsVector3("target")
  48302. ], ArcRotateCamera.prototype, "_target", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48330. __decorate([
  48331. BABYLON.serialize()
  48332. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48333. __decorate([
  48334. BABYLON.serialize()
  48335. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48336. __decorate([
  48337. BABYLON.serialize()
  48338. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48339. __decorate([
  48340. BABYLON.serialize()
  48341. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48342. __decorate([
  48343. BABYLON.serializeAsVector3()
  48344. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48345. __decorate([
  48346. BABYLON.serialize()
  48347. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48348. __decorate([
  48349. BABYLON.serialize()
  48350. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48351. __decorate([
  48352. BABYLON.serialize()
  48353. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  48354. __decorate([
  48355. BABYLON.serialize()
  48356. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48357. return ArcRotateCamera;
  48358. }(BABYLON.TargetCamera));
  48359. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48360. })(BABYLON || (BABYLON = {}));
  48361. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48365. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48366. });
  48367. /**
  48368. * The HemisphericLight simulates the ambient environment light,
  48369. * so the passed direction is the light reflection direction, not the incoming direction.
  48370. */
  48371. var HemisphericLight = /** @class */ (function (_super) {
  48372. __extends(HemisphericLight, _super);
  48373. /**
  48374. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48375. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48376. * The HemisphericLight can't cast shadows.
  48377. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48378. * @param name The friendly name of the light
  48379. * @param direction The direction of the light reflection
  48380. * @param scene The scene the light belongs to
  48381. */
  48382. function HemisphericLight(name, direction, scene) {
  48383. var _this = _super.call(this, name, scene) || this;
  48384. /**
  48385. * The groundColor is the light in the opposite direction to the one specified during creation.
  48386. * 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.
  48387. */
  48388. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48389. _this.direction = direction || BABYLON.Vector3.Up();
  48390. return _this;
  48391. }
  48392. HemisphericLight.prototype._buildUniformLayout = function () {
  48393. this._uniformBuffer.addUniform("vLightData", 4);
  48394. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48395. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48396. this._uniformBuffer.addUniform("vLightGround", 3);
  48397. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48398. this._uniformBuffer.addUniform("depthValues", 2);
  48399. this._uniformBuffer.create();
  48400. };
  48401. /**
  48402. * Returns the string "HemisphericLight".
  48403. * @return The class name
  48404. */
  48405. HemisphericLight.prototype.getClassName = function () {
  48406. return "HemisphericLight";
  48407. };
  48408. /**
  48409. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48410. * Returns the updated direction.
  48411. * @param target The target the direction should point to
  48412. * @return The computed direction
  48413. */
  48414. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48415. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48416. return this.direction;
  48417. };
  48418. /**
  48419. * Returns the shadow generator associated to the light.
  48420. * @returns Always null for hemispheric lights because it does not support shadows.
  48421. */
  48422. HemisphericLight.prototype.getShadowGenerator = function () {
  48423. return null;
  48424. };
  48425. /**
  48426. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48427. * @param effect The effect to update
  48428. * @param lightIndex The index of the light in the effect to update
  48429. * @returns The hemispheric light
  48430. */
  48431. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48432. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48433. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48434. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48435. return this;
  48436. };
  48437. /**
  48438. * Computes the world matrix of the node
  48439. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48440. * @param useWasUpdatedFlag defines a reserved property
  48441. * @returns the world matrix
  48442. */
  48443. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48444. if (!this._worldMatrix) {
  48445. this._worldMatrix = BABYLON.Matrix.Identity();
  48446. }
  48447. return this._worldMatrix;
  48448. };
  48449. /**
  48450. * Returns the integer 3.
  48451. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48452. */
  48453. HemisphericLight.prototype.getTypeID = function () {
  48454. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48455. };
  48456. /**
  48457. * Prepares the list of defines specific to the light type.
  48458. * @param defines the list of defines
  48459. * @param lightIndex defines the index of the light for the effect
  48460. */
  48461. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48462. defines["HEMILIGHT" + lightIndex] = true;
  48463. };
  48464. __decorate([
  48465. BABYLON.serializeAsColor3()
  48466. ], HemisphericLight.prototype, "groundColor", void 0);
  48467. __decorate([
  48468. BABYLON.serializeAsVector3()
  48469. ], HemisphericLight.prototype, "direction", void 0);
  48470. return HemisphericLight;
  48471. }(BABYLON.Light));
  48472. BABYLON.HemisphericLight = HemisphericLight;
  48473. })(BABYLON || (BABYLON = {}));
  48474. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48475. var BABYLON;
  48476. (function (BABYLON) {
  48477. /**
  48478. * Base implementation IShadowLight
  48479. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48480. */
  48481. var ShadowLight = /** @class */ (function (_super) {
  48482. __extends(ShadowLight, _super);
  48483. function ShadowLight() {
  48484. var _this = _super !== null && _super.apply(this, arguments) || this;
  48485. _this._needProjectionMatrixCompute = true;
  48486. return _this;
  48487. }
  48488. ShadowLight.prototype._setPosition = function (value) {
  48489. this._position = value;
  48490. };
  48491. Object.defineProperty(ShadowLight.prototype, "position", {
  48492. /**
  48493. * Sets the position the shadow will be casted from. Also use as the light position for both
  48494. * point and spot lights.
  48495. */
  48496. get: function () {
  48497. return this._position;
  48498. },
  48499. /**
  48500. * Sets the position the shadow will be casted from. Also use as the light position for both
  48501. * point and spot lights.
  48502. */
  48503. set: function (value) {
  48504. this._setPosition(value);
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. ShadowLight.prototype._setDirection = function (value) {
  48510. this._direction = value;
  48511. };
  48512. Object.defineProperty(ShadowLight.prototype, "direction", {
  48513. /**
  48514. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48515. * Also use as the light direction on spot and directional lights.
  48516. */
  48517. get: function () {
  48518. return this._direction;
  48519. },
  48520. /**
  48521. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48522. * Also use as the light direction on spot and directional lights.
  48523. */
  48524. set: function (value) {
  48525. this._setDirection(value);
  48526. },
  48527. enumerable: true,
  48528. configurable: true
  48529. });
  48530. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48531. /**
  48532. * Gets the shadow projection clipping minimum z value.
  48533. */
  48534. get: function () {
  48535. return this._shadowMinZ;
  48536. },
  48537. /**
  48538. * Sets the shadow projection clipping minimum z value.
  48539. */
  48540. set: function (value) {
  48541. this._shadowMinZ = value;
  48542. this.forceProjectionMatrixCompute();
  48543. },
  48544. enumerable: true,
  48545. configurable: true
  48546. });
  48547. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48548. /**
  48549. * Sets the shadow projection clipping maximum z value.
  48550. */
  48551. get: function () {
  48552. return this._shadowMaxZ;
  48553. },
  48554. /**
  48555. * Gets the shadow projection clipping maximum z value.
  48556. */
  48557. set: function (value) {
  48558. this._shadowMaxZ = value;
  48559. this.forceProjectionMatrixCompute();
  48560. },
  48561. enumerable: true,
  48562. configurable: true
  48563. });
  48564. /**
  48565. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48566. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48567. */
  48568. ShadowLight.prototype.computeTransformedInformation = function () {
  48569. if (this.parent && this.parent.getWorldMatrix) {
  48570. if (!this.transformedPosition) {
  48571. this.transformedPosition = BABYLON.Vector3.Zero();
  48572. }
  48573. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48574. // In case the direction is present.
  48575. if (this.direction) {
  48576. if (!this.transformedDirection) {
  48577. this.transformedDirection = BABYLON.Vector3.Zero();
  48578. }
  48579. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48580. }
  48581. return true;
  48582. }
  48583. return false;
  48584. };
  48585. /**
  48586. * Return the depth scale used for the shadow map.
  48587. * @returns the depth scale.
  48588. */
  48589. ShadowLight.prototype.getDepthScale = function () {
  48590. return 50.0;
  48591. };
  48592. /**
  48593. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48594. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48595. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48596. */
  48597. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48598. return this.transformedDirection ? this.transformedDirection : this.direction;
  48599. };
  48600. /**
  48601. * Returns the ShadowLight absolute position in the World.
  48602. * @returns the position vector in world space
  48603. */
  48604. ShadowLight.prototype.getAbsolutePosition = function () {
  48605. return this.transformedPosition ? this.transformedPosition : this.position;
  48606. };
  48607. /**
  48608. * Sets the ShadowLight direction toward the passed target.
  48609. * @param target The point tot target in local space
  48610. * @returns the updated ShadowLight direction
  48611. */
  48612. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48613. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48614. return this.direction;
  48615. };
  48616. /**
  48617. * Returns the light rotation in euler definition.
  48618. * @returns the x y z rotation in local space.
  48619. */
  48620. ShadowLight.prototype.getRotation = function () {
  48621. this.direction.normalize();
  48622. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48623. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48624. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48625. };
  48626. /**
  48627. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48628. * @returns true if a cube texture needs to be use
  48629. */
  48630. ShadowLight.prototype.needCube = function () {
  48631. return false;
  48632. };
  48633. /**
  48634. * Detects if the projection matrix requires to be recomputed this frame.
  48635. * @returns true if it requires to be recomputed otherwise, false.
  48636. */
  48637. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48638. return this._needProjectionMatrixCompute;
  48639. };
  48640. /**
  48641. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48642. */
  48643. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48644. this._needProjectionMatrixCompute = true;
  48645. };
  48646. /** @hidden */
  48647. ShadowLight.prototype._initCache = function () {
  48648. _super.prototype._initCache.call(this);
  48649. this._cache.position = BABYLON.Vector3.Zero();
  48650. };
  48651. /** @hidden */
  48652. ShadowLight.prototype._isSynchronized = function () {
  48653. if (!this._cache.position.equals(this.position))
  48654. return false;
  48655. return true;
  48656. };
  48657. /**
  48658. * Computes the world matrix of the node
  48659. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48660. * @returns the world matrix
  48661. */
  48662. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48663. if (!force && this.isSynchronized()) {
  48664. this._currentRenderId = this.getScene().getRenderId();
  48665. return this._worldMatrix;
  48666. }
  48667. this._updateCache();
  48668. this._cache.position.copyFrom(this.position);
  48669. if (!this._worldMatrix) {
  48670. this._worldMatrix = BABYLON.Matrix.Identity();
  48671. }
  48672. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48673. if (this.parent && this.parent.getWorldMatrix) {
  48674. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48675. this._markSyncedWithParent();
  48676. }
  48677. // Cache the determinant
  48678. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48679. return this._worldMatrix;
  48680. };
  48681. /**
  48682. * Gets the minZ used for shadow according to both the scene and the light.
  48683. * @param activeCamera The camera we are returning the min for
  48684. * @returns the depth min z
  48685. */
  48686. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48687. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48688. };
  48689. /**
  48690. * Gets the maxZ used for shadow according to both the scene and the light.
  48691. * @param activeCamera The camera we are returning the max for
  48692. * @returns the depth max z
  48693. */
  48694. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48695. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48696. };
  48697. /**
  48698. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48699. * @param matrix The materix to updated with the projection information
  48700. * @param viewMatrix The transform matrix of the light
  48701. * @param renderList The list of mesh to render in the map
  48702. * @returns The current light
  48703. */
  48704. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48705. if (this.customProjectionMatrixBuilder) {
  48706. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48707. }
  48708. else {
  48709. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48710. }
  48711. return this;
  48712. };
  48713. __decorate([
  48714. BABYLON.serializeAsVector3()
  48715. ], ShadowLight.prototype, "position", null);
  48716. __decorate([
  48717. BABYLON.serializeAsVector3()
  48718. ], ShadowLight.prototype, "direction", null);
  48719. __decorate([
  48720. BABYLON.serialize()
  48721. ], ShadowLight.prototype, "shadowMinZ", null);
  48722. __decorate([
  48723. BABYLON.serialize()
  48724. ], ShadowLight.prototype, "shadowMaxZ", null);
  48725. return ShadowLight;
  48726. }(BABYLON.Light));
  48727. BABYLON.ShadowLight = ShadowLight;
  48728. })(BABYLON || (BABYLON = {}));
  48729. //# sourceMappingURL=babylon.shadowLight.js.map
  48730. var BABYLON;
  48731. (function (BABYLON) {
  48732. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48733. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48734. });
  48735. /**
  48736. * A point light is a light defined by an unique point in world space.
  48737. * The light is emitted in every direction from this point.
  48738. * A good example of a point light is a standard light bulb.
  48739. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48740. */
  48741. var PointLight = /** @class */ (function (_super) {
  48742. __extends(PointLight, _super);
  48743. /**
  48744. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48745. * A PointLight emits the light in every direction.
  48746. * It can cast shadows.
  48747. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48748. * ```javascript
  48749. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48750. * ```
  48751. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48752. * @param name The light friendly name
  48753. * @param position The position of the point light in the scene
  48754. * @param scene The scene the lights belongs to
  48755. */
  48756. function PointLight(name, position, scene) {
  48757. var _this = _super.call(this, name, scene) || this;
  48758. _this._shadowAngle = Math.PI / 2;
  48759. _this.position = position;
  48760. return _this;
  48761. }
  48762. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48763. /**
  48764. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48765. * This specifies what angle the shadow will use to be created.
  48766. *
  48767. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48768. */
  48769. get: function () {
  48770. return this._shadowAngle;
  48771. },
  48772. /**
  48773. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48774. * This specifies what angle the shadow will use to be created.
  48775. *
  48776. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48777. */
  48778. set: function (value) {
  48779. this._shadowAngle = value;
  48780. this.forceProjectionMatrixCompute();
  48781. },
  48782. enumerable: true,
  48783. configurable: true
  48784. });
  48785. Object.defineProperty(PointLight.prototype, "direction", {
  48786. /**
  48787. * Gets the direction if it has been set.
  48788. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48789. */
  48790. get: function () {
  48791. return this._direction;
  48792. },
  48793. /**
  48794. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48795. */
  48796. set: function (value) {
  48797. var previousNeedCube = this.needCube();
  48798. this._direction = value;
  48799. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48800. this._shadowGenerator.recreateShadowMap();
  48801. }
  48802. },
  48803. enumerable: true,
  48804. configurable: true
  48805. });
  48806. /**
  48807. * Returns the string "PointLight"
  48808. * @returns the class name
  48809. */
  48810. PointLight.prototype.getClassName = function () {
  48811. return "PointLight";
  48812. };
  48813. /**
  48814. * Returns the integer 0.
  48815. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48816. */
  48817. PointLight.prototype.getTypeID = function () {
  48818. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48819. };
  48820. /**
  48821. * Specifies wether or not the shadowmap should be a cube texture.
  48822. * @returns true if the shadowmap needs to be a cube texture.
  48823. */
  48824. PointLight.prototype.needCube = function () {
  48825. return !this.direction;
  48826. };
  48827. /**
  48828. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48829. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48830. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48831. */
  48832. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48833. if (this.direction) {
  48834. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48835. }
  48836. else {
  48837. switch (faceIndex) {
  48838. case 0:
  48839. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48840. case 1:
  48841. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48842. case 2:
  48843. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48844. case 3:
  48845. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48846. case 4:
  48847. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48848. case 5:
  48849. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48850. }
  48851. }
  48852. return BABYLON.Vector3.Zero();
  48853. };
  48854. /**
  48855. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48856. * - fov = PI / 2
  48857. * - aspect ratio : 1.0
  48858. * - z-near and far equal to the active camera minZ and maxZ.
  48859. * Returns the PointLight.
  48860. */
  48861. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48862. var activeCamera = this.getScene().activeCamera;
  48863. if (!activeCamera) {
  48864. return;
  48865. }
  48866. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48867. };
  48868. PointLight.prototype._buildUniformLayout = function () {
  48869. this._uniformBuffer.addUniform("vLightData", 4);
  48870. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48871. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48872. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48873. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48874. this._uniformBuffer.addUniform("depthValues", 2);
  48875. this._uniformBuffer.create();
  48876. };
  48877. /**
  48878. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48879. * @param effect The effect to update
  48880. * @param lightIndex The index of the light in the effect to update
  48881. * @returns The point light
  48882. */
  48883. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48884. if (this.computeTransformedInformation()) {
  48885. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48886. }
  48887. else {
  48888. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48889. }
  48890. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48891. return this;
  48892. };
  48893. /**
  48894. * Prepares the list of defines specific to the light type.
  48895. * @param defines the list of defines
  48896. * @param lightIndex defines the index of the light for the effect
  48897. */
  48898. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48899. defines["POINTLIGHT" + lightIndex] = true;
  48900. };
  48901. __decorate([
  48902. BABYLON.serialize()
  48903. ], PointLight.prototype, "shadowAngle", null);
  48904. return PointLight;
  48905. }(BABYLON.ShadowLight));
  48906. BABYLON.PointLight = PointLight;
  48907. })(BABYLON || (BABYLON = {}));
  48908. //# sourceMappingURL=babylon.pointLight.js.map
  48909. var BABYLON;
  48910. (function (BABYLON) {
  48911. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48912. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48913. });
  48914. /**
  48915. * A directional light is defined by a direction (what a surprise!).
  48916. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48917. * 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.
  48918. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48919. */
  48920. var DirectionalLight = /** @class */ (function (_super) {
  48921. __extends(DirectionalLight, _super);
  48922. /**
  48923. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48924. * The directional light is emitted from everywhere in the given direction.
  48925. * It can cast shawdows.
  48926. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48927. * @param name The friendly name of the light
  48928. * @param direction The direction of the light
  48929. * @param scene The scene the light belongs to
  48930. */
  48931. function DirectionalLight(name, direction, scene) {
  48932. var _this = _super.call(this, name, scene) || this;
  48933. _this._shadowFrustumSize = 0;
  48934. _this._shadowOrthoScale = 0.1;
  48935. /**
  48936. * Automatically compute the projection matrix to best fit (including all the casters)
  48937. * on each frame.
  48938. */
  48939. _this.autoUpdateExtends = true;
  48940. // Cache
  48941. _this._orthoLeft = Number.MAX_VALUE;
  48942. _this._orthoRight = Number.MIN_VALUE;
  48943. _this._orthoTop = Number.MIN_VALUE;
  48944. _this._orthoBottom = Number.MAX_VALUE;
  48945. _this.position = direction.scale(-1.0);
  48946. _this.direction = direction;
  48947. return _this;
  48948. }
  48949. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48950. /**
  48951. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48952. */
  48953. get: function () {
  48954. return this._shadowFrustumSize;
  48955. },
  48956. /**
  48957. * Specifies a fix frustum size for the shadow generation.
  48958. */
  48959. set: function (value) {
  48960. this._shadowFrustumSize = value;
  48961. this.forceProjectionMatrixCompute();
  48962. },
  48963. enumerable: true,
  48964. configurable: true
  48965. });
  48966. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48967. /**
  48968. * Gets the shadow projection scale against the optimal computed one.
  48969. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48970. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48971. */
  48972. get: function () {
  48973. return this._shadowOrthoScale;
  48974. },
  48975. /**
  48976. * Sets the shadow projection scale against the optimal computed one.
  48977. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48978. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48979. */
  48980. set: function (value) {
  48981. this._shadowOrthoScale = value;
  48982. this.forceProjectionMatrixCompute();
  48983. },
  48984. enumerable: true,
  48985. configurable: true
  48986. });
  48987. /**
  48988. * Returns the string "DirectionalLight".
  48989. * @return The class name
  48990. */
  48991. DirectionalLight.prototype.getClassName = function () {
  48992. return "DirectionalLight";
  48993. };
  48994. /**
  48995. * Returns the integer 1.
  48996. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48997. */
  48998. DirectionalLight.prototype.getTypeID = function () {
  48999. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49000. };
  49001. /**
  49002. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49003. * Returns the DirectionalLight Shadow projection matrix.
  49004. */
  49005. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49006. if (this.shadowFrustumSize > 0) {
  49007. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49008. }
  49009. else {
  49010. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49011. }
  49012. };
  49013. /**
  49014. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49015. * Returns the DirectionalLight Shadow projection matrix.
  49016. */
  49017. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49018. var activeCamera = this.getScene().activeCamera;
  49019. if (!activeCamera) {
  49020. return;
  49021. }
  49022. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49023. };
  49024. /**
  49025. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49026. * Returns the DirectionalLight Shadow projection matrix.
  49027. */
  49028. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49029. var activeCamera = this.getScene().activeCamera;
  49030. if (!activeCamera) {
  49031. return;
  49032. }
  49033. // Check extends
  49034. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49035. var tempVector3 = BABYLON.Vector3.Zero();
  49036. this._orthoLeft = Number.MAX_VALUE;
  49037. this._orthoRight = Number.MIN_VALUE;
  49038. this._orthoTop = Number.MIN_VALUE;
  49039. this._orthoBottom = Number.MAX_VALUE;
  49040. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49041. var mesh = renderList[meshIndex];
  49042. if (!mesh) {
  49043. continue;
  49044. }
  49045. var boundingInfo = mesh.getBoundingInfo();
  49046. var boundingBox = boundingInfo.boundingBox;
  49047. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49048. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49049. if (tempVector3.x < this._orthoLeft)
  49050. this._orthoLeft = tempVector3.x;
  49051. if (tempVector3.y < this._orthoBottom)
  49052. this._orthoBottom = tempVector3.y;
  49053. if (tempVector3.x > this._orthoRight)
  49054. this._orthoRight = tempVector3.x;
  49055. if (tempVector3.y > this._orthoTop)
  49056. this._orthoTop = tempVector3.y;
  49057. }
  49058. }
  49059. }
  49060. var xOffset = this._orthoRight - this._orthoLeft;
  49061. var yOffset = this._orthoTop - this._orthoBottom;
  49062. 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);
  49063. };
  49064. DirectionalLight.prototype._buildUniformLayout = function () {
  49065. this._uniformBuffer.addUniform("vLightData", 4);
  49066. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49067. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49068. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49069. this._uniformBuffer.addUniform("depthValues", 2);
  49070. this._uniformBuffer.create();
  49071. };
  49072. /**
  49073. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49074. * @param effect The effect to update
  49075. * @param lightIndex The index of the light in the effect to update
  49076. * @returns The directional light
  49077. */
  49078. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49079. if (this.computeTransformedInformation()) {
  49080. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49081. return this;
  49082. }
  49083. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49084. return this;
  49085. };
  49086. /**
  49087. * Gets the minZ used for shadow according to both the scene and the light.
  49088. *
  49089. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49090. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49091. * @param activeCamera The camera we are returning the min for
  49092. * @returns the depth min z
  49093. */
  49094. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49095. return 1;
  49096. };
  49097. /**
  49098. * Gets the maxZ used for shadow according to both the scene and the light.
  49099. *
  49100. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49101. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49102. * @param activeCamera The camera we are returning the max for
  49103. * @returns the depth max z
  49104. */
  49105. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49106. return 1;
  49107. };
  49108. /**
  49109. * Prepares the list of defines specific to the light type.
  49110. * @param defines the list of defines
  49111. * @param lightIndex defines the index of the light for the effect
  49112. */
  49113. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49114. defines["DIRLIGHT" + lightIndex] = true;
  49115. };
  49116. __decorate([
  49117. BABYLON.serialize()
  49118. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49119. __decorate([
  49120. BABYLON.serialize()
  49121. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49122. __decorate([
  49123. BABYLON.serialize()
  49124. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49125. return DirectionalLight;
  49126. }(BABYLON.ShadowLight));
  49127. BABYLON.DirectionalLight = DirectionalLight;
  49128. })(BABYLON || (BABYLON = {}));
  49129. //# sourceMappingURL=babylon.directionalLight.js.map
  49130. var BABYLON;
  49131. (function (BABYLON) {
  49132. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49133. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49134. });
  49135. /**
  49136. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49137. * These values define a cone of light starting from the position, emitting toward the direction.
  49138. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49139. * and the exponent defines the speed of the decay of the light with distance (reach).
  49140. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49141. */
  49142. var SpotLight = /** @class */ (function (_super) {
  49143. __extends(SpotLight, _super);
  49144. /**
  49145. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49146. * It can cast shadows.
  49147. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49148. * @param name The light friendly name
  49149. * @param position The position of the spot light in the scene
  49150. * @param direction The direction of the light in the scene
  49151. * @param angle The cone angle of the light in Radians
  49152. * @param exponent The light decay speed with the distance from the emission spot
  49153. * @param scene The scene the lights belongs to
  49154. */
  49155. function SpotLight(name, position, direction, angle, exponent, scene) {
  49156. var _this = _super.call(this, name, scene) || this;
  49157. _this._innerAngle = 0;
  49158. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49159. _this._projectionTextureLightNear = 1e-6;
  49160. _this._projectionTextureLightFar = 1000.0;
  49161. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49162. _this._projectionTextureViewLightDirty = true;
  49163. _this._projectionTextureProjectionLightDirty = true;
  49164. _this._projectionTextureDirty = true;
  49165. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49166. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49167. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49168. _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);
  49169. _this.position = position;
  49170. _this.direction = direction;
  49171. _this.angle = angle;
  49172. _this.exponent = exponent;
  49173. return _this;
  49174. }
  49175. Object.defineProperty(SpotLight.prototype, "angle", {
  49176. /**
  49177. * Gets the cone angle of the spot light in Radians.
  49178. */
  49179. get: function () {
  49180. return this._angle;
  49181. },
  49182. /**
  49183. * Sets the cone angle of the spot light in Radians.
  49184. */
  49185. set: function (value) {
  49186. this._angle = value;
  49187. this._cosHalfAngle = Math.cos(value * 0.5);
  49188. this._projectionTextureProjectionLightDirty = true;
  49189. this.forceProjectionMatrixCompute();
  49190. this._computeAngleValues();
  49191. },
  49192. enumerable: true,
  49193. configurable: true
  49194. });
  49195. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49196. /**
  49197. * Only used in gltf falloff mode, this defines the angle where
  49198. * the directional falloff will start before cutting at angle which could be seen
  49199. * as outer angle.
  49200. */
  49201. get: function () {
  49202. return this._angle;
  49203. },
  49204. /**
  49205. * Only used in gltf falloff mode, this defines the angle where
  49206. * the directional falloff will start before cutting at angle which could be seen
  49207. * as outer angle.
  49208. */
  49209. set: function (value) {
  49210. this._innerAngle = value;
  49211. this._computeAngleValues();
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49217. /**
  49218. * Allows scaling the angle of the light for shadow generation only.
  49219. */
  49220. get: function () {
  49221. return this._shadowAngleScale;
  49222. },
  49223. /**
  49224. * Allows scaling the angle of the light for shadow generation only.
  49225. */
  49226. set: function (value) {
  49227. this._shadowAngleScale = value;
  49228. this.forceProjectionMatrixCompute();
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49234. /**
  49235. * Allows reading the projecton texture
  49236. */
  49237. get: function () {
  49238. return this._projectionTextureMatrix;
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49244. /**
  49245. * Gets the near clip of the Spotlight for texture projection.
  49246. */
  49247. get: function () {
  49248. return this._projectionTextureLightNear;
  49249. },
  49250. /**
  49251. * Sets the near clip of the Spotlight for texture projection.
  49252. */
  49253. set: function (value) {
  49254. this._projectionTextureLightNear = value;
  49255. this._projectionTextureProjectionLightDirty = true;
  49256. },
  49257. enumerable: true,
  49258. configurable: true
  49259. });
  49260. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49261. /**
  49262. * Gets the far clip of the Spotlight for texture projection.
  49263. */
  49264. get: function () {
  49265. return this._projectionTextureLightFar;
  49266. },
  49267. /**
  49268. * Sets the far clip of the Spotlight for texture projection.
  49269. */
  49270. set: function (value) {
  49271. this._projectionTextureLightFar = value;
  49272. this._projectionTextureProjectionLightDirty = true;
  49273. },
  49274. enumerable: true,
  49275. configurable: true
  49276. });
  49277. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49278. /**
  49279. * Gets the Up vector of the Spotlight for texture projection.
  49280. */
  49281. get: function () {
  49282. return this._projectionTextureUpDirection;
  49283. },
  49284. /**
  49285. * Sets the Up vector of the Spotlight for texture projection.
  49286. */
  49287. set: function (value) {
  49288. this._projectionTextureUpDirection = value;
  49289. this._projectionTextureProjectionLightDirty = true;
  49290. },
  49291. enumerable: true,
  49292. configurable: true
  49293. });
  49294. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49295. /**
  49296. * Gets the projection texture of the light.
  49297. */
  49298. get: function () {
  49299. return this._projectionTexture;
  49300. },
  49301. /**
  49302. * Sets the projection texture of the light.
  49303. */
  49304. set: function (value) {
  49305. this._projectionTexture = value;
  49306. this._projectionTextureDirty = true;
  49307. },
  49308. enumerable: true,
  49309. configurable: true
  49310. });
  49311. /**
  49312. * Returns the string "SpotLight".
  49313. * @returns the class name
  49314. */
  49315. SpotLight.prototype.getClassName = function () {
  49316. return "SpotLight";
  49317. };
  49318. /**
  49319. * Returns the integer 2.
  49320. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49321. */
  49322. SpotLight.prototype.getTypeID = function () {
  49323. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49324. };
  49325. /**
  49326. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49327. */
  49328. SpotLight.prototype._setDirection = function (value) {
  49329. _super.prototype._setDirection.call(this, value);
  49330. this._projectionTextureViewLightDirty = true;
  49331. };
  49332. /**
  49333. * Overrides the position setter to recompute the projection texture view light Matrix.
  49334. */
  49335. SpotLight.prototype._setPosition = function (value) {
  49336. _super.prototype._setPosition.call(this, value);
  49337. this._projectionTextureViewLightDirty = true;
  49338. };
  49339. /**
  49340. * 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.
  49341. * Returns the SpotLight.
  49342. */
  49343. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49344. var activeCamera = this.getScene().activeCamera;
  49345. if (!activeCamera) {
  49346. return;
  49347. }
  49348. this._shadowAngleScale = this._shadowAngleScale || 1;
  49349. var angle = this._shadowAngleScale * this._angle;
  49350. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49351. };
  49352. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49353. this._projectionTextureViewLightDirty = false;
  49354. this._projectionTextureDirty = true;
  49355. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49356. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49357. };
  49358. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49359. this._projectionTextureProjectionLightDirty = false;
  49360. this._projectionTextureDirty = true;
  49361. var light_far = this.projectionTextureLightFar;
  49362. var light_near = this.projectionTextureLightNear;
  49363. var P = light_far / (light_far - light_near);
  49364. var Q = -P * light_near;
  49365. var S = 1.0 / Math.tan(this._angle / 2.0);
  49366. var A = 1.0;
  49367. 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);
  49368. };
  49369. /**
  49370. * Main function for light texture projection matrix computing.
  49371. */
  49372. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49373. this._projectionTextureDirty = false;
  49374. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49375. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49376. };
  49377. SpotLight.prototype._buildUniformLayout = function () {
  49378. this._uniformBuffer.addUniform("vLightData", 4);
  49379. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49380. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49381. this._uniformBuffer.addUniform("vLightDirection", 3);
  49382. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49383. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49384. this._uniformBuffer.addUniform("depthValues", 2);
  49385. this._uniformBuffer.create();
  49386. };
  49387. SpotLight.prototype._computeAngleValues = function () {
  49388. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49389. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49390. };
  49391. /**
  49392. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49393. * @param effect The effect to update
  49394. * @param lightIndex The index of the light in the effect to update
  49395. * @returns The spot light
  49396. */
  49397. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49398. var normalizeDirection;
  49399. if (this.computeTransformedInformation()) {
  49400. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49401. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49402. }
  49403. else {
  49404. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49405. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49406. }
  49407. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49408. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49409. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49410. if (this._projectionTextureViewLightDirty) {
  49411. this._computeProjectionTextureViewLightMatrix();
  49412. }
  49413. if (this._projectionTextureProjectionLightDirty) {
  49414. this._computeProjectionTextureProjectionLightMatrix();
  49415. }
  49416. if (this._projectionTextureDirty) {
  49417. this._computeProjectionTextureMatrix();
  49418. }
  49419. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49420. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49421. }
  49422. return this;
  49423. };
  49424. /**
  49425. * Disposes the light and the associated resources.
  49426. */
  49427. SpotLight.prototype.dispose = function () {
  49428. _super.prototype.dispose.call(this);
  49429. if (this._projectionTexture) {
  49430. this._projectionTexture.dispose();
  49431. }
  49432. };
  49433. /**
  49434. * Prepares the list of defines specific to the light type.
  49435. * @param defines the list of defines
  49436. * @param lightIndex defines the index of the light for the effect
  49437. */
  49438. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49439. defines["SPOTLIGHT" + lightIndex] = true;
  49440. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49441. };
  49442. __decorate([
  49443. BABYLON.serialize()
  49444. ], SpotLight.prototype, "angle", null);
  49445. __decorate([
  49446. BABYLON.serialize()
  49447. ], SpotLight.prototype, "innerAngle", null);
  49448. __decorate([
  49449. BABYLON.serialize()
  49450. ], SpotLight.prototype, "shadowAngleScale", null);
  49451. __decorate([
  49452. BABYLON.serialize()
  49453. ], SpotLight.prototype, "exponent", void 0);
  49454. __decorate([
  49455. BABYLON.serialize()
  49456. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49457. __decorate([
  49458. BABYLON.serialize()
  49459. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49460. __decorate([
  49461. BABYLON.serialize()
  49462. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49463. __decorate([
  49464. BABYLON.serializeAsTexture("projectedLightTexture")
  49465. ], SpotLight.prototype, "_projectionTexture", void 0);
  49466. return SpotLight;
  49467. }(BABYLON.ShadowLight));
  49468. BABYLON.SpotLight = SpotLight;
  49469. })(BABYLON || (BABYLON = {}));
  49470. //# sourceMappingURL=babylon.spotLight.js.map
  49471. var BABYLON;
  49472. (function (BABYLON) {
  49473. /**
  49474. * Class used to override all child animations of a given target
  49475. */
  49476. var AnimationPropertiesOverride = /** @class */ (function () {
  49477. function AnimationPropertiesOverride() {
  49478. /**
  49479. * Gets or sets a value indicating if animation blending must be used
  49480. */
  49481. this.enableBlending = false;
  49482. /**
  49483. * Gets or sets the blending speed to use when enableBlending is true
  49484. */
  49485. this.blendingSpeed = 0.01;
  49486. /**
  49487. * Gets or sets the default loop mode to use
  49488. */
  49489. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49490. }
  49491. return AnimationPropertiesOverride;
  49492. }());
  49493. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49494. })(BABYLON || (BABYLON = {}));
  49495. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49496. var BABYLON;
  49497. (function (BABYLON) {
  49498. /**
  49499. * Represents the range of an animation
  49500. */
  49501. var AnimationRange = /** @class */ (function () {
  49502. /**
  49503. * Initializes the range of an animation
  49504. * @param name The name of the animation range
  49505. * @param from The starting frame of the animation
  49506. * @param to The ending frame of the animation
  49507. */
  49508. function AnimationRange(
  49509. /**The name of the animation range**/
  49510. name,
  49511. /**The starting frame of the animation */
  49512. from,
  49513. /**The ending frame of the animation*/
  49514. to) {
  49515. this.name = name;
  49516. this.from = from;
  49517. this.to = to;
  49518. }
  49519. /**
  49520. * Makes a copy of the animation range
  49521. * @returns A copy of the animation range
  49522. */
  49523. AnimationRange.prototype.clone = function () {
  49524. return new AnimationRange(this.name, this.from, this.to);
  49525. };
  49526. return AnimationRange;
  49527. }());
  49528. BABYLON.AnimationRange = AnimationRange;
  49529. /**
  49530. * Composed of a frame, and an action function
  49531. */
  49532. var AnimationEvent = /** @class */ (function () {
  49533. /**
  49534. * Initializes the animation event
  49535. * @param frame The frame for which the event is triggered
  49536. * @param action The event to perform when triggered
  49537. * @param onlyOnce Specifies if the event should be triggered only once
  49538. */
  49539. function AnimationEvent(
  49540. /** The frame for which the event is triggered **/
  49541. frame,
  49542. /** The event to perform when triggered **/
  49543. action,
  49544. /** Specifies if the event should be triggered only once**/
  49545. onlyOnce) {
  49546. this.frame = frame;
  49547. this.action = action;
  49548. this.onlyOnce = onlyOnce;
  49549. /**
  49550. * Specifies if the animation event is done
  49551. */
  49552. this.isDone = false;
  49553. }
  49554. /** @hidden */
  49555. AnimationEvent.prototype._clone = function () {
  49556. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49557. };
  49558. return AnimationEvent;
  49559. }());
  49560. BABYLON.AnimationEvent = AnimationEvent;
  49561. /**
  49562. * A cursor which tracks a point on a path
  49563. */
  49564. var PathCursor = /** @class */ (function () {
  49565. /**
  49566. * Initializes the path cursor
  49567. * @param path The path to track
  49568. */
  49569. function PathCursor(path) {
  49570. this.path = path;
  49571. /**
  49572. * Stores path cursor callbacks for when an onchange event is triggered
  49573. */
  49574. this._onchange = new Array();
  49575. /**
  49576. * The value of the path cursor
  49577. */
  49578. this.value = 0;
  49579. /**
  49580. * The animation array of the path cursor
  49581. */
  49582. this.animations = new Array();
  49583. }
  49584. /**
  49585. * Gets the cursor point on the path
  49586. * @returns A point on the path cursor at the cursor location
  49587. */
  49588. PathCursor.prototype.getPoint = function () {
  49589. var point = this.path.getPointAtLengthPosition(this.value);
  49590. return new BABYLON.Vector3(point.x, 0, point.y);
  49591. };
  49592. /**
  49593. * Moves the cursor ahead by the step amount
  49594. * @param step The amount to move the cursor forward
  49595. * @returns This path cursor
  49596. */
  49597. PathCursor.prototype.moveAhead = function (step) {
  49598. if (step === void 0) { step = 0.002; }
  49599. this.move(step);
  49600. return this;
  49601. };
  49602. /**
  49603. * Moves the cursor behind by the step amount
  49604. * @param step The amount to move the cursor back
  49605. * @returns This path cursor
  49606. */
  49607. PathCursor.prototype.moveBack = function (step) {
  49608. if (step === void 0) { step = 0.002; }
  49609. this.move(-step);
  49610. return this;
  49611. };
  49612. /**
  49613. * Moves the cursor by the step amount
  49614. * If the step amount is greater than one, an exception is thrown
  49615. * @param step The amount to move the cursor
  49616. * @returns This path cursor
  49617. */
  49618. PathCursor.prototype.move = function (step) {
  49619. if (Math.abs(step) > 1) {
  49620. throw "step size should be less than 1.";
  49621. }
  49622. this.value += step;
  49623. this.ensureLimits();
  49624. this.raiseOnChange();
  49625. return this;
  49626. };
  49627. /**
  49628. * Ensures that the value is limited between zero and one
  49629. * @returns This path cursor
  49630. */
  49631. PathCursor.prototype.ensureLimits = function () {
  49632. while (this.value > 1) {
  49633. this.value -= 1;
  49634. }
  49635. while (this.value < 0) {
  49636. this.value += 1;
  49637. }
  49638. return this;
  49639. };
  49640. /**
  49641. * Runs onchange callbacks on change (used by the animation engine)
  49642. * @returns This path cursor
  49643. */
  49644. PathCursor.prototype.raiseOnChange = function () {
  49645. var _this = this;
  49646. this._onchange.forEach(function (f) { return f(_this); });
  49647. return this;
  49648. };
  49649. /**
  49650. * Executes a function on change
  49651. * @param f A path cursor onchange callback
  49652. * @returns This path cursor
  49653. */
  49654. PathCursor.prototype.onchange = function (f) {
  49655. this._onchange.push(f);
  49656. return this;
  49657. };
  49658. return PathCursor;
  49659. }());
  49660. BABYLON.PathCursor = PathCursor;
  49661. /**
  49662. * Enum for the animation key frame interpolation type
  49663. */
  49664. var AnimationKeyInterpolation;
  49665. (function (AnimationKeyInterpolation) {
  49666. /**
  49667. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49668. */
  49669. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49670. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49671. /**
  49672. * Class used to store any kind of animation
  49673. */
  49674. var Animation = /** @class */ (function () {
  49675. /**
  49676. * Initializes the animation
  49677. * @param name Name of the animation
  49678. * @param targetProperty Property to animate
  49679. * @param framePerSecond The frames per second of the animation
  49680. * @param dataType The data type of the animation
  49681. * @param loopMode The loop mode of the animation
  49682. * @param enableBlendings Specifies if blending should be enabled
  49683. */
  49684. function Animation(
  49685. /**Name of the animation */
  49686. name,
  49687. /**Property to animate */
  49688. targetProperty,
  49689. /**The frames per second of the animation */
  49690. framePerSecond,
  49691. /**The data type of the animation */
  49692. dataType,
  49693. /**The loop mode of the animation */
  49694. loopMode,
  49695. /**Specifies if blending should be enabled */
  49696. enableBlending) {
  49697. this.name = name;
  49698. this.targetProperty = targetProperty;
  49699. this.framePerSecond = framePerSecond;
  49700. this.dataType = dataType;
  49701. this.loopMode = loopMode;
  49702. this.enableBlending = enableBlending;
  49703. /**
  49704. * @hidden Internal use only
  49705. */
  49706. this._runtimeAnimations = new Array();
  49707. /**
  49708. * The set of event that will be linked to this animation
  49709. */
  49710. this._events = new Array();
  49711. /**
  49712. * Stores the blending speed of the animation
  49713. */
  49714. this.blendingSpeed = 0.01;
  49715. /**
  49716. * Stores the animation ranges for the animation
  49717. */
  49718. this._ranges = {};
  49719. this.targetPropertyPath = targetProperty.split(".");
  49720. this.dataType = dataType;
  49721. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49722. }
  49723. /**
  49724. * @hidden Internal use
  49725. */
  49726. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49727. var dataType = undefined;
  49728. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49729. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49730. }
  49731. else if (from instanceof BABYLON.Quaternion) {
  49732. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49733. }
  49734. else if (from instanceof BABYLON.Vector3) {
  49735. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49736. }
  49737. else if (from instanceof BABYLON.Vector2) {
  49738. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49739. }
  49740. else if (from instanceof BABYLON.Color3) {
  49741. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49742. }
  49743. else if (from instanceof BABYLON.Size) {
  49744. dataType = Animation.ANIMATIONTYPE_SIZE;
  49745. }
  49746. if (dataType == undefined) {
  49747. return null;
  49748. }
  49749. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49750. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49751. animation.setKeys(keys);
  49752. if (easingFunction !== undefined) {
  49753. animation.setEasingFunction(easingFunction);
  49754. }
  49755. return animation;
  49756. };
  49757. /**
  49758. * Sets up an animation
  49759. * @param property The property to animate
  49760. * @param animationType The animation type to apply
  49761. * @param framePerSecond The frames per second of the animation
  49762. * @param easingFunction The easing function used in the animation
  49763. * @returns The created animation
  49764. */
  49765. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49766. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49767. animation.setEasingFunction(easingFunction);
  49768. return animation;
  49769. };
  49770. /**
  49771. * Create and start an animation on a node
  49772. * @param name defines the name of the global animation that will be run on all nodes
  49773. * @param node defines the root node where the animation will take place
  49774. * @param targetProperty defines property to animate
  49775. * @param framePerSecond defines the number of frame per second yo use
  49776. * @param totalFrame defines the number of frames in total
  49777. * @param from defines the initial value
  49778. * @param to defines the final value
  49779. * @param loopMode defines which loop mode you want to use (off by default)
  49780. * @param easingFunction defines the easing function to use (linear by default)
  49781. * @param onAnimationEnd defines the callback to call when animation end
  49782. * @returns the animatable created for this animation
  49783. */
  49784. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49785. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49786. if (!animation) {
  49787. return null;
  49788. }
  49789. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49790. };
  49791. /**
  49792. * Create and start an animation on a node and its descendants
  49793. * @param name defines the name of the global animation that will be run on all nodes
  49794. * @param node defines the root node where the animation will take place
  49795. * @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
  49796. * @param targetProperty defines property to animate
  49797. * @param framePerSecond defines the number of frame per second to use
  49798. * @param totalFrame defines the number of frames in total
  49799. * @param from defines the initial value
  49800. * @param to defines the final value
  49801. * @param loopMode defines which loop mode you want to use (off by default)
  49802. * @param easingFunction defines the easing function to use (linear by default)
  49803. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49804. * @returns the list of animatables created for all nodes
  49805. * @example https://www.babylonjs-playground.com/#MH0VLI
  49806. */
  49807. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49808. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49809. if (!animation) {
  49810. return null;
  49811. }
  49812. var scene = node.getScene();
  49813. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49814. };
  49815. /**
  49816. * Creates a new animation, merges it with the existing animations and starts it
  49817. * @param name Name of the animation
  49818. * @param node Node which contains the scene that begins the animations
  49819. * @param targetProperty Specifies which property to animate
  49820. * @param framePerSecond The frames per second of the animation
  49821. * @param totalFrame The total number of frames
  49822. * @param from The frame at the beginning of the animation
  49823. * @param to The frame at the end of the animation
  49824. * @param loopMode Specifies the loop mode of the animation
  49825. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49826. * @param onAnimationEnd Callback to run once the animation is complete
  49827. * @returns Nullable animation
  49828. */
  49829. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49830. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49831. if (!animation) {
  49832. return null;
  49833. }
  49834. node.animations.push(animation);
  49835. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49836. };
  49837. /**
  49838. * Transition property of an host to the target Value
  49839. * @param property The property to transition
  49840. * @param targetValue The target Value of the property
  49841. * @param host The object where the property to animate belongs
  49842. * @param scene Scene used to run the animation
  49843. * @param frameRate Framerate (in frame/s) to use
  49844. * @param transition The transition type we want to use
  49845. * @param duration The duration of the animation, in milliseconds
  49846. * @param onAnimationEnd Callback trigger at the end of the animation
  49847. * @returns Nullable animation
  49848. */
  49849. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49850. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49851. if (duration <= 0) {
  49852. host[property] = targetValue;
  49853. if (onAnimationEnd) {
  49854. onAnimationEnd();
  49855. }
  49856. return null;
  49857. }
  49858. var endFrame = frameRate * (duration / 1000);
  49859. transition.setKeys([{
  49860. frame: 0,
  49861. value: host[property].clone ? host[property].clone() : host[property]
  49862. },
  49863. {
  49864. frame: endFrame,
  49865. value: targetValue
  49866. }]);
  49867. if (!host.animations) {
  49868. host.animations = [];
  49869. }
  49870. host.animations.push(transition);
  49871. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49872. animation.onAnimationEnd = onAnimationEnd;
  49873. return animation;
  49874. };
  49875. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49876. /**
  49877. * Return the array of runtime animations currently using this animation
  49878. */
  49879. get: function () {
  49880. return this._runtimeAnimations;
  49881. },
  49882. enumerable: true,
  49883. configurable: true
  49884. });
  49885. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49886. /**
  49887. * Specifies if any of the runtime animations are currently running
  49888. */
  49889. get: function () {
  49890. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49891. var runtimeAnimation = _a[_i];
  49892. if (!runtimeAnimation.isStopped) {
  49893. return true;
  49894. }
  49895. }
  49896. return false;
  49897. },
  49898. enumerable: true,
  49899. configurable: true
  49900. });
  49901. // Methods
  49902. /**
  49903. * Converts the animation to a string
  49904. * @param fullDetails support for multiple levels of logging within scene loading
  49905. * @returns String form of the animation
  49906. */
  49907. Animation.prototype.toString = function (fullDetails) {
  49908. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49909. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49910. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49911. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49912. if (fullDetails) {
  49913. ret += ", Ranges: {";
  49914. var first = true;
  49915. for (var name in this._ranges) {
  49916. if (first) {
  49917. ret += ", ";
  49918. first = false;
  49919. }
  49920. ret += name;
  49921. }
  49922. ret += "}";
  49923. }
  49924. return ret;
  49925. };
  49926. /**
  49927. * Add an event to this animation
  49928. * @param event Event to add
  49929. */
  49930. Animation.prototype.addEvent = function (event) {
  49931. this._events.push(event);
  49932. };
  49933. /**
  49934. * Remove all events found at the given frame
  49935. * @param frame The frame to remove events from
  49936. */
  49937. Animation.prototype.removeEvents = function (frame) {
  49938. for (var index = 0; index < this._events.length; index++) {
  49939. if (this._events[index].frame === frame) {
  49940. this._events.splice(index, 1);
  49941. index--;
  49942. }
  49943. }
  49944. };
  49945. /**
  49946. * Retrieves all the events from the animation
  49947. * @returns Events from the animation
  49948. */
  49949. Animation.prototype.getEvents = function () {
  49950. return this._events;
  49951. };
  49952. /**
  49953. * Creates an animation range
  49954. * @param name Name of the animation range
  49955. * @param from Starting frame of the animation range
  49956. * @param to Ending frame of the animation
  49957. */
  49958. Animation.prototype.createRange = function (name, from, to) {
  49959. // check name not already in use; could happen for bones after serialized
  49960. if (!this._ranges[name]) {
  49961. this._ranges[name] = new AnimationRange(name, from, to);
  49962. }
  49963. };
  49964. /**
  49965. * Deletes an animation range by name
  49966. * @param name Name of the animation range to delete
  49967. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49968. */
  49969. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49970. if (deleteFrames === void 0) { deleteFrames = true; }
  49971. var range = this._ranges[name];
  49972. if (!range) {
  49973. return;
  49974. }
  49975. if (deleteFrames) {
  49976. var from = range.from;
  49977. var to = range.to;
  49978. // this loop MUST go high to low for multiple splices to work
  49979. for (var key = this._keys.length - 1; key >= 0; key--) {
  49980. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49981. this._keys.splice(key, 1);
  49982. }
  49983. }
  49984. }
  49985. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49986. };
  49987. /**
  49988. * Gets the animation range by name, or null if not defined
  49989. * @param name Name of the animation range
  49990. * @returns Nullable animation range
  49991. */
  49992. Animation.prototype.getRange = function (name) {
  49993. return this._ranges[name];
  49994. };
  49995. /**
  49996. * Gets the key frames from the animation
  49997. * @returns The key frames of the animation
  49998. */
  49999. Animation.prototype.getKeys = function () {
  50000. return this._keys;
  50001. };
  50002. /**
  50003. * Gets the highest frame rate of the animation
  50004. * @returns Highest frame rate of the animation
  50005. */
  50006. Animation.prototype.getHighestFrame = function () {
  50007. var ret = 0;
  50008. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50009. if (ret < this._keys[key].frame) {
  50010. ret = this._keys[key].frame;
  50011. }
  50012. }
  50013. return ret;
  50014. };
  50015. /**
  50016. * Gets the easing function of the animation
  50017. * @returns Easing function of the animation
  50018. */
  50019. Animation.prototype.getEasingFunction = function () {
  50020. return this._easingFunction;
  50021. };
  50022. /**
  50023. * Sets the easing function of the animation
  50024. * @param easingFunction A custom mathematical formula for animation
  50025. */
  50026. Animation.prototype.setEasingFunction = function (easingFunction) {
  50027. this._easingFunction = easingFunction;
  50028. };
  50029. /**
  50030. * Interpolates a scalar linearly
  50031. * @param startValue Start value of the animation curve
  50032. * @param endValue End value of the animation curve
  50033. * @param gradient Scalar amount to interpolate
  50034. * @returns Interpolated scalar value
  50035. */
  50036. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50037. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50038. };
  50039. /**
  50040. * Interpolates a scalar cubically
  50041. * @param startValue Start value of the animation curve
  50042. * @param outTangent End tangent of the animation
  50043. * @param endValue End value of the animation curve
  50044. * @param inTangent Start tangent of the animation curve
  50045. * @param gradient Scalar amount to interpolate
  50046. * @returns Interpolated scalar value
  50047. */
  50048. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50049. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50050. };
  50051. /**
  50052. * Interpolates a quaternion using a spherical linear interpolation
  50053. * @param startValue Start value of the animation curve
  50054. * @param endValue End value of the animation curve
  50055. * @param gradient Scalar amount to interpolate
  50056. * @returns Interpolated quaternion value
  50057. */
  50058. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50059. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50060. };
  50061. /**
  50062. * Interpolates a quaternion cubically
  50063. * @param startValue Start value of the animation curve
  50064. * @param outTangent End tangent of the animation curve
  50065. * @param endValue End value of the animation curve
  50066. * @param inTangent Start tangent of the animation curve
  50067. * @param gradient Scalar amount to interpolate
  50068. * @returns Interpolated quaternion value
  50069. */
  50070. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50071. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50072. };
  50073. /**
  50074. * Interpolates a Vector3 linearl
  50075. * @param startValue Start value of the animation curve
  50076. * @param endValue End value of the animation curve
  50077. * @param gradient Scalar amount to interpolate
  50078. * @returns Interpolated scalar value
  50079. */
  50080. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50081. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50082. };
  50083. /**
  50084. * Interpolates a Vector3 cubically
  50085. * @param startValue Start value of the animation curve
  50086. * @param outTangent End tangent of the animation
  50087. * @param endValue End value of the animation curve
  50088. * @param inTangent Start tangent of the animation curve
  50089. * @param gradient Scalar amount to interpolate
  50090. * @returns InterpolatedVector3 value
  50091. */
  50092. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50093. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50094. };
  50095. /**
  50096. * Interpolates a Vector2 linearly
  50097. * @param startValue Start value of the animation curve
  50098. * @param endValue End value of the animation curve
  50099. * @param gradient Scalar amount to interpolate
  50100. * @returns Interpolated Vector2 value
  50101. */
  50102. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50103. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50104. };
  50105. /**
  50106. * Interpolates a Vector2 cubically
  50107. * @param startValue Start value of the animation curve
  50108. * @param outTangent End tangent of the animation
  50109. * @param endValue End value of the animation curve
  50110. * @param inTangent Start tangent of the animation curve
  50111. * @param gradient Scalar amount to interpolate
  50112. * @returns Interpolated Vector2 value
  50113. */
  50114. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50115. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50116. };
  50117. /**
  50118. * Interpolates a size linearly
  50119. * @param startValue Start value of the animation curve
  50120. * @param endValue End value of the animation curve
  50121. * @param gradient Scalar amount to interpolate
  50122. * @returns Interpolated Size value
  50123. */
  50124. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50125. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50126. };
  50127. /**
  50128. * Interpolates a Color3 linearly
  50129. * @param startValue Start value of the animation curve
  50130. * @param endValue End value of the animation curve
  50131. * @param gradient Scalar amount to interpolate
  50132. * @returns Interpolated Color3 value
  50133. */
  50134. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50135. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50136. };
  50137. /**
  50138. * @hidden Internal use only
  50139. */
  50140. Animation.prototype._getKeyValue = function (value) {
  50141. if (typeof value === "function") {
  50142. return value();
  50143. }
  50144. return value;
  50145. };
  50146. /**
  50147. * @hidden Internal use only
  50148. */
  50149. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50150. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50151. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50152. }
  50153. var keys = this.getKeys();
  50154. // Try to get a hash to find the right key
  50155. 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));
  50156. if (keys[startKeyIndex].frame >= currentFrame) {
  50157. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50158. startKeyIndex--;
  50159. }
  50160. }
  50161. for (var key = startKeyIndex; key < keys.length; key++) {
  50162. var endKey = keys[key + 1];
  50163. if (endKey.frame >= currentFrame) {
  50164. var startKey = keys[key];
  50165. var startValue = this._getKeyValue(startKey.value);
  50166. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50167. return startValue;
  50168. }
  50169. var endValue = this._getKeyValue(endKey.value);
  50170. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50171. var frameDelta = endKey.frame - startKey.frame;
  50172. // gradient : percent of currentFrame between the frame inf and the frame sup
  50173. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50174. // check for easingFunction and correction of gradient
  50175. var easingFunction = this.getEasingFunction();
  50176. if (easingFunction != null) {
  50177. gradient = easingFunction.ease(gradient);
  50178. }
  50179. switch (this.dataType) {
  50180. // Float
  50181. case Animation.ANIMATIONTYPE_FLOAT:
  50182. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50183. switch (loopMode) {
  50184. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50185. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50186. return floatValue;
  50187. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50188. return offsetValue * repeatCount + floatValue;
  50189. }
  50190. break;
  50191. // Quaternion
  50192. case Animation.ANIMATIONTYPE_QUATERNION:
  50193. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50194. switch (loopMode) {
  50195. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50196. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50197. return quatValue;
  50198. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50199. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50200. }
  50201. return quatValue;
  50202. // Vector3
  50203. case Animation.ANIMATIONTYPE_VECTOR3:
  50204. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50205. switch (loopMode) {
  50206. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50207. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50208. return vec3Value;
  50209. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50210. return vec3Value.add(offsetValue.scale(repeatCount));
  50211. }
  50212. // Vector2
  50213. case Animation.ANIMATIONTYPE_VECTOR2:
  50214. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50215. switch (loopMode) {
  50216. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50217. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50218. return vec2Value;
  50219. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50220. return vec2Value.add(offsetValue.scale(repeatCount));
  50221. }
  50222. // Size
  50223. case Animation.ANIMATIONTYPE_SIZE:
  50224. switch (loopMode) {
  50225. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50226. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50227. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50228. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50229. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50230. }
  50231. // Color3
  50232. case Animation.ANIMATIONTYPE_COLOR3:
  50233. switch (loopMode) {
  50234. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50235. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50236. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50237. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50238. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50239. }
  50240. // Matrix
  50241. case Animation.ANIMATIONTYPE_MATRIX:
  50242. switch (loopMode) {
  50243. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50244. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50245. if (Animation.AllowMatricesInterpolation) {
  50246. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50247. }
  50248. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50249. return startValue;
  50250. }
  50251. default:
  50252. break;
  50253. }
  50254. break;
  50255. }
  50256. }
  50257. return this._getKeyValue(keys[keys.length - 1].value);
  50258. };
  50259. /**
  50260. * Defines the function to use to interpolate matrices
  50261. * @param startValue defines the start matrix
  50262. * @param endValue defines the end matrix
  50263. * @param gradient defines the gradient between both matrices
  50264. * @param result defines an optional target matrix where to store the interpolation
  50265. * @returns the interpolated matrix
  50266. */
  50267. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50268. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50269. if (result) {
  50270. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50271. return result;
  50272. }
  50273. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50274. }
  50275. if (result) {
  50276. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50277. return result;
  50278. }
  50279. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50280. };
  50281. /**
  50282. * Makes a copy of the animation
  50283. * @returns Cloned animation
  50284. */
  50285. Animation.prototype.clone = function () {
  50286. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50287. clone.enableBlending = this.enableBlending;
  50288. clone.blendingSpeed = this.blendingSpeed;
  50289. if (this._keys) {
  50290. clone.setKeys(this._keys);
  50291. }
  50292. if (this._ranges) {
  50293. clone._ranges = {};
  50294. for (var name in this._ranges) {
  50295. var range = this._ranges[name];
  50296. if (!range) {
  50297. continue;
  50298. }
  50299. clone._ranges[name] = range.clone();
  50300. }
  50301. }
  50302. return clone;
  50303. };
  50304. /**
  50305. * Sets the key frames of the animation
  50306. * @param values The animation key frames to set
  50307. */
  50308. Animation.prototype.setKeys = function (values) {
  50309. this._keys = values.slice(0);
  50310. };
  50311. /**
  50312. * Serializes the animation to an object
  50313. * @returns Serialized object
  50314. */
  50315. Animation.prototype.serialize = function () {
  50316. var serializationObject = {};
  50317. serializationObject.name = this.name;
  50318. serializationObject.property = this.targetProperty;
  50319. serializationObject.framePerSecond = this.framePerSecond;
  50320. serializationObject.dataType = this.dataType;
  50321. serializationObject.loopBehavior = this.loopMode;
  50322. serializationObject.enableBlending = this.enableBlending;
  50323. serializationObject.blendingSpeed = this.blendingSpeed;
  50324. var dataType = this.dataType;
  50325. serializationObject.keys = [];
  50326. var keys = this.getKeys();
  50327. for (var index = 0; index < keys.length; index++) {
  50328. var animationKey = keys[index];
  50329. var key = {};
  50330. key.frame = animationKey.frame;
  50331. switch (dataType) {
  50332. case Animation.ANIMATIONTYPE_FLOAT:
  50333. key.values = [animationKey.value];
  50334. break;
  50335. case Animation.ANIMATIONTYPE_QUATERNION:
  50336. case Animation.ANIMATIONTYPE_MATRIX:
  50337. case Animation.ANIMATIONTYPE_VECTOR3:
  50338. case Animation.ANIMATIONTYPE_COLOR3:
  50339. key.values = animationKey.value.asArray();
  50340. break;
  50341. }
  50342. serializationObject.keys.push(key);
  50343. }
  50344. serializationObject.ranges = [];
  50345. for (var name in this._ranges) {
  50346. var source = this._ranges[name];
  50347. if (!source) {
  50348. continue;
  50349. }
  50350. var range = {};
  50351. range.name = name;
  50352. range.from = source.from;
  50353. range.to = source.to;
  50354. serializationObject.ranges.push(range);
  50355. }
  50356. return serializationObject;
  50357. };
  50358. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50359. /**
  50360. * Get the float animation type
  50361. */
  50362. get: function () {
  50363. return Animation._ANIMATIONTYPE_FLOAT;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50369. /**
  50370. * Get the Vector3 animation type
  50371. */
  50372. get: function () {
  50373. return Animation._ANIMATIONTYPE_VECTOR3;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50379. /**
  50380. * Get the Vector2 animation type
  50381. */
  50382. get: function () {
  50383. return Animation._ANIMATIONTYPE_VECTOR2;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50389. /**
  50390. * Get the Size animation type
  50391. */
  50392. get: function () {
  50393. return Animation._ANIMATIONTYPE_SIZE;
  50394. },
  50395. enumerable: true,
  50396. configurable: true
  50397. });
  50398. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50399. /**
  50400. * Get the Quaternion animation type
  50401. */
  50402. get: function () {
  50403. return Animation._ANIMATIONTYPE_QUATERNION;
  50404. },
  50405. enumerable: true,
  50406. configurable: true
  50407. });
  50408. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50409. /**
  50410. * Get the Matrix animation type
  50411. */
  50412. get: function () {
  50413. return Animation._ANIMATIONTYPE_MATRIX;
  50414. },
  50415. enumerable: true,
  50416. configurable: true
  50417. });
  50418. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50419. /**
  50420. * Get the Color3 animation type
  50421. */
  50422. get: function () {
  50423. return Animation._ANIMATIONTYPE_COLOR3;
  50424. },
  50425. enumerable: true,
  50426. configurable: true
  50427. });
  50428. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50429. /**
  50430. * Get the Relative Loop Mode
  50431. */
  50432. get: function () {
  50433. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50434. },
  50435. enumerable: true,
  50436. configurable: true
  50437. });
  50438. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50439. /**
  50440. * Get the Cycle Loop Mode
  50441. */
  50442. get: function () {
  50443. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50444. },
  50445. enumerable: true,
  50446. configurable: true
  50447. });
  50448. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50449. /**
  50450. * Get the Constant Loop Mode
  50451. */
  50452. get: function () {
  50453. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50454. },
  50455. enumerable: true,
  50456. configurable: true
  50457. });
  50458. /** @hidden */
  50459. Animation._UniversalLerp = function (left, right, amount) {
  50460. var constructor = left.constructor;
  50461. if (constructor.Lerp) { // Lerp supported
  50462. return constructor.Lerp(left, right, amount);
  50463. }
  50464. else if (constructor.Slerp) { // Slerp supported
  50465. return constructor.Slerp(left, right, amount);
  50466. }
  50467. else if (left.toFixed) { // Number
  50468. return left * (1.0 - amount) + amount * right;
  50469. }
  50470. else { // Blending not supported
  50471. return right;
  50472. }
  50473. };
  50474. /**
  50475. * Parses an animation object and creates an animation
  50476. * @param parsedAnimation Parsed animation object
  50477. * @returns Animation object
  50478. */
  50479. Animation.Parse = function (parsedAnimation) {
  50480. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50481. var dataType = parsedAnimation.dataType;
  50482. var keys = [];
  50483. var data;
  50484. var index;
  50485. if (parsedAnimation.enableBlending) {
  50486. animation.enableBlending = parsedAnimation.enableBlending;
  50487. }
  50488. if (parsedAnimation.blendingSpeed) {
  50489. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50490. }
  50491. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50492. var key = parsedAnimation.keys[index];
  50493. var inTangent;
  50494. var outTangent;
  50495. switch (dataType) {
  50496. case Animation.ANIMATIONTYPE_FLOAT:
  50497. data = key.values[0];
  50498. if (key.values.length >= 1) {
  50499. inTangent = key.values[1];
  50500. }
  50501. if (key.values.length >= 2) {
  50502. outTangent = key.values[2];
  50503. }
  50504. break;
  50505. case Animation.ANIMATIONTYPE_QUATERNION:
  50506. data = BABYLON.Quaternion.FromArray(key.values);
  50507. if (key.values.length >= 8) {
  50508. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50509. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50510. inTangent = _inTangent;
  50511. }
  50512. }
  50513. if (key.values.length >= 12) {
  50514. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50515. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50516. outTangent = _outTangent;
  50517. }
  50518. }
  50519. break;
  50520. case Animation.ANIMATIONTYPE_MATRIX:
  50521. data = BABYLON.Matrix.FromArray(key.values);
  50522. break;
  50523. case Animation.ANIMATIONTYPE_COLOR3:
  50524. data = BABYLON.Color3.FromArray(key.values);
  50525. break;
  50526. case Animation.ANIMATIONTYPE_VECTOR3:
  50527. default:
  50528. data = BABYLON.Vector3.FromArray(key.values);
  50529. break;
  50530. }
  50531. var keyData = {};
  50532. keyData.frame = key.frame;
  50533. keyData.value = data;
  50534. if (inTangent != undefined) {
  50535. keyData.inTangent = inTangent;
  50536. }
  50537. if (outTangent != undefined) {
  50538. keyData.outTangent = outTangent;
  50539. }
  50540. keys.push(keyData);
  50541. }
  50542. animation.setKeys(keys);
  50543. if (parsedAnimation.ranges) {
  50544. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50545. data = parsedAnimation.ranges[index];
  50546. animation.createRange(data.name, data.from, data.to);
  50547. }
  50548. }
  50549. return animation;
  50550. };
  50551. /**
  50552. * Appends the serialized animations from the source animations
  50553. * @param source Source containing the animations
  50554. * @param destination Target to store the animations
  50555. */
  50556. Animation.AppendSerializedAnimations = function (source, destination) {
  50557. if (source.animations) {
  50558. destination.animations = [];
  50559. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50560. var animation = source.animations[animationIndex];
  50561. destination.animations.push(animation.serialize());
  50562. }
  50563. }
  50564. };
  50565. /**
  50566. * Use matrix interpolation instead of using direct key value when animating matrices
  50567. */
  50568. Animation.AllowMatricesInterpolation = false;
  50569. /**
  50570. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50571. */
  50572. Animation.AllowMatrixDecomposeForInterpolation = true;
  50573. // Statics
  50574. /**
  50575. * Float animation type
  50576. */
  50577. Animation._ANIMATIONTYPE_FLOAT = 0;
  50578. /**
  50579. * Vector3 animation type
  50580. */
  50581. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50582. /**
  50583. * Quaternion animation type
  50584. */
  50585. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50586. /**
  50587. * Matrix animation type
  50588. */
  50589. Animation._ANIMATIONTYPE_MATRIX = 3;
  50590. /**
  50591. * Color3 animation type
  50592. */
  50593. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50594. /**
  50595. * Vector2 animation type
  50596. */
  50597. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50598. /**
  50599. * Size animation type
  50600. */
  50601. Animation._ANIMATIONTYPE_SIZE = 6;
  50602. /**
  50603. * Relative Loop Mode
  50604. */
  50605. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50606. /**
  50607. * Cycle Loop Mode
  50608. */
  50609. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50610. /**
  50611. * Constant Loop Mode
  50612. */
  50613. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50614. return Animation;
  50615. }());
  50616. BABYLON.Animation = Animation;
  50617. })(BABYLON || (BABYLON = {}));
  50618. //# sourceMappingURL=babylon.animation.js.map
  50619. var BABYLON;
  50620. (function (BABYLON) {
  50621. /**
  50622. * This class defines the direct association between an animation and a target
  50623. */
  50624. var TargetedAnimation = /** @class */ (function () {
  50625. function TargetedAnimation() {
  50626. }
  50627. return TargetedAnimation;
  50628. }());
  50629. BABYLON.TargetedAnimation = TargetedAnimation;
  50630. /**
  50631. * Use this class to create coordinated animations on multiple targets
  50632. */
  50633. var AnimationGroup = /** @class */ (function () {
  50634. /**
  50635. * Instantiates a new Animation Group.
  50636. * This helps managing several animations at once.
  50637. * @see http://doc.babylonjs.com/how_to/group
  50638. * @param name Defines the name of the group
  50639. * @param scene Defines the scene the group belongs to
  50640. */
  50641. function AnimationGroup(
  50642. /** The name of the animation group */
  50643. name, scene) {
  50644. if (scene === void 0) { scene = null; }
  50645. this.name = name;
  50646. this._targetedAnimations = new Array();
  50647. this._animatables = new Array();
  50648. this._from = Number.MAX_VALUE;
  50649. this._to = -Number.MAX_VALUE;
  50650. this._speedRatio = 1;
  50651. /**
  50652. * This observable will notify when one animation have ended.
  50653. */
  50654. this.onAnimationEndObservable = new BABYLON.Observable();
  50655. /**
  50656. * This observable will notify when all animations have ended.
  50657. */
  50658. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50659. /**
  50660. * This observable will notify when all animations have paused.
  50661. */
  50662. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50663. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50664. this._scene.animationGroups.push(this);
  50665. }
  50666. Object.defineProperty(AnimationGroup.prototype, "from", {
  50667. /**
  50668. * Gets the first frame
  50669. */
  50670. get: function () {
  50671. return this._from;
  50672. },
  50673. enumerable: true,
  50674. configurable: true
  50675. });
  50676. Object.defineProperty(AnimationGroup.prototype, "to", {
  50677. /**
  50678. * Gets the last frame
  50679. */
  50680. get: function () {
  50681. return this._to;
  50682. },
  50683. enumerable: true,
  50684. configurable: true
  50685. });
  50686. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50687. /**
  50688. * Define if the animations are started
  50689. */
  50690. get: function () {
  50691. return this._isStarted;
  50692. },
  50693. enumerable: true,
  50694. configurable: true
  50695. });
  50696. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50697. /**
  50698. * Gets or sets the speed ratio to use for all animations
  50699. */
  50700. get: function () {
  50701. return this._speedRatio;
  50702. },
  50703. /**
  50704. * Gets or sets the speed ratio to use for all animations
  50705. */
  50706. set: function (value) {
  50707. if (this._speedRatio === value) {
  50708. return;
  50709. }
  50710. this._speedRatio = value;
  50711. for (var index = 0; index < this._animatables.length; index++) {
  50712. var animatable = this._animatables[index];
  50713. animatable.speedRatio = this._speedRatio;
  50714. }
  50715. },
  50716. enumerable: true,
  50717. configurable: true
  50718. });
  50719. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50720. /**
  50721. * Gets the targeted animations for this animation group
  50722. */
  50723. get: function () {
  50724. return this._targetedAnimations;
  50725. },
  50726. enumerable: true,
  50727. configurable: true
  50728. });
  50729. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50730. /**
  50731. * returning the list of animatables controlled by this animation group.
  50732. */
  50733. get: function () {
  50734. return this._animatables;
  50735. },
  50736. enumerable: true,
  50737. configurable: true
  50738. });
  50739. /**
  50740. * Add an animation (with its target) in the group
  50741. * @param animation defines the animation we want to add
  50742. * @param target defines the target of the animation
  50743. * @returns the {BABYLON.TargetedAnimation} object
  50744. */
  50745. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50746. var targetedAnimation = {
  50747. animation: animation,
  50748. target: target
  50749. };
  50750. var keys = animation.getKeys();
  50751. if (this._from > keys[0].frame) {
  50752. this._from = keys[0].frame;
  50753. }
  50754. if (this._to < keys[keys.length - 1].frame) {
  50755. this._to = keys[keys.length - 1].frame;
  50756. }
  50757. this._targetedAnimations.push(targetedAnimation);
  50758. return targetedAnimation;
  50759. };
  50760. /**
  50761. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50762. * It can add constant keys at begin or end
  50763. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50764. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50765. * @returns the animation group
  50766. */
  50767. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50768. if (beginFrame === void 0) { beginFrame = null; }
  50769. if (endFrame === void 0) { endFrame = null; }
  50770. if (beginFrame == null)
  50771. beginFrame = this._from;
  50772. if (endFrame == null)
  50773. endFrame = this._to;
  50774. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50775. var targetedAnimation = this._targetedAnimations[index];
  50776. var keys = targetedAnimation.animation.getKeys();
  50777. var startKey = keys[0];
  50778. var endKey = keys[keys.length - 1];
  50779. if (startKey.frame > beginFrame) {
  50780. var newKey = {
  50781. frame: beginFrame,
  50782. value: startKey.value,
  50783. inTangent: startKey.inTangent,
  50784. outTangent: startKey.outTangent,
  50785. interpolation: startKey.interpolation
  50786. };
  50787. keys.splice(0, 0, newKey);
  50788. }
  50789. if (endKey.frame < endFrame) {
  50790. var newKey = {
  50791. frame: endFrame,
  50792. value: endKey.value,
  50793. inTangent: endKey.outTangent,
  50794. outTangent: endKey.outTangent,
  50795. interpolation: endKey.interpolation
  50796. };
  50797. keys.push(newKey);
  50798. }
  50799. }
  50800. this._from = beginFrame;
  50801. this._to = endFrame;
  50802. return this;
  50803. };
  50804. /**
  50805. * Start all animations on given targets
  50806. * @param loop defines if animations must loop
  50807. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50808. * @param from defines the from key (optional)
  50809. * @param to defines the to key (optional)
  50810. * @returns the current animation group
  50811. */
  50812. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50813. var _this = this;
  50814. if (loop === void 0) { loop = false; }
  50815. if (speedRatio === void 0) { speedRatio = 1; }
  50816. if (this._isStarted || this._targetedAnimations.length === 0) {
  50817. return this;
  50818. }
  50819. var _loop_1 = function (targetedAnimation) {
  50820. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50821. animatable.onAnimationEnd = function () {
  50822. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50823. _this._checkAnimationGroupEnded(animatable);
  50824. };
  50825. this_1._animatables.push(animatable);
  50826. };
  50827. var this_1 = this;
  50828. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50829. var targetedAnimation = _a[_i];
  50830. _loop_1(targetedAnimation);
  50831. }
  50832. this._speedRatio = speedRatio;
  50833. this._isStarted = true;
  50834. return this;
  50835. };
  50836. /**
  50837. * Pause all animations
  50838. * @returns the animation group
  50839. */
  50840. AnimationGroup.prototype.pause = function () {
  50841. if (!this._isStarted) {
  50842. return this;
  50843. }
  50844. for (var index = 0; index < this._animatables.length; index++) {
  50845. var animatable = this._animatables[index];
  50846. animatable.pause();
  50847. }
  50848. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50849. return this;
  50850. };
  50851. /**
  50852. * Play all animations to initial state
  50853. * This function will start() the animations if they were not started or will restart() them if they were paused
  50854. * @param loop defines if animations must loop
  50855. * @returns the animation group
  50856. */
  50857. AnimationGroup.prototype.play = function (loop) {
  50858. // only if all animatables are ready and exist
  50859. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50860. if (loop !== undefined) {
  50861. for (var index = 0; index < this._animatables.length; index++) {
  50862. var animatable = this._animatables[index];
  50863. animatable.loopAnimation = loop;
  50864. }
  50865. }
  50866. this.restart();
  50867. }
  50868. else {
  50869. this.stop();
  50870. this.start(loop, this._speedRatio);
  50871. }
  50872. return this;
  50873. };
  50874. /**
  50875. * Reset all animations to initial state
  50876. * @returns the animation group
  50877. */
  50878. AnimationGroup.prototype.reset = function () {
  50879. if (!this._isStarted) {
  50880. return this;
  50881. }
  50882. for (var index = 0; index < this._animatables.length; index++) {
  50883. var animatable = this._animatables[index];
  50884. animatable.reset();
  50885. }
  50886. return this;
  50887. };
  50888. /**
  50889. * Restart animations from key 0
  50890. * @returns the animation group
  50891. */
  50892. AnimationGroup.prototype.restart = function () {
  50893. if (!this._isStarted) {
  50894. return this;
  50895. }
  50896. for (var index = 0; index < this._animatables.length; index++) {
  50897. var animatable = this._animatables[index];
  50898. animatable.restart();
  50899. }
  50900. return this;
  50901. };
  50902. /**
  50903. * Stop all animations
  50904. * @returns the animation group
  50905. */
  50906. AnimationGroup.prototype.stop = function () {
  50907. if (!this._isStarted) {
  50908. return this;
  50909. }
  50910. var list = this._animatables.slice();
  50911. for (var index = 0; index < list.length; index++) {
  50912. list[index].stop();
  50913. }
  50914. this._isStarted = false;
  50915. return this;
  50916. };
  50917. /**
  50918. * Set animation weight for all animatables
  50919. * @param weight defines the weight to use
  50920. * @return the animationGroup
  50921. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50922. */
  50923. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50924. for (var index = 0; index < this._animatables.length; index++) {
  50925. var animatable = this._animatables[index];
  50926. animatable.weight = weight;
  50927. }
  50928. return this;
  50929. };
  50930. /**
  50931. * Synchronize and normalize all animatables with a source animatable
  50932. * @param root defines the root animatable to synchronize with
  50933. * @return the animationGroup
  50934. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50935. */
  50936. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50937. for (var index = 0; index < this._animatables.length; index++) {
  50938. var animatable = this._animatables[index];
  50939. animatable.syncWith(root);
  50940. }
  50941. return this;
  50942. };
  50943. /**
  50944. * Goes to a specific frame in this animation group
  50945. * @param frame the frame number to go to
  50946. * @return the animationGroup
  50947. */
  50948. AnimationGroup.prototype.goToFrame = function (frame) {
  50949. if (!this._isStarted) {
  50950. return this;
  50951. }
  50952. for (var index = 0; index < this._animatables.length; index++) {
  50953. var animatable = this._animatables[index];
  50954. animatable.goToFrame(frame);
  50955. }
  50956. return this;
  50957. };
  50958. /**
  50959. * Dispose all associated resources
  50960. */
  50961. AnimationGroup.prototype.dispose = function () {
  50962. this._targetedAnimations = [];
  50963. this._animatables = [];
  50964. var index = this._scene.animationGroups.indexOf(this);
  50965. if (index > -1) {
  50966. this._scene.animationGroups.splice(index, 1);
  50967. }
  50968. };
  50969. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50970. // animatable should be taken out of the array
  50971. var idx = this._animatables.indexOf(animatable);
  50972. if (idx > -1) {
  50973. this._animatables.splice(idx, 1);
  50974. }
  50975. // all animatables were removed? animation group ended!
  50976. if (this._animatables.length === 0) {
  50977. this._isStarted = false;
  50978. this.onAnimationGroupEndObservable.notifyObservers(this);
  50979. }
  50980. };
  50981. // Statics
  50982. /**
  50983. * Returns a new AnimationGroup object parsed from the source provided.
  50984. * @param parsedAnimationGroup defines the source
  50985. * @param scene defines the scene that will receive the animationGroup
  50986. * @returns a new AnimationGroup
  50987. */
  50988. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50989. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50990. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50991. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50992. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50993. var id = targetedAnimation.targetId;
  50994. var targetNode = scene.getNodeByID(id);
  50995. if (targetNode != null)
  50996. animationGroup.addTargetedAnimation(animation, targetNode);
  50997. }
  50998. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50999. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51000. return animationGroup;
  51001. };
  51002. /**
  51003. * Returns the string "AnimationGroup"
  51004. * @returns "AnimationGroup"
  51005. */
  51006. AnimationGroup.prototype.getClassName = function () {
  51007. return "AnimationGroup";
  51008. };
  51009. /**
  51010. * Creates a detailled string about the object
  51011. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51012. * @returns a string representing the object
  51013. */
  51014. AnimationGroup.prototype.toString = function (fullDetails) {
  51015. var ret = "Name: " + this.name;
  51016. ret += ", type: " + this.getClassName();
  51017. if (fullDetails) {
  51018. ret += ", from: " + this._from;
  51019. ret += ", to: " + this._to;
  51020. ret += ", isStarted: " + this._isStarted;
  51021. ret += ", speedRatio: " + this._speedRatio;
  51022. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51023. ret += ", animatables length: " + this._animatables;
  51024. }
  51025. return ret;
  51026. };
  51027. return AnimationGroup;
  51028. }());
  51029. BABYLON.AnimationGroup = AnimationGroup;
  51030. })(BABYLON || (BABYLON = {}));
  51031. //# sourceMappingURL=babylon.animationGroup.js.map
  51032. var BABYLON;
  51033. (function (BABYLON) {
  51034. // Static values to help the garbage collector
  51035. // Quaternion
  51036. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51037. // Vector3
  51038. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51039. // Vector2
  51040. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51041. // Size
  51042. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51043. // Color3
  51044. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51045. /**
  51046. * Defines a runtime animation
  51047. */
  51048. var RuntimeAnimation = /** @class */ (function () {
  51049. /**
  51050. * Create a new RuntimeAnimation object
  51051. * @param target defines the target of the animation
  51052. * @param animation defines the source animation object
  51053. * @param scene defines the hosting scene
  51054. * @param host defines the initiating Animatable
  51055. */
  51056. function RuntimeAnimation(target, animation, scene, host) {
  51057. var _this = this;
  51058. this._events = new Array();
  51059. /**
  51060. * The current frame of the runtime animation
  51061. */
  51062. this._currentFrame = 0;
  51063. /**
  51064. * The original value of the runtime animation
  51065. */
  51066. this._originalValue = new Array();
  51067. /**
  51068. * The offsets cache of the runtime animation
  51069. */
  51070. this._offsetsCache = {};
  51071. /**
  51072. * The high limits cache of the runtime animation
  51073. */
  51074. this._highLimitsCache = {};
  51075. /**
  51076. * Specifies if the runtime animation has been stopped
  51077. */
  51078. this._stopped = false;
  51079. /**
  51080. * The blending factor of the runtime animation
  51081. */
  51082. this._blendingFactor = 0;
  51083. /**
  51084. * The target path of the runtime animation
  51085. */
  51086. this._targetPath = "";
  51087. /**
  51088. * The weight of the runtime animation
  51089. */
  51090. this._weight = 1.0;
  51091. /**
  51092. * The ratio offset of the runtime animation
  51093. */
  51094. this._ratioOffset = 0;
  51095. /**
  51096. * The previous delay of the runtime animation
  51097. */
  51098. this._previousDelay = 0;
  51099. /**
  51100. * The previous ratio of the runtime animation
  51101. */
  51102. this._previousRatio = 0;
  51103. this._animation = animation;
  51104. this._target = target;
  51105. this._scene = scene;
  51106. this._host = host;
  51107. animation._runtimeAnimations.push(this);
  51108. // Cloning events locally
  51109. var events = animation.getEvents();
  51110. if (events && events.length > 0) {
  51111. events.forEach(function (e) {
  51112. _this._events.push(e._clone());
  51113. });
  51114. }
  51115. }
  51116. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51117. /**
  51118. * Gets the current frame of the runtime animation
  51119. */
  51120. get: function () {
  51121. return this._currentFrame;
  51122. },
  51123. enumerable: true,
  51124. configurable: true
  51125. });
  51126. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51127. /**
  51128. * Gets the weight of the runtime animation
  51129. */
  51130. get: function () {
  51131. return this._weight;
  51132. },
  51133. enumerable: true,
  51134. configurable: true
  51135. });
  51136. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51137. /**
  51138. * Gets the current value of the runtime animation
  51139. */
  51140. get: function () {
  51141. return this._currentValue;
  51142. },
  51143. enumerable: true,
  51144. configurable: true
  51145. });
  51146. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51147. /**
  51148. * Gets the target path of the runtime animation
  51149. */
  51150. get: function () {
  51151. return this._targetPath;
  51152. },
  51153. enumerable: true,
  51154. configurable: true
  51155. });
  51156. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51157. /**
  51158. * Gets the actual target of the runtime animation
  51159. */
  51160. get: function () {
  51161. return this._activeTarget;
  51162. },
  51163. enumerable: true,
  51164. configurable: true
  51165. });
  51166. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51167. /**
  51168. * Gets the animation from the runtime animation
  51169. */
  51170. get: function () {
  51171. return this._animation;
  51172. },
  51173. enumerable: true,
  51174. configurable: true
  51175. });
  51176. /**
  51177. * Resets the runtime animation to the beginning
  51178. * @param restoreOriginal defines whether to restore the target property to the original value
  51179. */
  51180. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51181. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51182. if (restoreOriginal) {
  51183. if (this._target instanceof Array) {
  51184. var index = 0;
  51185. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51186. var target = _a[_i];
  51187. if (this._originalValue[index] !== undefined) {
  51188. this._setValue(target, this._originalValue[index], -1);
  51189. }
  51190. index++;
  51191. }
  51192. }
  51193. else {
  51194. if (this._originalValue[0] !== undefined) {
  51195. this._setValue(this._target, this._originalValue[0], -1);
  51196. }
  51197. }
  51198. }
  51199. this._offsetsCache = {};
  51200. this._highLimitsCache = {};
  51201. this._currentFrame = 0;
  51202. this._blendingFactor = 0;
  51203. this._originalValue = new Array();
  51204. // Events
  51205. for (var index = 0; index < this._events.length; index++) {
  51206. this._events[index].isDone = false;
  51207. }
  51208. };
  51209. /**
  51210. * Specifies if the runtime animation is stopped
  51211. * @returns Boolean specifying if the runtime animation is stopped
  51212. */
  51213. RuntimeAnimation.prototype.isStopped = function () {
  51214. return this._stopped;
  51215. };
  51216. /**
  51217. * Disposes of the runtime animation
  51218. */
  51219. RuntimeAnimation.prototype.dispose = function () {
  51220. var index = this._animation.runtimeAnimations.indexOf(this);
  51221. if (index > -1) {
  51222. this._animation.runtimeAnimations.splice(index, 1);
  51223. }
  51224. };
  51225. /**
  51226. * Interpolates the animation from the current frame
  51227. * @param currentFrame The frame to interpolate the animation to
  51228. * @param repeatCount The number of times that the animation should loop
  51229. * @param loopMode The type of looping mode to use
  51230. * @param offsetValue Animation offset value
  51231. * @param highLimitValue The high limit value
  51232. * @returns The interpolated value
  51233. */
  51234. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51235. this._currentFrame = currentFrame;
  51236. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51237. this._workValue = BABYLON.Matrix.Zero();
  51238. }
  51239. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51240. };
  51241. /**
  51242. * Apply the interpolated value to the target
  51243. * @param currentValue defines the value computed by the animation
  51244. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51245. */
  51246. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51247. if (weight === void 0) { weight = 1.0; }
  51248. if (this._target instanceof Array) {
  51249. var index = 0;
  51250. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51251. var target = _a[_i];
  51252. this._setValue(target, currentValue, weight, index);
  51253. index++;
  51254. }
  51255. }
  51256. else {
  51257. this._setValue(this._target, currentValue, weight);
  51258. }
  51259. };
  51260. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51261. if (targetIndex === void 0) { targetIndex = 0; }
  51262. // Set value
  51263. var path;
  51264. var destination;
  51265. var targetPropertyPath = this._animation.targetPropertyPath;
  51266. if (targetPropertyPath.length > 1) {
  51267. var property = target[targetPropertyPath[0]];
  51268. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51269. property = property[targetPropertyPath[index]];
  51270. }
  51271. path = targetPropertyPath[targetPropertyPath.length - 1];
  51272. destination = property;
  51273. }
  51274. else {
  51275. path = targetPropertyPath[0];
  51276. destination = target;
  51277. }
  51278. this._targetPath = path;
  51279. this._activeTarget = destination;
  51280. this._weight = weight;
  51281. if (this._originalValue[targetIndex] === undefined) {
  51282. var originalValue = void 0;
  51283. if (destination.getRestPose && path === "_matrix") { // For bones
  51284. originalValue = destination.getRestPose();
  51285. }
  51286. else {
  51287. originalValue = destination[path];
  51288. }
  51289. if (originalValue && originalValue.clone) {
  51290. this._originalValue[targetIndex] = originalValue.clone();
  51291. }
  51292. else {
  51293. this._originalValue[targetIndex] = originalValue;
  51294. }
  51295. }
  51296. // Blending
  51297. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51298. if (enableBlending && this._blendingFactor <= 1.0) {
  51299. if (!this._originalBlendValue) {
  51300. var originalValue = destination[path];
  51301. if (originalValue.clone) {
  51302. this._originalBlendValue = originalValue.clone();
  51303. }
  51304. else {
  51305. this._originalBlendValue = originalValue;
  51306. }
  51307. }
  51308. if (this._originalBlendValue.m) { // Matrix
  51309. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51310. if (this._currentValue) {
  51311. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51312. }
  51313. else {
  51314. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51315. }
  51316. }
  51317. else {
  51318. if (this._currentValue) {
  51319. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51320. }
  51321. else {
  51322. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51323. }
  51324. }
  51325. }
  51326. else {
  51327. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51328. }
  51329. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51330. this._blendingFactor += blendingSpeed;
  51331. }
  51332. else {
  51333. this._currentValue = currentValue;
  51334. }
  51335. if (weight !== -1.0) {
  51336. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51337. }
  51338. else {
  51339. destination[path] = this._currentValue;
  51340. }
  51341. if (target.markAsDirty) {
  51342. target.markAsDirty(this._animation.targetProperty);
  51343. }
  51344. };
  51345. /**
  51346. * Gets the loop pmode of the runtime animation
  51347. * @returns Loop Mode
  51348. */
  51349. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51350. if (this._target && this._target.animationPropertiesOverride) {
  51351. return this._target.animationPropertiesOverride.loopMode;
  51352. }
  51353. return this._animation.loopMode;
  51354. };
  51355. /**
  51356. * Move the current animation to a given frame
  51357. * @param frame defines the frame to move to
  51358. */
  51359. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51360. var keys = this._animation.getKeys();
  51361. if (frame < keys[0].frame) {
  51362. frame = keys[0].frame;
  51363. }
  51364. else if (frame > keys[keys.length - 1].frame) {
  51365. frame = keys[keys.length - 1].frame;
  51366. }
  51367. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51368. this.setValue(currentValue, -1);
  51369. };
  51370. /**
  51371. * @hidden Internal use only
  51372. */
  51373. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51374. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51375. this._ratioOffset = this._previousRatio - newRatio;
  51376. };
  51377. /**
  51378. * Execute the current animation
  51379. * @param delay defines the delay to add to the current frame
  51380. * @param from defines the lower bound of the animation range
  51381. * @param to defines the upper bound of the animation range
  51382. * @param loop defines if the current animation must loop
  51383. * @param speedRatio defines the current speed ratio
  51384. * @param weight defines the weight of the animation (default is -1 so no weight)
  51385. * @returns a boolean indicating if the animation is running
  51386. */
  51387. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51388. if (weight === void 0) { weight = -1.0; }
  51389. var targetPropertyPath = this._animation.targetPropertyPath;
  51390. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51391. this._stopped = true;
  51392. return false;
  51393. }
  51394. var returnValue = true;
  51395. var keys = this._animation.getKeys();
  51396. // Adding a start key at frame 0 if missing
  51397. if (keys[0].frame !== 0) {
  51398. var newKey = { frame: 0, value: keys[0].value };
  51399. keys.splice(0, 0, newKey);
  51400. }
  51401. // Adding a duplicate key when there is only one key at frame zero
  51402. else if (keys.length === 1) {
  51403. var newKey = { frame: 0.001, value: keys[0].value };
  51404. keys.push(newKey);
  51405. }
  51406. // Check limits
  51407. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51408. from = keys[0].frame;
  51409. }
  51410. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51411. to = keys[keys.length - 1].frame;
  51412. }
  51413. //to and from cannot be the same key
  51414. if (from === to) {
  51415. if (from > keys[0].frame) {
  51416. from--;
  51417. }
  51418. else if (to < keys[keys.length - 1].frame) {
  51419. to++;
  51420. }
  51421. }
  51422. // Compute ratio
  51423. var range = to - from;
  51424. var offsetValue;
  51425. // ratio represents the frame delta between from and to
  51426. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51427. var highLimitValue = 0;
  51428. this._previousDelay = delay;
  51429. this._previousRatio = ratio;
  51430. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51431. returnValue = false;
  51432. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51433. }
  51434. else {
  51435. // Get max value if required
  51436. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51437. var keyOffset = to.toString() + from.toString();
  51438. if (!this._offsetsCache[keyOffset]) {
  51439. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51440. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51441. switch (this._animation.dataType) {
  51442. // Float
  51443. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51444. this._offsetsCache[keyOffset] = toValue - fromValue;
  51445. break;
  51446. // Quaternion
  51447. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51449. break;
  51450. // Vector3
  51451. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51453. // Vector2
  51454. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51455. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51456. // Size
  51457. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51458. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51459. // Color3
  51460. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51462. default:
  51463. break;
  51464. }
  51465. this._highLimitsCache[keyOffset] = toValue;
  51466. }
  51467. highLimitValue = this._highLimitsCache[keyOffset];
  51468. offsetValue = this._offsetsCache[keyOffset];
  51469. }
  51470. }
  51471. if (offsetValue === undefined) {
  51472. switch (this._animation.dataType) {
  51473. // Float
  51474. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51475. offsetValue = 0;
  51476. break;
  51477. // Quaternion
  51478. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51479. offsetValue = _staticOffsetValueQuaternion;
  51480. break;
  51481. // Vector3
  51482. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51483. offsetValue = _staticOffsetValueVector3;
  51484. break;
  51485. // Vector2
  51486. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51487. offsetValue = _staticOffsetValueVector2;
  51488. break;
  51489. // Size
  51490. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51491. offsetValue = _staticOffsetValueSize;
  51492. break;
  51493. // Color3
  51494. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51495. offsetValue = _staticOffsetValueColor3;
  51496. }
  51497. }
  51498. // Compute value
  51499. var repeatCount = (ratio / range) >> 0;
  51500. var currentFrame = returnValue ? from + ratio % range : to;
  51501. // Need to normalize?
  51502. if (this._host && this._host.syncRoot) {
  51503. var syncRoot = this._host.syncRoot;
  51504. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51505. currentFrame = from + (to - from) * hostNormalizedFrame;
  51506. }
  51507. // Reset events if looping
  51508. var events = this._events;
  51509. if (range > 0 && this.currentFrame > currentFrame ||
  51510. range < 0 && this.currentFrame < currentFrame) {
  51511. // Need to reset animation events
  51512. for (var index = 0; index < events.length; index++) {
  51513. if (!events[index].onlyOnce) {
  51514. // reset event, the animation is looping
  51515. events[index].isDone = false;
  51516. }
  51517. }
  51518. }
  51519. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51520. // Set value
  51521. this.setValue(currentValue, weight);
  51522. // Check events
  51523. for (var index = 0; index < events.length; index++) {
  51524. // Make sure current frame has passed event frame and that event frame is within the current range
  51525. // Also, handle both forward and reverse animations
  51526. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51527. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51528. var event = events[index];
  51529. if (!event.isDone) {
  51530. // If event should be done only once, remove it.
  51531. if (event.onlyOnce) {
  51532. events.splice(index, 1);
  51533. index--;
  51534. }
  51535. event.isDone = true;
  51536. event.action(currentFrame);
  51537. } // Don't do anything if the event has already be done.
  51538. }
  51539. }
  51540. if (!returnValue) {
  51541. this._stopped = true;
  51542. }
  51543. return returnValue;
  51544. };
  51545. return RuntimeAnimation;
  51546. }());
  51547. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51548. })(BABYLON || (BABYLON = {}));
  51549. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51550. var BABYLON;
  51551. (function (BABYLON) {
  51552. /**
  51553. * Class used to store an actual running animation
  51554. */
  51555. var Animatable = /** @class */ (function () {
  51556. /**
  51557. * Creates a new Animatable
  51558. * @param scene defines the hosting scene
  51559. * @param target defines the target object
  51560. * @param fromFrame defines the starting frame number (default is 0)
  51561. * @param toFrame defines the ending frame number (default is 100)
  51562. * @param loopAnimation defines if the animation must loop (default is false)
  51563. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51564. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51565. * @param animations defines a group of animation to add to the new Animatable
  51566. */
  51567. function Animatable(scene,
  51568. /** defines the target object */
  51569. target,
  51570. /** defines the starting frame number (default is 0) */
  51571. fromFrame,
  51572. /** defines the ending frame number (default is 100) */
  51573. toFrame,
  51574. /** defines if the animation must loop (default is false) */
  51575. loopAnimation, speedRatio,
  51576. /** defines a callback to call when animation ends if it is not looping */
  51577. onAnimationEnd, animations) {
  51578. if (fromFrame === void 0) { fromFrame = 0; }
  51579. if (toFrame === void 0) { toFrame = 100; }
  51580. if (loopAnimation === void 0) { loopAnimation = false; }
  51581. if (speedRatio === void 0) { speedRatio = 1.0; }
  51582. this.target = target;
  51583. this.fromFrame = fromFrame;
  51584. this.toFrame = toFrame;
  51585. this.loopAnimation = loopAnimation;
  51586. this.onAnimationEnd = onAnimationEnd;
  51587. this._localDelayOffset = null;
  51588. this._pausedDelay = null;
  51589. this._runtimeAnimations = new Array();
  51590. this._paused = false;
  51591. this._speedRatio = 1;
  51592. this._weight = -1.0;
  51593. /**
  51594. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51595. * This will only apply for non looping animation (default is true)
  51596. */
  51597. this.disposeOnEnd = true;
  51598. /**
  51599. * Gets a boolean indicating if the animation has started
  51600. */
  51601. this.animationStarted = false;
  51602. /**
  51603. * Observer raised when the animation ends
  51604. */
  51605. this.onAnimationEndObservable = new BABYLON.Observable();
  51606. this._scene = scene;
  51607. if (animations) {
  51608. this.appendAnimations(target, animations);
  51609. }
  51610. this._speedRatio = speedRatio;
  51611. scene._activeAnimatables.push(this);
  51612. }
  51613. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51614. /**
  51615. * Gets the root Animatable used to synchronize and normalize animations
  51616. */
  51617. get: function () {
  51618. return this._syncRoot;
  51619. },
  51620. enumerable: true,
  51621. configurable: true
  51622. });
  51623. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51624. /**
  51625. * Gets the current frame of the first RuntimeAnimation
  51626. * Used to synchronize Animatables
  51627. */
  51628. get: function () {
  51629. if (this._runtimeAnimations.length === 0) {
  51630. return 0;
  51631. }
  51632. return this._runtimeAnimations[0].currentFrame;
  51633. },
  51634. enumerable: true,
  51635. configurable: true
  51636. });
  51637. Object.defineProperty(Animatable.prototype, "weight", {
  51638. /**
  51639. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51640. */
  51641. get: function () {
  51642. return this._weight;
  51643. },
  51644. set: function (value) {
  51645. if (value === -1) { // -1 is ok and means no weight
  51646. this._weight = -1;
  51647. return;
  51648. }
  51649. // Else weight must be in [0, 1] range
  51650. this._weight = Math.min(Math.max(value, 0), 1.0);
  51651. },
  51652. enumerable: true,
  51653. configurable: true
  51654. });
  51655. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51656. /**
  51657. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51658. */
  51659. get: function () {
  51660. return this._speedRatio;
  51661. },
  51662. set: function (value) {
  51663. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51664. var animation = this._runtimeAnimations[index];
  51665. animation._prepareForSpeedRatioChange(value);
  51666. }
  51667. this._speedRatio = value;
  51668. },
  51669. enumerable: true,
  51670. configurable: true
  51671. });
  51672. // Methods
  51673. /**
  51674. * Synchronize and normalize current Animatable with a source Animatable
  51675. * This is useful when using animation weights and when animations are not of the same length
  51676. * @param root defines the root Animatable to synchronize with
  51677. * @returns the current Animatable
  51678. */
  51679. Animatable.prototype.syncWith = function (root) {
  51680. this._syncRoot = root;
  51681. if (root) {
  51682. // Make sure this animatable will animate after the root
  51683. var index = this._scene._activeAnimatables.indexOf(this);
  51684. if (index > -1) {
  51685. this._scene._activeAnimatables.splice(index, 1);
  51686. this._scene._activeAnimatables.push(this);
  51687. }
  51688. }
  51689. return this;
  51690. };
  51691. /**
  51692. * Gets the list of runtime animations
  51693. * @returns an array of RuntimeAnimation
  51694. */
  51695. Animatable.prototype.getAnimations = function () {
  51696. return this._runtimeAnimations;
  51697. };
  51698. /**
  51699. * Adds more animations to the current animatable
  51700. * @param target defines the target of the animations
  51701. * @param animations defines the new animations to add
  51702. */
  51703. Animatable.prototype.appendAnimations = function (target, animations) {
  51704. for (var index = 0; index < animations.length; index++) {
  51705. var animation = animations[index];
  51706. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51707. }
  51708. };
  51709. /**
  51710. * Gets the source animation for a specific property
  51711. * @param property defines the propertyu to look for
  51712. * @returns null or the source animation for the given property
  51713. */
  51714. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51715. var runtimeAnimations = this._runtimeAnimations;
  51716. for (var index = 0; index < runtimeAnimations.length; index++) {
  51717. if (runtimeAnimations[index].animation.targetProperty === property) {
  51718. return runtimeAnimations[index].animation;
  51719. }
  51720. }
  51721. return null;
  51722. };
  51723. /**
  51724. * Gets the runtime animation for a specific property
  51725. * @param property defines the propertyu to look for
  51726. * @returns null or the runtime animation for the given property
  51727. */
  51728. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51729. var runtimeAnimations = this._runtimeAnimations;
  51730. for (var index = 0; index < runtimeAnimations.length; index++) {
  51731. if (runtimeAnimations[index].animation.targetProperty === property) {
  51732. return runtimeAnimations[index];
  51733. }
  51734. }
  51735. return null;
  51736. };
  51737. /**
  51738. * Resets the animatable to its original state
  51739. */
  51740. Animatable.prototype.reset = function () {
  51741. var runtimeAnimations = this._runtimeAnimations;
  51742. for (var index = 0; index < runtimeAnimations.length; index++) {
  51743. runtimeAnimations[index].reset(true);
  51744. }
  51745. this._localDelayOffset = null;
  51746. this._pausedDelay = null;
  51747. };
  51748. /**
  51749. * Allows the animatable to blend with current running animations
  51750. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51751. * @param blendingSpeed defines the blending speed to use
  51752. */
  51753. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51754. var runtimeAnimations = this._runtimeAnimations;
  51755. for (var index = 0; index < runtimeAnimations.length; index++) {
  51756. runtimeAnimations[index].animation.enableBlending = true;
  51757. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51758. }
  51759. };
  51760. /**
  51761. * Disable animation blending
  51762. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51763. */
  51764. Animatable.prototype.disableBlending = function () {
  51765. var runtimeAnimations = this._runtimeAnimations;
  51766. for (var index = 0; index < runtimeAnimations.length; index++) {
  51767. runtimeAnimations[index].animation.enableBlending = false;
  51768. }
  51769. };
  51770. /**
  51771. * Jump directly to a given frame
  51772. * @param frame defines the frame to jump to
  51773. */
  51774. Animatable.prototype.goToFrame = function (frame) {
  51775. var runtimeAnimations = this._runtimeAnimations;
  51776. if (runtimeAnimations[0]) {
  51777. var fps = runtimeAnimations[0].animation.framePerSecond;
  51778. var currentFrame = runtimeAnimations[0].currentFrame;
  51779. var adjustTime = frame - currentFrame;
  51780. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51781. if (this._localDelayOffset === null) {
  51782. this._localDelayOffset = 0;
  51783. }
  51784. this._localDelayOffset -= delay;
  51785. }
  51786. for (var index = 0; index < runtimeAnimations.length; index++) {
  51787. runtimeAnimations[index].goToFrame(frame);
  51788. }
  51789. };
  51790. /**
  51791. * Pause the animation
  51792. */
  51793. Animatable.prototype.pause = function () {
  51794. if (this._paused) {
  51795. return;
  51796. }
  51797. this._paused = true;
  51798. };
  51799. /**
  51800. * Restart the animation
  51801. */
  51802. Animatable.prototype.restart = function () {
  51803. this._paused = false;
  51804. };
  51805. Animatable.prototype._raiseOnAnimationEnd = function () {
  51806. if (this.onAnimationEnd) {
  51807. this.onAnimationEnd();
  51808. }
  51809. this.onAnimationEndObservable.notifyObservers(this);
  51810. };
  51811. /**
  51812. * Stop and delete the current animation
  51813. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51814. * @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)
  51815. */
  51816. Animatable.prototype.stop = function (animationName, targetMask) {
  51817. if (animationName || targetMask) {
  51818. var idx = this._scene._activeAnimatables.indexOf(this);
  51819. if (idx > -1) {
  51820. var runtimeAnimations = this._runtimeAnimations;
  51821. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51822. var runtimeAnimation = runtimeAnimations[index];
  51823. if (animationName && runtimeAnimation.animation.name != animationName) {
  51824. continue;
  51825. }
  51826. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51827. continue;
  51828. }
  51829. runtimeAnimation.dispose();
  51830. runtimeAnimations.splice(index, 1);
  51831. }
  51832. if (runtimeAnimations.length == 0) {
  51833. this._scene._activeAnimatables.splice(idx, 1);
  51834. this._raiseOnAnimationEnd();
  51835. }
  51836. }
  51837. }
  51838. else {
  51839. var index = this._scene._activeAnimatables.indexOf(this);
  51840. if (index > -1) {
  51841. this._scene._activeAnimatables.splice(index, 1);
  51842. var runtimeAnimations = this._runtimeAnimations;
  51843. for (var index = 0; index < runtimeAnimations.length; index++) {
  51844. runtimeAnimations[index].dispose();
  51845. }
  51846. this._raiseOnAnimationEnd();
  51847. }
  51848. }
  51849. };
  51850. /**
  51851. * Wait asynchronously for the animation to end
  51852. * @returns a promise which will be fullfilled when the animation ends
  51853. */
  51854. Animatable.prototype.waitAsync = function () {
  51855. var _this = this;
  51856. return new Promise(function (resolve, reject) {
  51857. _this.onAnimationEndObservable.add(function () {
  51858. resolve(_this);
  51859. }, undefined, undefined, _this, true);
  51860. });
  51861. };
  51862. /** @hidden */
  51863. Animatable.prototype._animate = function (delay) {
  51864. if (this._paused) {
  51865. this.animationStarted = false;
  51866. if (this._pausedDelay === null) {
  51867. this._pausedDelay = delay;
  51868. }
  51869. return true;
  51870. }
  51871. if (this._localDelayOffset === null) {
  51872. this._localDelayOffset = delay;
  51873. this._pausedDelay = null;
  51874. }
  51875. else if (this._pausedDelay !== null) {
  51876. this._localDelayOffset += delay - this._pausedDelay;
  51877. this._pausedDelay = null;
  51878. }
  51879. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51880. return true;
  51881. }
  51882. // Animating
  51883. var running = false;
  51884. var runtimeAnimations = this._runtimeAnimations;
  51885. var index;
  51886. for (index = 0; index < runtimeAnimations.length; index++) {
  51887. var animation = runtimeAnimations[index];
  51888. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51889. running = running || isRunning;
  51890. }
  51891. this.animationStarted = running;
  51892. if (!running) {
  51893. if (this.disposeOnEnd) {
  51894. // Remove from active animatables
  51895. index = this._scene._activeAnimatables.indexOf(this);
  51896. this._scene._activeAnimatables.splice(index, 1);
  51897. // Dispose all runtime animations
  51898. for (index = 0; index < runtimeAnimations.length; index++) {
  51899. runtimeAnimations[index].dispose();
  51900. }
  51901. }
  51902. this._raiseOnAnimationEnd();
  51903. if (this.disposeOnEnd) {
  51904. this.onAnimationEnd = null;
  51905. this.onAnimationEndObservable.clear();
  51906. }
  51907. }
  51908. return running;
  51909. };
  51910. return Animatable;
  51911. }());
  51912. BABYLON.Animatable = Animatable;
  51913. })(BABYLON || (BABYLON = {}));
  51914. //# sourceMappingURL=babylon.animatable.js.map
  51915. var BABYLON;
  51916. (function (BABYLON) {
  51917. var EasingFunction = /** @class */ (function () {
  51918. function EasingFunction() {
  51919. // Properties
  51920. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51921. }
  51922. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51923. get: function () {
  51924. return EasingFunction._EASINGMODE_EASEIN;
  51925. },
  51926. enumerable: true,
  51927. configurable: true
  51928. });
  51929. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51930. get: function () {
  51931. return EasingFunction._EASINGMODE_EASEOUT;
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51937. get: function () {
  51938. return EasingFunction._EASINGMODE_EASEINOUT;
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51944. var n = Math.min(Math.max(easingMode, 0), 2);
  51945. this._easingMode = n;
  51946. };
  51947. EasingFunction.prototype.getEasingMode = function () {
  51948. return this._easingMode;
  51949. };
  51950. EasingFunction.prototype.easeInCore = function (gradient) {
  51951. throw new Error('You must implement this method');
  51952. };
  51953. EasingFunction.prototype.ease = function (gradient) {
  51954. switch (this._easingMode) {
  51955. case EasingFunction.EASINGMODE_EASEIN:
  51956. return this.easeInCore(gradient);
  51957. case EasingFunction.EASINGMODE_EASEOUT:
  51958. return (1 - this.easeInCore(1 - gradient));
  51959. }
  51960. if (gradient >= 0.5) {
  51961. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51962. }
  51963. return (this.easeInCore(gradient * 2) * 0.5);
  51964. };
  51965. //Statics
  51966. EasingFunction._EASINGMODE_EASEIN = 0;
  51967. EasingFunction._EASINGMODE_EASEOUT = 1;
  51968. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51969. return EasingFunction;
  51970. }());
  51971. BABYLON.EasingFunction = EasingFunction;
  51972. var CircleEase = /** @class */ (function (_super) {
  51973. __extends(CircleEase, _super);
  51974. function CircleEase() {
  51975. return _super !== null && _super.apply(this, arguments) || this;
  51976. }
  51977. CircleEase.prototype.easeInCore = function (gradient) {
  51978. gradient = Math.max(0, Math.min(1, gradient));
  51979. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51980. };
  51981. return CircleEase;
  51982. }(EasingFunction));
  51983. BABYLON.CircleEase = CircleEase;
  51984. var BackEase = /** @class */ (function (_super) {
  51985. __extends(BackEase, _super);
  51986. function BackEase(amplitude) {
  51987. if (amplitude === void 0) { amplitude = 1; }
  51988. var _this = _super.call(this) || this;
  51989. _this.amplitude = amplitude;
  51990. return _this;
  51991. }
  51992. BackEase.prototype.easeInCore = function (gradient) {
  51993. var num = Math.max(0, this.amplitude);
  51994. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51995. };
  51996. return BackEase;
  51997. }(EasingFunction));
  51998. BABYLON.BackEase = BackEase;
  51999. var BounceEase = /** @class */ (function (_super) {
  52000. __extends(BounceEase, _super);
  52001. function BounceEase(bounces, bounciness) {
  52002. if (bounces === void 0) { bounces = 3; }
  52003. if (bounciness === void 0) { bounciness = 2; }
  52004. var _this = _super.call(this) || this;
  52005. _this.bounces = bounces;
  52006. _this.bounciness = bounciness;
  52007. return _this;
  52008. }
  52009. BounceEase.prototype.easeInCore = function (gradient) {
  52010. var y = Math.max(0.0, this.bounces);
  52011. var bounciness = this.bounciness;
  52012. if (bounciness <= 1.0) {
  52013. bounciness = 1.001;
  52014. }
  52015. var num9 = Math.pow(bounciness, y);
  52016. var num5 = 1.0 - bounciness;
  52017. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52018. var num15 = gradient * num4;
  52019. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52020. var num3 = Math.floor(num65);
  52021. var num13 = num3 + 1.0;
  52022. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52023. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52024. var num7 = (num8 + num12) * 0.5;
  52025. var num6 = gradient - num7;
  52026. var num2 = num7 - num8;
  52027. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52028. };
  52029. return BounceEase;
  52030. }(EasingFunction));
  52031. BABYLON.BounceEase = BounceEase;
  52032. var CubicEase = /** @class */ (function (_super) {
  52033. __extends(CubicEase, _super);
  52034. function CubicEase() {
  52035. return _super !== null && _super.apply(this, arguments) || this;
  52036. }
  52037. CubicEase.prototype.easeInCore = function (gradient) {
  52038. return (gradient * gradient * gradient);
  52039. };
  52040. return CubicEase;
  52041. }(EasingFunction));
  52042. BABYLON.CubicEase = CubicEase;
  52043. var ElasticEase = /** @class */ (function (_super) {
  52044. __extends(ElasticEase, _super);
  52045. function ElasticEase(oscillations, springiness) {
  52046. if (oscillations === void 0) { oscillations = 3; }
  52047. if (springiness === void 0) { springiness = 3; }
  52048. var _this = _super.call(this) || this;
  52049. _this.oscillations = oscillations;
  52050. _this.springiness = springiness;
  52051. return _this;
  52052. }
  52053. ElasticEase.prototype.easeInCore = function (gradient) {
  52054. var num2;
  52055. var num3 = Math.max(0.0, this.oscillations);
  52056. var num = Math.max(0.0, this.springiness);
  52057. if (num == 0) {
  52058. num2 = gradient;
  52059. }
  52060. else {
  52061. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52062. }
  52063. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52064. };
  52065. return ElasticEase;
  52066. }(EasingFunction));
  52067. BABYLON.ElasticEase = ElasticEase;
  52068. var ExponentialEase = /** @class */ (function (_super) {
  52069. __extends(ExponentialEase, _super);
  52070. function ExponentialEase(exponent) {
  52071. if (exponent === void 0) { exponent = 2; }
  52072. var _this = _super.call(this) || this;
  52073. _this.exponent = exponent;
  52074. return _this;
  52075. }
  52076. ExponentialEase.prototype.easeInCore = function (gradient) {
  52077. if (this.exponent <= 0) {
  52078. return gradient;
  52079. }
  52080. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52081. };
  52082. return ExponentialEase;
  52083. }(EasingFunction));
  52084. BABYLON.ExponentialEase = ExponentialEase;
  52085. var PowerEase = /** @class */ (function (_super) {
  52086. __extends(PowerEase, _super);
  52087. function PowerEase(power) {
  52088. if (power === void 0) { power = 2; }
  52089. var _this = _super.call(this) || this;
  52090. _this.power = power;
  52091. return _this;
  52092. }
  52093. PowerEase.prototype.easeInCore = function (gradient) {
  52094. var y = Math.max(0.0, this.power);
  52095. return Math.pow(gradient, y);
  52096. };
  52097. return PowerEase;
  52098. }(EasingFunction));
  52099. BABYLON.PowerEase = PowerEase;
  52100. var QuadraticEase = /** @class */ (function (_super) {
  52101. __extends(QuadraticEase, _super);
  52102. function QuadraticEase() {
  52103. return _super !== null && _super.apply(this, arguments) || this;
  52104. }
  52105. QuadraticEase.prototype.easeInCore = function (gradient) {
  52106. return (gradient * gradient);
  52107. };
  52108. return QuadraticEase;
  52109. }(EasingFunction));
  52110. BABYLON.QuadraticEase = QuadraticEase;
  52111. var QuarticEase = /** @class */ (function (_super) {
  52112. __extends(QuarticEase, _super);
  52113. function QuarticEase() {
  52114. return _super !== null && _super.apply(this, arguments) || this;
  52115. }
  52116. QuarticEase.prototype.easeInCore = function (gradient) {
  52117. return (gradient * gradient * gradient * gradient);
  52118. };
  52119. return QuarticEase;
  52120. }(EasingFunction));
  52121. BABYLON.QuarticEase = QuarticEase;
  52122. var QuinticEase = /** @class */ (function (_super) {
  52123. __extends(QuinticEase, _super);
  52124. function QuinticEase() {
  52125. return _super !== null && _super.apply(this, arguments) || this;
  52126. }
  52127. QuinticEase.prototype.easeInCore = function (gradient) {
  52128. return (gradient * gradient * gradient * gradient * gradient);
  52129. };
  52130. return QuinticEase;
  52131. }(EasingFunction));
  52132. BABYLON.QuinticEase = QuinticEase;
  52133. var SineEase = /** @class */ (function (_super) {
  52134. __extends(SineEase, _super);
  52135. function SineEase() {
  52136. return _super !== null && _super.apply(this, arguments) || this;
  52137. }
  52138. SineEase.prototype.easeInCore = function (gradient) {
  52139. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52140. };
  52141. return SineEase;
  52142. }(EasingFunction));
  52143. BABYLON.SineEase = SineEase;
  52144. var BezierCurveEase = /** @class */ (function (_super) {
  52145. __extends(BezierCurveEase, _super);
  52146. function BezierCurveEase(x1, y1, x2, y2) {
  52147. if (x1 === void 0) { x1 = 0; }
  52148. if (y1 === void 0) { y1 = 0; }
  52149. if (x2 === void 0) { x2 = 1; }
  52150. if (y2 === void 0) { y2 = 1; }
  52151. var _this = _super.call(this) || this;
  52152. _this.x1 = x1;
  52153. _this.y1 = y1;
  52154. _this.x2 = x2;
  52155. _this.y2 = y2;
  52156. return _this;
  52157. }
  52158. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52159. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52160. };
  52161. return BezierCurveEase;
  52162. }(EasingFunction));
  52163. BABYLON.BezierCurveEase = BezierCurveEase;
  52164. })(BABYLON || (BABYLON = {}));
  52165. //# sourceMappingURL=babylon.easing.js.map
  52166. var BABYLON;
  52167. (function (BABYLON) {
  52168. /**
  52169. * A Condition applied to an Action
  52170. */
  52171. var Condition = /** @class */ (function () {
  52172. /**
  52173. * Creates a new Condition
  52174. * @param actionManager the manager of the action the condition is applied to
  52175. */
  52176. function Condition(actionManager) {
  52177. this._actionManager = actionManager;
  52178. }
  52179. /**
  52180. * Check if the current condition is valid
  52181. * @returns a boolean
  52182. */
  52183. Condition.prototype.isValid = function () {
  52184. return true;
  52185. };
  52186. /**
  52187. * Internal only
  52188. * @hidden
  52189. */
  52190. Condition.prototype._getProperty = function (propertyPath) {
  52191. return this._actionManager._getProperty(propertyPath);
  52192. };
  52193. /**
  52194. * Internal only
  52195. * @hidden
  52196. */
  52197. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52198. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52199. };
  52200. /**
  52201. * Serialize placeholder for child classes
  52202. * @returns the serialized object
  52203. */
  52204. Condition.prototype.serialize = function () {
  52205. };
  52206. /**
  52207. * Internal only
  52208. * @hidden
  52209. */
  52210. Condition.prototype._serialize = function (serializedCondition) {
  52211. return {
  52212. type: 2,
  52213. children: [],
  52214. name: serializedCondition.name,
  52215. properties: serializedCondition.properties
  52216. };
  52217. };
  52218. return Condition;
  52219. }());
  52220. BABYLON.Condition = Condition;
  52221. /**
  52222. * Defines specific conditional operators as extensions of Condition
  52223. */
  52224. var ValueCondition = /** @class */ (function (_super) {
  52225. __extends(ValueCondition, _super);
  52226. /**
  52227. * Creates a new ValueCondition
  52228. * @param actionManager manager for the action the condition applies to
  52229. * @param target for the action
  52230. * @param propertyPath path to specify the property of the target the conditional operator uses
  52231. * @param value the value compared by the conditional operator against the current value of the property
  52232. * @param operator the conditional operator, default ValueCondition.IsEqual
  52233. */
  52234. function ValueCondition(actionManager, target,
  52235. /** path to specify the property of the target the conditional operator uses */
  52236. propertyPath,
  52237. /** the value compared by the conditional operator against the current value of the property */
  52238. value,
  52239. /** the conditional operator, default ValueCondition.IsEqual */
  52240. operator) {
  52241. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52242. var _this = _super.call(this, actionManager) || this;
  52243. _this.propertyPath = propertyPath;
  52244. _this.value = value;
  52245. _this.operator = operator;
  52246. _this._target = target;
  52247. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52248. _this._property = _this._getProperty(_this.propertyPath);
  52249. return _this;
  52250. }
  52251. Object.defineProperty(ValueCondition, "IsEqual", {
  52252. /**
  52253. * returns the number for IsEqual
  52254. */
  52255. get: function () {
  52256. return ValueCondition._IsEqual;
  52257. },
  52258. enumerable: true,
  52259. configurable: true
  52260. });
  52261. Object.defineProperty(ValueCondition, "IsDifferent", {
  52262. /**
  52263. * Returns the number for IsDifferent
  52264. */
  52265. get: function () {
  52266. return ValueCondition._IsDifferent;
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(ValueCondition, "IsGreater", {
  52272. /**
  52273. * Returns the number for IsGreater
  52274. */
  52275. get: function () {
  52276. return ValueCondition._IsGreater;
  52277. },
  52278. enumerable: true,
  52279. configurable: true
  52280. });
  52281. Object.defineProperty(ValueCondition, "IsLesser", {
  52282. /**
  52283. * Returns the number for IsLesser
  52284. */
  52285. get: function () {
  52286. return ValueCondition._IsLesser;
  52287. },
  52288. enumerable: true,
  52289. configurable: true
  52290. });
  52291. /**
  52292. * Compares the given value with the property value for the specified conditional operator
  52293. * @returns the result of the comparison
  52294. */
  52295. ValueCondition.prototype.isValid = function () {
  52296. switch (this.operator) {
  52297. case ValueCondition.IsGreater:
  52298. return this._effectiveTarget[this._property] > this.value;
  52299. case ValueCondition.IsLesser:
  52300. return this._effectiveTarget[this._property] < this.value;
  52301. case ValueCondition.IsEqual:
  52302. case ValueCondition.IsDifferent:
  52303. var check;
  52304. if (this.value.equals) {
  52305. check = this.value.equals(this._effectiveTarget[this._property]);
  52306. }
  52307. else {
  52308. check = this.value === this._effectiveTarget[this._property];
  52309. }
  52310. return this.operator === ValueCondition.IsEqual ? check : !check;
  52311. }
  52312. return false;
  52313. };
  52314. /**
  52315. * Serialize the ValueCondition into a JSON compatible object
  52316. * @returns serialization object
  52317. */
  52318. ValueCondition.prototype.serialize = function () {
  52319. return this._serialize({
  52320. name: "ValueCondition",
  52321. properties: [
  52322. BABYLON.Action._GetTargetProperty(this._target),
  52323. { name: "propertyPath", value: this.propertyPath },
  52324. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52325. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52326. ]
  52327. });
  52328. };
  52329. /**
  52330. * Gets the name of the conditional operator for the ValueCondition
  52331. * @param operator the conditional operator
  52332. * @returns the name
  52333. */
  52334. ValueCondition.GetOperatorName = function (operator) {
  52335. switch (operator) {
  52336. case ValueCondition._IsEqual: return "IsEqual";
  52337. case ValueCondition._IsDifferent: return "IsDifferent";
  52338. case ValueCondition._IsGreater: return "IsGreater";
  52339. case ValueCondition._IsLesser: return "IsLesser";
  52340. default: return "";
  52341. }
  52342. };
  52343. /**
  52344. * Internal only
  52345. * @hidden
  52346. */
  52347. ValueCondition._IsEqual = 0;
  52348. /**
  52349. * Internal only
  52350. * @hidden
  52351. */
  52352. ValueCondition._IsDifferent = 1;
  52353. /**
  52354. * Internal only
  52355. * @hidden
  52356. */
  52357. ValueCondition._IsGreater = 2;
  52358. /**
  52359. * Internal only
  52360. * @hidden
  52361. */
  52362. ValueCondition._IsLesser = 3;
  52363. return ValueCondition;
  52364. }(Condition));
  52365. BABYLON.ValueCondition = ValueCondition;
  52366. /**
  52367. * Defines a predicate condition as an extension of Condition
  52368. */
  52369. var PredicateCondition = /** @class */ (function (_super) {
  52370. __extends(PredicateCondition, _super);
  52371. /**
  52372. * Creates a new PredicateCondition
  52373. * @param actionManager manager for the action the condition applies to
  52374. * @param predicate defines the predicate function used to validate the condition
  52375. */
  52376. function PredicateCondition(actionManager,
  52377. /** defines the predicate function used to validate the condition */
  52378. predicate) {
  52379. var _this = _super.call(this, actionManager) || this;
  52380. _this.predicate = predicate;
  52381. return _this;
  52382. }
  52383. /**
  52384. * @returns the validity of the predicate condition
  52385. */
  52386. PredicateCondition.prototype.isValid = function () {
  52387. return this.predicate();
  52388. };
  52389. return PredicateCondition;
  52390. }(Condition));
  52391. BABYLON.PredicateCondition = PredicateCondition;
  52392. /**
  52393. * Defines a state condition as an extension of Condition
  52394. */
  52395. var StateCondition = /** @class */ (function (_super) {
  52396. __extends(StateCondition, _super);
  52397. /**
  52398. * Creates a new StateCondition
  52399. * @param actionManager manager for the action the condition applies to
  52400. * @param target of the condition
  52401. * @param value to compare with target state
  52402. */
  52403. function StateCondition(actionManager, target, value) {
  52404. var _this = _super.call(this, actionManager) || this;
  52405. _this.value = value;
  52406. _this._target = target;
  52407. return _this;
  52408. }
  52409. /**
  52410. * @returns the validity of the state
  52411. */
  52412. StateCondition.prototype.isValid = function () {
  52413. return this._target.state === this.value;
  52414. };
  52415. /**
  52416. * Serialize the StateCondition into a JSON compatible object
  52417. * @returns serialization object
  52418. */
  52419. StateCondition.prototype.serialize = function () {
  52420. return this._serialize({
  52421. name: "StateCondition",
  52422. properties: [
  52423. BABYLON.Action._GetTargetProperty(this._target),
  52424. { name: "value", value: this.value }
  52425. ]
  52426. });
  52427. };
  52428. return StateCondition;
  52429. }(Condition));
  52430. BABYLON.StateCondition = StateCondition;
  52431. })(BABYLON || (BABYLON = {}));
  52432. //# sourceMappingURL=babylon.condition.js.map
  52433. var BABYLON;
  52434. (function (BABYLON) {
  52435. /**
  52436. * The action to be carried out following a trigger
  52437. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52438. */
  52439. var Action = /** @class */ (function () {
  52440. /**
  52441. * Creates a new Action
  52442. * @param triggerOptions the trigger, with or without parameters, for the action
  52443. * @param condition an optional determinant of action
  52444. */
  52445. function Action(
  52446. /** the trigger, with or without parameters, for the action */
  52447. triggerOptions, condition) {
  52448. this.triggerOptions = triggerOptions;
  52449. /**
  52450. * An event triggered prior to action being executed.
  52451. */
  52452. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52453. if (triggerOptions.parameter) {
  52454. this.trigger = triggerOptions.trigger;
  52455. this._triggerParameter = triggerOptions.parameter;
  52456. }
  52457. else if (triggerOptions.trigger) {
  52458. this.trigger = triggerOptions.trigger;
  52459. }
  52460. else {
  52461. this.trigger = triggerOptions;
  52462. }
  52463. this._nextActiveAction = this;
  52464. this._condition = condition;
  52465. }
  52466. /**
  52467. * Internal only
  52468. * @hidden
  52469. */
  52470. Action.prototype._prepare = function () {
  52471. };
  52472. /**
  52473. * Gets the trigger parameters
  52474. * @returns the trigger parameters
  52475. */
  52476. Action.prototype.getTriggerParameter = function () {
  52477. return this._triggerParameter;
  52478. };
  52479. /**
  52480. * Internal only - executes current action event
  52481. * @hidden
  52482. */
  52483. Action.prototype._executeCurrent = function (evt) {
  52484. if (this._nextActiveAction._condition) {
  52485. var condition = this._nextActiveAction._condition;
  52486. var currentRenderId = this._actionManager.getScene().getRenderId();
  52487. // We cache the current evaluation for the current frame
  52488. if (condition._evaluationId === currentRenderId) {
  52489. if (!condition._currentResult) {
  52490. return;
  52491. }
  52492. }
  52493. else {
  52494. condition._evaluationId = currentRenderId;
  52495. if (!condition.isValid()) {
  52496. condition._currentResult = false;
  52497. return;
  52498. }
  52499. condition._currentResult = true;
  52500. }
  52501. }
  52502. this.onBeforeExecuteObservable.notifyObservers(this);
  52503. this._nextActiveAction.execute(evt);
  52504. this.skipToNextActiveAction();
  52505. };
  52506. /**
  52507. * Execute placeholder for child classes
  52508. * @param evt optional action event
  52509. */
  52510. Action.prototype.execute = function (evt) {
  52511. };
  52512. /**
  52513. * Skips to next active action
  52514. */
  52515. Action.prototype.skipToNextActiveAction = function () {
  52516. if (this._nextActiveAction._child) {
  52517. if (!this._nextActiveAction._child._actionManager) {
  52518. this._nextActiveAction._child._actionManager = this._actionManager;
  52519. }
  52520. this._nextActiveAction = this._nextActiveAction._child;
  52521. }
  52522. else {
  52523. this._nextActiveAction = this;
  52524. }
  52525. };
  52526. /**
  52527. * Adds action to chain of actions, may be a DoNothingAction
  52528. * @param action defines the next action to execute
  52529. * @returns The action passed in
  52530. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52531. */
  52532. Action.prototype.then = function (action) {
  52533. this._child = action;
  52534. action._actionManager = this._actionManager;
  52535. action._prepare();
  52536. return action;
  52537. };
  52538. /**
  52539. * Internal only
  52540. * @hidden
  52541. */
  52542. Action.prototype._getProperty = function (propertyPath) {
  52543. return this._actionManager._getProperty(propertyPath);
  52544. };
  52545. /**
  52546. * Internal only
  52547. * @hidden
  52548. */
  52549. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52550. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52551. };
  52552. /**
  52553. * Serialize placeholder for child classes
  52554. * @param parent of child
  52555. * @returns the serialized object
  52556. */
  52557. Action.prototype.serialize = function (parent) {
  52558. };
  52559. /**
  52560. * Internal only called by serialize
  52561. * @hidden
  52562. */
  52563. Action.prototype._serialize = function (serializedAction, parent) {
  52564. var serializationObject = {
  52565. type: 1,
  52566. children: [],
  52567. name: serializedAction.name,
  52568. properties: serializedAction.properties || []
  52569. };
  52570. // Serialize child
  52571. if (this._child) {
  52572. this._child.serialize(serializationObject);
  52573. }
  52574. // Check if "this" has a condition
  52575. if (this._condition) {
  52576. var serializedCondition = this._condition.serialize();
  52577. serializedCondition.children.push(serializationObject);
  52578. if (parent) {
  52579. parent.children.push(serializedCondition);
  52580. }
  52581. return serializedCondition;
  52582. }
  52583. if (parent) {
  52584. parent.children.push(serializationObject);
  52585. }
  52586. return serializationObject;
  52587. };
  52588. /**
  52589. * Internal only
  52590. * @hidden
  52591. */
  52592. Action._SerializeValueAsString = function (value) {
  52593. if (typeof value === "number") {
  52594. return value.toString();
  52595. }
  52596. if (typeof value === "boolean") {
  52597. return value ? "true" : "false";
  52598. }
  52599. if (value instanceof BABYLON.Vector2) {
  52600. return value.x + ", " + value.y;
  52601. }
  52602. if (value instanceof BABYLON.Vector3) {
  52603. return value.x + ", " + value.y + ", " + value.z;
  52604. }
  52605. if (value instanceof BABYLON.Color3) {
  52606. return value.r + ", " + value.g + ", " + value.b;
  52607. }
  52608. if (value instanceof BABYLON.Color4) {
  52609. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52610. }
  52611. return value; // string
  52612. };
  52613. /**
  52614. * Internal only
  52615. * @hidden
  52616. */
  52617. Action._GetTargetProperty = function (target) {
  52618. return {
  52619. name: "target",
  52620. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52621. : target instanceof BABYLON.Light ? "LightProperties"
  52622. : target instanceof BABYLON.Camera ? "CameraProperties"
  52623. : "SceneProperties",
  52624. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52625. };
  52626. };
  52627. return Action;
  52628. }());
  52629. BABYLON.Action = Action;
  52630. })(BABYLON || (BABYLON = {}));
  52631. //# sourceMappingURL=babylon.action.js.map
  52632. var BABYLON;
  52633. (function (BABYLON) {
  52634. /**
  52635. * ActionEvent is the event being sent when an action is triggered.
  52636. */
  52637. var ActionEvent = /** @class */ (function () {
  52638. /**
  52639. * Creates a new ActionEvent
  52640. * @param source The mesh or sprite that triggered the action
  52641. * @param pointerX The X mouse cursor position at the time of the event
  52642. * @param pointerY The Y mouse cursor position at the time of the event
  52643. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52644. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52645. * @param additionalData additional data for the event
  52646. */
  52647. function ActionEvent(
  52648. /** The mesh or sprite that triggered the action */
  52649. source,
  52650. /** The X mouse cursor position at the time of the event */
  52651. pointerX,
  52652. /** The Y mouse cursor position at the time of the event */
  52653. pointerY,
  52654. /** The mesh that is currently pointed at (can be null) */
  52655. meshUnderPointer,
  52656. /** the original (browser) event that triggered the ActionEvent */
  52657. sourceEvent,
  52658. /** additional data for the event */
  52659. additionalData) {
  52660. this.source = source;
  52661. this.pointerX = pointerX;
  52662. this.pointerY = pointerY;
  52663. this.meshUnderPointer = meshUnderPointer;
  52664. this.sourceEvent = sourceEvent;
  52665. this.additionalData = additionalData;
  52666. }
  52667. /**
  52668. * Helper function to auto-create an ActionEvent from a source mesh.
  52669. * @param source The source mesh that triggered the event
  52670. * @param evt The original (browser) event
  52671. * @param additionalData additional data for the event
  52672. * @returns the new ActionEvent
  52673. */
  52674. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52675. var scene = source.getScene();
  52676. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52677. };
  52678. /**
  52679. * Helper function to auto-create an ActionEvent from a source sprite
  52680. * @param source The source sprite that triggered the event
  52681. * @param scene Scene associated with the sprite
  52682. * @param evt The original (browser) event
  52683. * @param additionalData additional data for the event
  52684. * @returns the new ActionEvent
  52685. */
  52686. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52687. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52688. };
  52689. /**
  52690. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52691. * @param scene the scene where the event occurred
  52692. * @param evt The original (browser) event
  52693. * @returns the new ActionEvent
  52694. */
  52695. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52696. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52697. };
  52698. /**
  52699. * Helper function to auto-create an ActionEvent from a primitive
  52700. * @param prim defines the target primitive
  52701. * @param pointerPos defines the pointer position
  52702. * @param evt The original (browser) event
  52703. * @param additionalData additional data for the event
  52704. * @returns the new ActionEvent
  52705. */
  52706. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52707. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52708. };
  52709. return ActionEvent;
  52710. }());
  52711. BABYLON.ActionEvent = ActionEvent;
  52712. /**
  52713. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52714. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52715. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52716. */
  52717. var ActionManager = /** @class */ (function () {
  52718. /**
  52719. * Creates a new action manager
  52720. * @param scene defines the hosting scene
  52721. */
  52722. function ActionManager(scene) {
  52723. // Members
  52724. /** Gets the list of actions */
  52725. this.actions = new Array();
  52726. /** Gets the cursor to use when hovering items */
  52727. this.hoverCursor = '';
  52728. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52729. scene.actionManagers.push(this);
  52730. }
  52731. Object.defineProperty(ActionManager, "NothingTrigger", {
  52732. /**
  52733. * Nothing
  52734. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52735. */
  52736. get: function () {
  52737. return ActionManager._NothingTrigger;
  52738. },
  52739. enumerable: true,
  52740. configurable: true
  52741. });
  52742. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52743. /**
  52744. * On pick
  52745. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52746. */
  52747. get: function () {
  52748. return ActionManager._OnPickTrigger;
  52749. },
  52750. enumerable: true,
  52751. configurable: true
  52752. });
  52753. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52754. /**
  52755. * On left pick
  52756. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52757. */
  52758. get: function () {
  52759. return ActionManager._OnLeftPickTrigger;
  52760. },
  52761. enumerable: true,
  52762. configurable: true
  52763. });
  52764. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52765. /**
  52766. * On right pick
  52767. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52768. */
  52769. get: function () {
  52770. return ActionManager._OnRightPickTrigger;
  52771. },
  52772. enumerable: true,
  52773. configurable: true
  52774. });
  52775. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52776. /**
  52777. * On center pick
  52778. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52779. */
  52780. get: function () {
  52781. return ActionManager._OnCenterPickTrigger;
  52782. },
  52783. enumerable: true,
  52784. configurable: true
  52785. });
  52786. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52787. /**
  52788. * On pick down
  52789. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52790. */
  52791. get: function () {
  52792. return ActionManager._OnPickDownTrigger;
  52793. },
  52794. enumerable: true,
  52795. configurable: true
  52796. });
  52797. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52798. /**
  52799. * On double pick
  52800. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52801. */
  52802. get: function () {
  52803. return ActionManager._OnDoublePickTrigger;
  52804. },
  52805. enumerable: true,
  52806. configurable: true
  52807. });
  52808. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52809. /**
  52810. * On pick up
  52811. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52812. */
  52813. get: function () {
  52814. return ActionManager._OnPickUpTrigger;
  52815. },
  52816. enumerable: true,
  52817. configurable: true
  52818. });
  52819. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52820. /**
  52821. * On pick out.
  52822. * This trigger will only be raised if you also declared a OnPickDown
  52823. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52824. */
  52825. get: function () {
  52826. return ActionManager._OnPickOutTrigger;
  52827. },
  52828. enumerable: true,
  52829. configurable: true
  52830. });
  52831. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52832. /**
  52833. * On long press
  52834. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52835. */
  52836. get: function () {
  52837. return ActionManager._OnLongPressTrigger;
  52838. },
  52839. enumerable: true,
  52840. configurable: true
  52841. });
  52842. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52843. /**
  52844. * On pointer over
  52845. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52846. */
  52847. get: function () {
  52848. return ActionManager._OnPointerOverTrigger;
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52854. /**
  52855. * On pointer out
  52856. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52857. */
  52858. get: function () {
  52859. return ActionManager._OnPointerOutTrigger;
  52860. },
  52861. enumerable: true,
  52862. configurable: true
  52863. });
  52864. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52865. /**
  52866. * On every frame
  52867. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52868. */
  52869. get: function () {
  52870. return ActionManager._OnEveryFrameTrigger;
  52871. },
  52872. enumerable: true,
  52873. configurable: true
  52874. });
  52875. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52876. /**
  52877. * On intersection enter
  52878. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52879. */
  52880. get: function () {
  52881. return ActionManager._OnIntersectionEnterTrigger;
  52882. },
  52883. enumerable: true,
  52884. configurable: true
  52885. });
  52886. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52887. /**
  52888. * On intersection exit
  52889. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52890. */
  52891. get: function () {
  52892. return ActionManager._OnIntersectionExitTrigger;
  52893. },
  52894. enumerable: true,
  52895. configurable: true
  52896. });
  52897. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52898. /**
  52899. * On key down
  52900. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52901. */
  52902. get: function () {
  52903. return ActionManager._OnKeyDownTrigger;
  52904. },
  52905. enumerable: true,
  52906. configurable: true
  52907. });
  52908. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52909. /**
  52910. * On key up
  52911. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52912. */
  52913. get: function () {
  52914. return ActionManager._OnKeyUpTrigger;
  52915. },
  52916. enumerable: true,
  52917. configurable: true
  52918. });
  52919. // Methods
  52920. /**
  52921. * Releases all associated resources
  52922. */
  52923. ActionManager.prototype.dispose = function () {
  52924. var index = this._scene.actionManagers.indexOf(this);
  52925. for (var i = 0; i < this.actions.length; i++) {
  52926. var action = this.actions[i];
  52927. ActionManager.Triggers[action.trigger]--;
  52928. if (ActionManager.Triggers[action.trigger] === 0) {
  52929. delete ActionManager.Triggers[action.trigger];
  52930. }
  52931. }
  52932. if (index > -1) {
  52933. this._scene.actionManagers.splice(index, 1);
  52934. }
  52935. };
  52936. /**
  52937. * Gets hosting scene
  52938. * @returns the hosting scene
  52939. */
  52940. ActionManager.prototype.getScene = function () {
  52941. return this._scene;
  52942. };
  52943. /**
  52944. * Does this action manager handles actions of any of the given triggers
  52945. * @param triggers defines the triggers to be tested
  52946. * @return a boolean indicating whether one (or more) of the triggers is handled
  52947. */
  52948. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52949. for (var index = 0; index < this.actions.length; index++) {
  52950. var action = this.actions[index];
  52951. if (triggers.indexOf(action.trigger) > -1) {
  52952. return true;
  52953. }
  52954. }
  52955. return false;
  52956. };
  52957. /**
  52958. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52959. * speed.
  52960. * @param triggerA defines the trigger to be tested
  52961. * @param triggerB defines the trigger to be tested
  52962. * @return a boolean indicating whether one (or more) of the triggers is handled
  52963. */
  52964. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52965. for (var index = 0; index < this.actions.length; index++) {
  52966. var action = this.actions[index];
  52967. if (triggerA == action.trigger || triggerB == action.trigger) {
  52968. return true;
  52969. }
  52970. }
  52971. return false;
  52972. };
  52973. /**
  52974. * Does this action manager handles actions of a given trigger
  52975. * @param trigger defines the trigger to be tested
  52976. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52977. * @return whether the trigger is handled
  52978. */
  52979. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52980. for (var index = 0; index < this.actions.length; index++) {
  52981. var action = this.actions[index];
  52982. if (action.trigger === trigger) {
  52983. if (parameterPredicate) {
  52984. if (parameterPredicate(action.getTriggerParameter())) {
  52985. return true;
  52986. }
  52987. }
  52988. else {
  52989. return true;
  52990. }
  52991. }
  52992. }
  52993. return false;
  52994. };
  52995. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52996. /**
  52997. * Does this action manager has pointer triggers
  52998. */
  52999. get: function () {
  53000. for (var index = 0; index < this.actions.length; index++) {
  53001. var action = this.actions[index];
  53002. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53003. return true;
  53004. }
  53005. }
  53006. return false;
  53007. },
  53008. enumerable: true,
  53009. configurable: true
  53010. });
  53011. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53012. /**
  53013. * Does this action manager has pick triggers
  53014. */
  53015. get: function () {
  53016. for (var index = 0; index < this.actions.length; index++) {
  53017. var action = this.actions[index];
  53018. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53019. return true;
  53020. }
  53021. }
  53022. return false;
  53023. },
  53024. enumerable: true,
  53025. configurable: true
  53026. });
  53027. Object.defineProperty(ActionManager, "HasTriggers", {
  53028. /**
  53029. * Does exist one action manager with at least one trigger
  53030. **/
  53031. get: function () {
  53032. for (var t in ActionManager.Triggers) {
  53033. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53034. return true;
  53035. }
  53036. }
  53037. return false;
  53038. },
  53039. enumerable: true,
  53040. configurable: true
  53041. });
  53042. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53043. /**
  53044. * Does exist one action manager with at least one pick trigger
  53045. **/
  53046. get: function () {
  53047. for (var t in ActionManager.Triggers) {
  53048. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53049. var t_int = parseInt(t);
  53050. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53051. return true;
  53052. }
  53053. }
  53054. }
  53055. return false;
  53056. },
  53057. enumerable: true,
  53058. configurable: true
  53059. });
  53060. /**
  53061. * Does exist one action manager that handles actions of a given trigger
  53062. * @param trigger defines the trigger to be tested
  53063. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53064. **/
  53065. ActionManager.HasSpecificTrigger = function (trigger) {
  53066. for (var t in ActionManager.Triggers) {
  53067. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53068. var t_int = parseInt(t);
  53069. if (t_int === trigger) {
  53070. return true;
  53071. }
  53072. }
  53073. }
  53074. return false;
  53075. };
  53076. /**
  53077. * Registers an action to this action manager
  53078. * @param action defines the action to be registered
  53079. * @return the action amended (prepared) after registration
  53080. */
  53081. ActionManager.prototype.registerAction = function (action) {
  53082. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53083. if (this.getScene().actionManager !== this) {
  53084. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53085. return null;
  53086. }
  53087. }
  53088. this.actions.push(action);
  53089. if (ActionManager.Triggers[action.trigger]) {
  53090. ActionManager.Triggers[action.trigger]++;
  53091. }
  53092. else {
  53093. ActionManager.Triggers[action.trigger] = 1;
  53094. }
  53095. action._actionManager = this;
  53096. action._prepare();
  53097. return action;
  53098. };
  53099. /**
  53100. * Unregisters an action to this action manager
  53101. * @param action defines the action to be unregistered
  53102. * @return a boolean indicating whether the action has been unregistered
  53103. */
  53104. ActionManager.prototype.unregisterAction = function (action) {
  53105. var index = this.actions.indexOf(action);
  53106. if (index !== -1) {
  53107. this.actions.splice(index, 1);
  53108. ActionManager.Triggers[action.trigger] -= 1;
  53109. if (ActionManager.Triggers[action.trigger] === 0) {
  53110. delete ActionManager.Triggers[action.trigger];
  53111. }
  53112. delete action._actionManager;
  53113. return true;
  53114. }
  53115. return false;
  53116. };
  53117. /**
  53118. * Process a specific trigger
  53119. * @param trigger defines the trigger to process
  53120. * @param evt defines the event details to be processed
  53121. */
  53122. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53123. for (var index = 0; index < this.actions.length; index++) {
  53124. var action = this.actions[index];
  53125. if (action.trigger === trigger) {
  53126. if (evt) {
  53127. if (trigger === ActionManager.OnKeyUpTrigger
  53128. || trigger === ActionManager.OnKeyDownTrigger) {
  53129. var parameter = action.getTriggerParameter();
  53130. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53131. if (!parameter.toLowerCase) {
  53132. continue;
  53133. }
  53134. var lowerCase = parameter.toLowerCase();
  53135. if (lowerCase !== evt.sourceEvent.key) {
  53136. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53137. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53138. if (actualkey !== lowerCase) {
  53139. continue;
  53140. }
  53141. }
  53142. }
  53143. }
  53144. }
  53145. action._executeCurrent(evt);
  53146. }
  53147. }
  53148. };
  53149. /** @hidden */
  53150. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53151. var properties = propertyPath.split(".");
  53152. for (var index = 0; index < properties.length - 1; index++) {
  53153. target = target[properties[index]];
  53154. }
  53155. return target;
  53156. };
  53157. /** @hidden */
  53158. ActionManager.prototype._getProperty = function (propertyPath) {
  53159. var properties = propertyPath.split(".");
  53160. return properties[properties.length - 1];
  53161. };
  53162. /**
  53163. * Serialize this manager to a JSON object
  53164. * @param name defines the property name to store this manager
  53165. * @returns a JSON representation of this manager
  53166. */
  53167. ActionManager.prototype.serialize = function (name) {
  53168. var root = {
  53169. children: new Array(),
  53170. name: name,
  53171. type: 3,
  53172. properties: new Array() // Empty for root but required
  53173. };
  53174. for (var i = 0; i < this.actions.length; i++) {
  53175. var triggerObject = {
  53176. type: 0,
  53177. children: new Array(),
  53178. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53179. properties: new Array()
  53180. };
  53181. var triggerOptions = this.actions[i].triggerOptions;
  53182. if (triggerOptions && typeof triggerOptions !== "number") {
  53183. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53184. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53185. }
  53186. else {
  53187. var parameter = {};
  53188. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53189. if (triggerOptions.parameter.mesh) {
  53190. parameter._meshId = triggerOptions.parameter.mesh.id;
  53191. }
  53192. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53193. }
  53194. }
  53195. // Serialize child action, recursively
  53196. this.actions[i].serialize(triggerObject);
  53197. // Add serialized trigger
  53198. root.children.push(triggerObject);
  53199. }
  53200. return root;
  53201. };
  53202. /**
  53203. * Creates a new ActionManager from a JSON data
  53204. * @param parsedActions defines the JSON data to read from
  53205. * @param object defines the hosting mesh
  53206. * @param scene defines the hosting scene
  53207. */
  53208. ActionManager.Parse = function (parsedActions, object, scene) {
  53209. var actionManager = new ActionManager(scene);
  53210. if (object === null)
  53211. scene.actionManager = actionManager;
  53212. else
  53213. object.actionManager = actionManager;
  53214. // instanciate a new object
  53215. var instanciate = function (name, params) {
  53216. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53217. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53218. newInstance.constructor.apply(newInstance, params);
  53219. return newInstance;
  53220. };
  53221. var parseParameter = function (name, value, target, propertyPath) {
  53222. if (propertyPath === null) {
  53223. // String, boolean or float
  53224. var floatValue = parseFloat(value);
  53225. if (value === "true" || value === "false")
  53226. return value === "true";
  53227. else
  53228. return isNaN(floatValue) ? value : floatValue;
  53229. }
  53230. var effectiveTarget = propertyPath.split(".");
  53231. var values = value.split(",");
  53232. // Get effective Target
  53233. for (var i = 0; i < effectiveTarget.length; i++) {
  53234. target = target[effectiveTarget[i]];
  53235. }
  53236. // Return appropriate value with its type
  53237. if (typeof (target) === "boolean")
  53238. return values[0] === "true";
  53239. if (typeof (target) === "string")
  53240. return values[0];
  53241. // Parameters with multiple values such as Vector3 etc.
  53242. var split = new Array();
  53243. for (var i = 0; i < values.length; i++)
  53244. split.push(parseFloat(values[i]));
  53245. if (target instanceof BABYLON.Vector3)
  53246. return BABYLON.Vector3.FromArray(split);
  53247. if (target instanceof BABYLON.Vector4)
  53248. return BABYLON.Vector4.FromArray(split);
  53249. if (target instanceof BABYLON.Color3)
  53250. return BABYLON.Color3.FromArray(split);
  53251. if (target instanceof BABYLON.Color4)
  53252. return BABYLON.Color4.FromArray(split);
  53253. return parseFloat(values[0]);
  53254. };
  53255. // traverse graph per trigger
  53256. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53257. if (combineArray === void 0) { combineArray = null; }
  53258. if (parsedAction.detached)
  53259. return;
  53260. var parameters = new Array();
  53261. var target = null;
  53262. var propertyPath = null;
  53263. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53264. // Parameters
  53265. if (parsedAction.type === 2)
  53266. parameters.push(actionManager);
  53267. else
  53268. parameters.push(trigger);
  53269. if (combine) {
  53270. var actions = new Array();
  53271. for (var j = 0; j < parsedAction.combine.length; j++) {
  53272. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53273. }
  53274. parameters.push(actions);
  53275. }
  53276. else {
  53277. for (var i = 0; i < parsedAction.properties.length; i++) {
  53278. var value = parsedAction.properties[i].value;
  53279. var name = parsedAction.properties[i].name;
  53280. var targetType = parsedAction.properties[i].targetType;
  53281. if (name === "target")
  53282. if (targetType !== null && targetType === "SceneProperties")
  53283. value = target = scene;
  53284. else
  53285. value = target = scene.getNodeByName(value);
  53286. else if (name === "parent")
  53287. value = scene.getNodeByName(value);
  53288. else if (name === "sound") {
  53289. // Can not externalize to component, so only checks for the presence off the API.
  53290. if (scene.getSoundByName) {
  53291. value = scene.getSoundByName(value);
  53292. }
  53293. }
  53294. else if (name !== "propertyPath") {
  53295. if (parsedAction.type === 2 && name === "operator")
  53296. value = BABYLON.ValueCondition[value];
  53297. else
  53298. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53299. }
  53300. else {
  53301. propertyPath = value;
  53302. }
  53303. parameters.push(value);
  53304. }
  53305. }
  53306. if (combineArray === null) {
  53307. parameters.push(condition);
  53308. }
  53309. else {
  53310. parameters.push(null);
  53311. }
  53312. // If interpolate value action
  53313. if (parsedAction.name === "InterpolateValueAction") {
  53314. var param = parameters[parameters.length - 2];
  53315. parameters[parameters.length - 1] = param;
  53316. parameters[parameters.length - 2] = condition;
  53317. }
  53318. // Action or condition(s) and not CombineAction
  53319. var newAction = instanciate(parsedAction.name, parameters);
  53320. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53321. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53322. if (action)
  53323. action.then(nothing);
  53324. else
  53325. actionManager.registerAction(nothing);
  53326. action = nothing;
  53327. }
  53328. if (combineArray === null) {
  53329. if (newAction instanceof BABYLON.Condition) {
  53330. condition = newAction;
  53331. newAction = action;
  53332. }
  53333. else {
  53334. condition = null;
  53335. if (action)
  53336. action.then(newAction);
  53337. else
  53338. actionManager.registerAction(newAction);
  53339. }
  53340. }
  53341. else {
  53342. combineArray.push(newAction);
  53343. }
  53344. for (var i = 0; i < parsedAction.children.length; i++)
  53345. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53346. };
  53347. // triggers
  53348. for (var i = 0; i < parsedActions.children.length; i++) {
  53349. var triggerParams;
  53350. var trigger = parsedActions.children[i];
  53351. if (trigger.properties.length > 0) {
  53352. var param = trigger.properties[0].value;
  53353. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53354. if (value._meshId) {
  53355. value.mesh = scene.getMeshByID(value._meshId);
  53356. }
  53357. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53358. }
  53359. else
  53360. triggerParams = ActionManager[trigger.name];
  53361. for (var j = 0; j < trigger.children.length; j++) {
  53362. if (!trigger.detached)
  53363. traverse(trigger.children[j], triggerParams, null, null);
  53364. }
  53365. }
  53366. };
  53367. /**
  53368. * Get a trigger name by index
  53369. * @param trigger defines the trigger index
  53370. * @returns a trigger name
  53371. */
  53372. ActionManager.GetTriggerName = function (trigger) {
  53373. switch (trigger) {
  53374. case 0: return "NothingTrigger";
  53375. case 1: return "OnPickTrigger";
  53376. case 2: return "OnLeftPickTrigger";
  53377. case 3: return "OnRightPickTrigger";
  53378. case 4: return "OnCenterPickTrigger";
  53379. case 5: return "OnPickDownTrigger";
  53380. case 6: return "OnPickUpTrigger";
  53381. case 7: return "OnLongPressTrigger";
  53382. case 8: return "OnPointerOverTrigger";
  53383. case 9: return "OnPointerOutTrigger";
  53384. case 10: return "OnEveryFrameTrigger";
  53385. case 11: return "OnIntersectionEnterTrigger";
  53386. case 12: return "OnIntersectionExitTrigger";
  53387. case 13: return "OnKeyDownTrigger";
  53388. case 14: return "OnKeyUpTrigger";
  53389. case 15: return "OnPickOutTrigger";
  53390. default: return "";
  53391. }
  53392. };
  53393. // Statics
  53394. ActionManager._NothingTrigger = 0;
  53395. ActionManager._OnPickTrigger = 1;
  53396. ActionManager._OnLeftPickTrigger = 2;
  53397. ActionManager._OnRightPickTrigger = 3;
  53398. ActionManager._OnCenterPickTrigger = 4;
  53399. ActionManager._OnPickDownTrigger = 5;
  53400. ActionManager._OnDoublePickTrigger = 6;
  53401. ActionManager._OnPickUpTrigger = 7;
  53402. ActionManager._OnLongPressTrigger = 8;
  53403. ActionManager._OnPointerOverTrigger = 9;
  53404. ActionManager._OnPointerOutTrigger = 10;
  53405. ActionManager._OnEveryFrameTrigger = 11;
  53406. ActionManager._OnIntersectionEnterTrigger = 12;
  53407. ActionManager._OnIntersectionExitTrigger = 13;
  53408. ActionManager._OnKeyDownTrigger = 14;
  53409. ActionManager._OnKeyUpTrigger = 15;
  53410. ActionManager._OnPickOutTrigger = 16;
  53411. /** Gets the list of active triggers */
  53412. ActionManager.Triggers = {};
  53413. return ActionManager;
  53414. }());
  53415. BABYLON.ActionManager = ActionManager;
  53416. })(BABYLON || (BABYLON = {}));
  53417. //# sourceMappingURL=babylon.actionManager.js.map
  53418. var BABYLON;
  53419. (function (BABYLON) {
  53420. var InterpolateValueAction = /** @class */ (function (_super) {
  53421. __extends(InterpolateValueAction, _super);
  53422. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53423. if (duration === void 0) { duration = 1000; }
  53424. var _this = _super.call(this, triggerOptions, condition) || this;
  53425. _this.propertyPath = propertyPath;
  53426. _this.value = value;
  53427. _this.duration = duration;
  53428. _this.stopOtherAnimations = stopOtherAnimations;
  53429. _this.onInterpolationDone = onInterpolationDone;
  53430. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53431. _this._target = _this._effectiveTarget = target;
  53432. return _this;
  53433. }
  53434. /** @hidden */
  53435. InterpolateValueAction.prototype._prepare = function () {
  53436. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53437. this._property = this._getProperty(this.propertyPath);
  53438. };
  53439. InterpolateValueAction.prototype.execute = function () {
  53440. var _this = this;
  53441. var scene = this._actionManager.getScene();
  53442. var keys = [
  53443. {
  53444. frame: 0,
  53445. value: this._effectiveTarget[this._property]
  53446. }, {
  53447. frame: 100,
  53448. value: this.value
  53449. }
  53450. ];
  53451. var dataType;
  53452. if (typeof this.value === "number") {
  53453. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53454. }
  53455. else if (this.value instanceof BABYLON.Color3) {
  53456. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53457. }
  53458. else if (this.value instanceof BABYLON.Vector3) {
  53459. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53460. }
  53461. else if (this.value instanceof BABYLON.Matrix) {
  53462. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53463. }
  53464. else if (this.value instanceof BABYLON.Quaternion) {
  53465. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53466. }
  53467. else {
  53468. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53469. return;
  53470. }
  53471. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53472. animation.setKeys(keys);
  53473. if (this.stopOtherAnimations) {
  53474. scene.stopAnimation(this._effectiveTarget);
  53475. }
  53476. var wrapper = function () {
  53477. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53478. if (_this.onInterpolationDone) {
  53479. _this.onInterpolationDone();
  53480. }
  53481. };
  53482. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53483. };
  53484. InterpolateValueAction.prototype.serialize = function (parent) {
  53485. return _super.prototype._serialize.call(this, {
  53486. name: "InterpolateValueAction",
  53487. properties: [
  53488. BABYLON.Action._GetTargetProperty(this._target),
  53489. { name: "propertyPath", value: this.propertyPath },
  53490. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53491. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53492. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53493. ]
  53494. }, parent);
  53495. };
  53496. return InterpolateValueAction;
  53497. }(BABYLON.Action));
  53498. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53499. })(BABYLON || (BABYLON = {}));
  53500. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53501. var BABYLON;
  53502. (function (BABYLON) {
  53503. var SwitchBooleanAction = /** @class */ (function (_super) {
  53504. __extends(SwitchBooleanAction, _super);
  53505. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53506. var _this = _super.call(this, triggerOptions, condition) || this;
  53507. _this.propertyPath = propertyPath;
  53508. _this._target = _this._effectiveTarget = target;
  53509. return _this;
  53510. }
  53511. /** @hidden */
  53512. SwitchBooleanAction.prototype._prepare = function () {
  53513. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53514. this._property = this._getProperty(this.propertyPath);
  53515. };
  53516. SwitchBooleanAction.prototype.execute = function () {
  53517. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53518. };
  53519. SwitchBooleanAction.prototype.serialize = function (parent) {
  53520. return _super.prototype._serialize.call(this, {
  53521. name: "SwitchBooleanAction",
  53522. properties: [
  53523. BABYLON.Action._GetTargetProperty(this._target),
  53524. { name: "propertyPath", value: this.propertyPath }
  53525. ]
  53526. }, parent);
  53527. };
  53528. return SwitchBooleanAction;
  53529. }(BABYLON.Action));
  53530. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53531. var SetStateAction = /** @class */ (function (_super) {
  53532. __extends(SetStateAction, _super);
  53533. function SetStateAction(triggerOptions, target, value, condition) {
  53534. var _this = _super.call(this, triggerOptions, condition) || this;
  53535. _this.value = value;
  53536. _this._target = target;
  53537. return _this;
  53538. }
  53539. SetStateAction.prototype.execute = function () {
  53540. this._target.state = this.value;
  53541. };
  53542. SetStateAction.prototype.serialize = function (parent) {
  53543. return _super.prototype._serialize.call(this, {
  53544. name: "SetStateAction",
  53545. properties: [
  53546. BABYLON.Action._GetTargetProperty(this._target),
  53547. { name: "value", value: this.value }
  53548. ]
  53549. }, parent);
  53550. };
  53551. return SetStateAction;
  53552. }(BABYLON.Action));
  53553. BABYLON.SetStateAction = SetStateAction;
  53554. var SetValueAction = /** @class */ (function (_super) {
  53555. __extends(SetValueAction, _super);
  53556. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53557. var _this = _super.call(this, triggerOptions, condition) || this;
  53558. _this.propertyPath = propertyPath;
  53559. _this.value = value;
  53560. _this._target = _this._effectiveTarget = target;
  53561. return _this;
  53562. }
  53563. /** @hidden */
  53564. SetValueAction.prototype._prepare = function () {
  53565. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53566. this._property = this._getProperty(this.propertyPath);
  53567. };
  53568. SetValueAction.prototype.execute = function () {
  53569. this._effectiveTarget[this._property] = this.value;
  53570. if (this._target.markAsDirty) {
  53571. this._target.markAsDirty(this._property);
  53572. }
  53573. };
  53574. SetValueAction.prototype.serialize = function (parent) {
  53575. return _super.prototype._serialize.call(this, {
  53576. name: "SetValueAction",
  53577. properties: [
  53578. BABYLON.Action._GetTargetProperty(this._target),
  53579. { name: "propertyPath", value: this.propertyPath },
  53580. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53581. ]
  53582. }, parent);
  53583. };
  53584. return SetValueAction;
  53585. }(BABYLON.Action));
  53586. BABYLON.SetValueAction = SetValueAction;
  53587. var IncrementValueAction = /** @class */ (function (_super) {
  53588. __extends(IncrementValueAction, _super);
  53589. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53590. var _this = _super.call(this, triggerOptions, condition) || this;
  53591. _this.propertyPath = propertyPath;
  53592. _this.value = value;
  53593. _this._target = _this._effectiveTarget = target;
  53594. return _this;
  53595. }
  53596. /** @hidden */
  53597. IncrementValueAction.prototype._prepare = function () {
  53598. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53599. this._property = this._getProperty(this.propertyPath);
  53600. if (typeof this._effectiveTarget[this._property] !== "number") {
  53601. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53602. }
  53603. };
  53604. IncrementValueAction.prototype.execute = function () {
  53605. this._effectiveTarget[this._property] += this.value;
  53606. if (this._target.markAsDirty) {
  53607. this._target.markAsDirty(this._property);
  53608. }
  53609. };
  53610. IncrementValueAction.prototype.serialize = function (parent) {
  53611. return _super.prototype._serialize.call(this, {
  53612. name: "IncrementValueAction",
  53613. properties: [
  53614. BABYLON.Action._GetTargetProperty(this._target),
  53615. { name: "propertyPath", value: this.propertyPath },
  53616. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53617. ]
  53618. }, parent);
  53619. };
  53620. return IncrementValueAction;
  53621. }(BABYLON.Action));
  53622. BABYLON.IncrementValueAction = IncrementValueAction;
  53623. var PlayAnimationAction = /** @class */ (function (_super) {
  53624. __extends(PlayAnimationAction, _super);
  53625. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53626. var _this = _super.call(this, triggerOptions, condition) || this;
  53627. _this.from = from;
  53628. _this.to = to;
  53629. _this.loop = loop;
  53630. _this._target = target;
  53631. return _this;
  53632. }
  53633. /** @hidden */
  53634. PlayAnimationAction.prototype._prepare = function () {
  53635. };
  53636. PlayAnimationAction.prototype.execute = function () {
  53637. var scene = this._actionManager.getScene();
  53638. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53639. };
  53640. PlayAnimationAction.prototype.serialize = function (parent) {
  53641. return _super.prototype._serialize.call(this, {
  53642. name: "PlayAnimationAction",
  53643. properties: [
  53644. BABYLON.Action._GetTargetProperty(this._target),
  53645. { name: "from", value: String(this.from) },
  53646. { name: "to", value: String(this.to) },
  53647. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53648. ]
  53649. }, parent);
  53650. };
  53651. return PlayAnimationAction;
  53652. }(BABYLON.Action));
  53653. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53654. var StopAnimationAction = /** @class */ (function (_super) {
  53655. __extends(StopAnimationAction, _super);
  53656. function StopAnimationAction(triggerOptions, target, condition) {
  53657. var _this = _super.call(this, triggerOptions, condition) || this;
  53658. _this._target = target;
  53659. return _this;
  53660. }
  53661. /** @hidden */
  53662. StopAnimationAction.prototype._prepare = function () {
  53663. };
  53664. StopAnimationAction.prototype.execute = function () {
  53665. var scene = this._actionManager.getScene();
  53666. scene.stopAnimation(this._target);
  53667. };
  53668. StopAnimationAction.prototype.serialize = function (parent) {
  53669. return _super.prototype._serialize.call(this, {
  53670. name: "StopAnimationAction",
  53671. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53672. }, parent);
  53673. };
  53674. return StopAnimationAction;
  53675. }(BABYLON.Action));
  53676. BABYLON.StopAnimationAction = StopAnimationAction;
  53677. var DoNothingAction = /** @class */ (function (_super) {
  53678. __extends(DoNothingAction, _super);
  53679. function DoNothingAction(triggerOptions, condition) {
  53680. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53681. return _super.call(this, triggerOptions, condition) || this;
  53682. }
  53683. DoNothingAction.prototype.execute = function () {
  53684. };
  53685. DoNothingAction.prototype.serialize = function (parent) {
  53686. return _super.prototype._serialize.call(this, {
  53687. name: "DoNothingAction",
  53688. properties: []
  53689. }, parent);
  53690. };
  53691. return DoNothingAction;
  53692. }(BABYLON.Action));
  53693. BABYLON.DoNothingAction = DoNothingAction;
  53694. var CombineAction = /** @class */ (function (_super) {
  53695. __extends(CombineAction, _super);
  53696. function CombineAction(triggerOptions, children, condition) {
  53697. var _this = _super.call(this, triggerOptions, condition) || this;
  53698. _this.children = children;
  53699. return _this;
  53700. }
  53701. /** @hidden */
  53702. CombineAction.prototype._prepare = function () {
  53703. for (var index = 0; index < this.children.length; index++) {
  53704. this.children[index]._actionManager = this._actionManager;
  53705. this.children[index]._prepare();
  53706. }
  53707. };
  53708. CombineAction.prototype.execute = function (evt) {
  53709. for (var index = 0; index < this.children.length; index++) {
  53710. this.children[index].execute(evt);
  53711. }
  53712. };
  53713. CombineAction.prototype.serialize = function (parent) {
  53714. var serializationObject = _super.prototype._serialize.call(this, {
  53715. name: "CombineAction",
  53716. properties: [],
  53717. combine: []
  53718. }, parent);
  53719. for (var i = 0; i < this.children.length; i++) {
  53720. serializationObject.combine.push(this.children[i].serialize(null));
  53721. }
  53722. return serializationObject;
  53723. };
  53724. return CombineAction;
  53725. }(BABYLON.Action));
  53726. BABYLON.CombineAction = CombineAction;
  53727. var ExecuteCodeAction = /** @class */ (function (_super) {
  53728. __extends(ExecuteCodeAction, _super);
  53729. function ExecuteCodeAction(triggerOptions, func, condition) {
  53730. var _this = _super.call(this, triggerOptions, condition) || this;
  53731. _this.func = func;
  53732. return _this;
  53733. }
  53734. ExecuteCodeAction.prototype.execute = function (evt) {
  53735. this.func(evt);
  53736. };
  53737. return ExecuteCodeAction;
  53738. }(BABYLON.Action));
  53739. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53740. var SetParentAction = /** @class */ (function (_super) {
  53741. __extends(SetParentAction, _super);
  53742. function SetParentAction(triggerOptions, target, parent, condition) {
  53743. var _this = _super.call(this, triggerOptions, condition) || this;
  53744. _this._target = target;
  53745. _this._parent = parent;
  53746. return _this;
  53747. }
  53748. /** @hidden */
  53749. SetParentAction.prototype._prepare = function () {
  53750. };
  53751. SetParentAction.prototype.execute = function () {
  53752. if (this._target.parent === this._parent) {
  53753. return;
  53754. }
  53755. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53756. invertParentWorldMatrix.invert();
  53757. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53758. this._target.parent = this._parent;
  53759. };
  53760. SetParentAction.prototype.serialize = function (parent) {
  53761. return _super.prototype._serialize.call(this, {
  53762. name: "SetParentAction",
  53763. properties: [
  53764. BABYLON.Action._GetTargetProperty(this._target),
  53765. BABYLON.Action._GetTargetProperty(this._parent),
  53766. ]
  53767. }, parent);
  53768. };
  53769. return SetParentAction;
  53770. }(BABYLON.Action));
  53771. BABYLON.SetParentAction = SetParentAction;
  53772. })(BABYLON || (BABYLON = {}));
  53773. //# sourceMappingURL=babylon.directActions.js.map
  53774. var BABYLON;
  53775. (function (BABYLON) {
  53776. var SpriteManager = /** @class */ (function () {
  53777. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53778. if (epsilon === void 0) { epsilon = 0.01; }
  53779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53780. this.name = name;
  53781. this.sprites = new Array();
  53782. this.renderingGroupId = 0;
  53783. this.layerMask = 0x0FFFFFFF;
  53784. this.fogEnabled = true;
  53785. this.isPickable = false;
  53786. /**
  53787. * An event triggered when the manager is disposed.
  53788. */
  53789. this.onDisposeObservable = new BABYLON.Observable();
  53790. this._vertexBuffers = {};
  53791. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53792. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53793. }
  53794. this._capacity = capacity;
  53795. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53796. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53797. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53798. if (cellSize.width && cellSize.height) {
  53799. this.cellWidth = cellSize.width;
  53800. this.cellHeight = cellSize.height;
  53801. }
  53802. else if (cellSize !== undefined) {
  53803. this.cellWidth = cellSize;
  53804. this.cellHeight = cellSize;
  53805. }
  53806. else {
  53807. return;
  53808. }
  53809. this._epsilon = epsilon;
  53810. this._scene = scene;
  53811. this._scene.spriteManagers.push(this);
  53812. var indices = [];
  53813. var index = 0;
  53814. for (var count = 0; count < capacity; count++) {
  53815. indices.push(index);
  53816. indices.push(index + 1);
  53817. indices.push(index + 2);
  53818. indices.push(index);
  53819. indices.push(index + 2);
  53820. indices.push(index + 3);
  53821. index += 4;
  53822. }
  53823. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53824. // VBO
  53825. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53826. this._vertexData = new Float32Array(capacity * 16 * 4);
  53827. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53828. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53829. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53830. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53831. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53833. this._vertexBuffers["options"] = options;
  53834. this._vertexBuffers["cellInfo"] = cellInfo;
  53835. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53836. // Effects
  53837. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53838. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53839. }
  53840. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53841. set: function (callback) {
  53842. if (this._onDisposeObserver) {
  53843. this.onDisposeObservable.remove(this._onDisposeObserver);
  53844. }
  53845. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53846. },
  53847. enumerable: true,
  53848. configurable: true
  53849. });
  53850. Object.defineProperty(SpriteManager.prototype, "texture", {
  53851. get: function () {
  53852. return this._spriteTexture;
  53853. },
  53854. set: function (value) {
  53855. this._spriteTexture = value;
  53856. },
  53857. enumerable: true,
  53858. configurable: true
  53859. });
  53860. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53861. var arrayOffset = index * 16;
  53862. if (offsetX === 0)
  53863. offsetX = this._epsilon;
  53864. else if (offsetX === 1)
  53865. offsetX = 1 - this._epsilon;
  53866. if (offsetY === 0)
  53867. offsetY = this._epsilon;
  53868. else if (offsetY === 1)
  53869. offsetY = 1 - this._epsilon;
  53870. this._vertexData[arrayOffset] = sprite.position.x;
  53871. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53872. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53873. this._vertexData[arrayOffset + 3] = sprite.angle;
  53874. this._vertexData[arrayOffset + 4] = sprite.width;
  53875. this._vertexData[arrayOffset + 5] = sprite.height;
  53876. this._vertexData[arrayOffset + 6] = offsetX;
  53877. this._vertexData[arrayOffset + 7] = offsetY;
  53878. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53879. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53880. var offset = (sprite.cellIndex / rowSize) >> 0;
  53881. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53882. this._vertexData[arrayOffset + 11] = offset;
  53883. // Color
  53884. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53885. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53886. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53887. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53888. };
  53889. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53890. var count = Math.min(this._capacity, this.sprites.length);
  53891. var min = BABYLON.Vector3.Zero();
  53892. var max = BABYLON.Vector3.Zero();
  53893. var distance = Number.MAX_VALUE;
  53894. var currentSprite = null;
  53895. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53896. var cameraView = camera.getViewMatrix();
  53897. for (var index = 0; index < count; index++) {
  53898. var sprite = this.sprites[index];
  53899. if (!sprite) {
  53900. continue;
  53901. }
  53902. if (predicate) {
  53903. if (!predicate(sprite)) {
  53904. continue;
  53905. }
  53906. }
  53907. else if (!sprite.isPickable) {
  53908. continue;
  53909. }
  53910. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53911. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53912. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53913. if (ray.intersectsBoxMinMax(min, max)) {
  53914. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53915. if (distance > currentDistance) {
  53916. distance = currentDistance;
  53917. currentSprite = sprite;
  53918. if (fastCheck) {
  53919. break;
  53920. }
  53921. }
  53922. }
  53923. }
  53924. if (currentSprite) {
  53925. var result = new BABYLON.PickingInfo();
  53926. result.hit = true;
  53927. result.pickedSprite = currentSprite;
  53928. result.distance = distance;
  53929. return result;
  53930. }
  53931. return null;
  53932. };
  53933. SpriteManager.prototype.render = function () {
  53934. // Check
  53935. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53936. return;
  53937. var engine = this._scene.getEngine();
  53938. var baseSize = this._spriteTexture.getBaseSize();
  53939. // Sprites
  53940. var deltaTime = engine.getDeltaTime();
  53941. var max = Math.min(this._capacity, this.sprites.length);
  53942. var rowSize = baseSize.width / this.cellWidth;
  53943. var offset = 0;
  53944. for (var index = 0; index < max; index++) {
  53945. var sprite = this.sprites[index];
  53946. if (!sprite || !sprite.isVisible) {
  53947. continue;
  53948. }
  53949. sprite._animate(deltaTime);
  53950. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53951. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53952. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53953. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53954. }
  53955. this._buffer.update(this._vertexData);
  53956. // Render
  53957. var effect = this._effectBase;
  53958. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53959. effect = this._effectFog;
  53960. }
  53961. engine.enableEffect(effect);
  53962. var viewMatrix = this._scene.getViewMatrix();
  53963. effect.setTexture("diffuseSampler", this._spriteTexture);
  53964. effect.setMatrix("view", viewMatrix);
  53965. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53966. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53967. // Fog
  53968. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53969. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53970. effect.setColor3("vFogColor", this._scene.fogColor);
  53971. }
  53972. // VBOs
  53973. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53974. // Draw order
  53975. engine.setDepthFunctionToLessOrEqual();
  53976. effect.setBool("alphaTest", true);
  53977. engine.setColorWrite(false);
  53978. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53979. engine.setColorWrite(true);
  53980. effect.setBool("alphaTest", false);
  53981. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53982. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53983. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53984. };
  53985. SpriteManager.prototype.dispose = function () {
  53986. if (this._buffer) {
  53987. this._buffer.dispose();
  53988. this._buffer = null;
  53989. }
  53990. if (this._indexBuffer) {
  53991. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53992. this._indexBuffer = null;
  53993. }
  53994. if (this._spriteTexture) {
  53995. this._spriteTexture.dispose();
  53996. this._spriteTexture = null;
  53997. }
  53998. // Remove from scene
  53999. var index = this._scene.spriteManagers.indexOf(this);
  54000. this._scene.spriteManagers.splice(index, 1);
  54001. // Callback
  54002. this.onDisposeObservable.notifyObservers(this);
  54003. this.onDisposeObservable.clear();
  54004. };
  54005. return SpriteManager;
  54006. }());
  54007. BABYLON.SpriteManager = SpriteManager;
  54008. })(BABYLON || (BABYLON = {}));
  54009. //# sourceMappingURL=babylon.spriteManager.js.map
  54010. var BABYLON;
  54011. (function (BABYLON) {
  54012. var Sprite = /** @class */ (function () {
  54013. function Sprite(name, manager) {
  54014. this.name = name;
  54015. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54016. this.width = 1.0;
  54017. this.height = 1.0;
  54018. this.angle = 0;
  54019. this.cellIndex = 0;
  54020. this.invertU = 0;
  54021. this.invertV = 0;
  54022. this.animations = new Array();
  54023. this.isPickable = false;
  54024. this._animationStarted = false;
  54025. this._loopAnimation = false;
  54026. this._fromIndex = 0;
  54027. this._toIndex = 0;
  54028. this._delay = 0;
  54029. this._direction = 1;
  54030. this._time = 0;
  54031. /**
  54032. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54033. */
  54034. this.isVisible = true;
  54035. this._manager = manager;
  54036. this._manager.sprites.push(this);
  54037. this.position = BABYLON.Vector3.Zero();
  54038. }
  54039. Object.defineProperty(Sprite.prototype, "size", {
  54040. get: function () {
  54041. return this.width;
  54042. },
  54043. set: function (value) {
  54044. this.width = value;
  54045. this.height = value;
  54046. },
  54047. enumerable: true,
  54048. configurable: true
  54049. });
  54050. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54051. this._fromIndex = from;
  54052. this._toIndex = to;
  54053. this._loopAnimation = loop;
  54054. this._delay = delay;
  54055. this._animationStarted = true;
  54056. this._direction = from < to ? 1 : -1;
  54057. this.cellIndex = from;
  54058. this._time = 0;
  54059. this._onAnimationEnd = onAnimationEnd;
  54060. };
  54061. Sprite.prototype.stopAnimation = function () {
  54062. this._animationStarted = false;
  54063. };
  54064. /** @hidden */
  54065. Sprite.prototype._animate = function (deltaTime) {
  54066. if (!this._animationStarted)
  54067. return;
  54068. this._time += deltaTime;
  54069. if (this._time > this._delay) {
  54070. this._time = this._time % this._delay;
  54071. this.cellIndex += this._direction;
  54072. if (this.cellIndex > this._toIndex) {
  54073. if (this._loopAnimation) {
  54074. this.cellIndex = this._fromIndex;
  54075. }
  54076. else {
  54077. this.cellIndex = this._toIndex;
  54078. this._animationStarted = false;
  54079. if (this._onAnimationEnd) {
  54080. this._onAnimationEnd();
  54081. }
  54082. if (this.disposeWhenFinishedAnimating) {
  54083. this.dispose();
  54084. }
  54085. }
  54086. }
  54087. }
  54088. };
  54089. Sprite.prototype.dispose = function () {
  54090. for (var i = 0; i < this._manager.sprites.length; i++) {
  54091. if (this._manager.sprites[i] == this) {
  54092. this._manager.sprites.splice(i, 1);
  54093. }
  54094. }
  54095. };
  54096. return Sprite;
  54097. }());
  54098. BABYLON.Sprite = Sprite;
  54099. })(BABYLON || (BABYLON = {}));
  54100. //# sourceMappingURL=babylon.sprite.js.map
  54101. var BABYLON;
  54102. (function (BABYLON) {
  54103. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54104. if (!BABYLON.PickingInfo) {
  54105. return null;
  54106. }
  54107. var pickingInfo = null;
  54108. if (!camera) {
  54109. if (!this.activeCamera) {
  54110. return null;
  54111. }
  54112. camera = this.activeCamera;
  54113. }
  54114. if (this.spriteManagers.length > 0) {
  54115. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54116. var spriteManager = this.spriteManagers[spriteIndex];
  54117. if (!spriteManager.isPickable) {
  54118. continue;
  54119. }
  54120. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54121. if (!result || !result.hit)
  54122. continue;
  54123. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54124. continue;
  54125. pickingInfo = result;
  54126. if (fastCheck) {
  54127. break;
  54128. }
  54129. }
  54130. }
  54131. return pickingInfo || new BABYLON.PickingInfo();
  54132. };
  54133. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54134. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54135. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54136. };
  54137. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54138. if (!this._tempSpritePickingRay) {
  54139. return null;
  54140. }
  54141. if (!camera) {
  54142. if (!this.activeCamera) {
  54143. return null;
  54144. }
  54145. camera = this.activeCamera;
  54146. }
  54147. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54148. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54149. };
  54150. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54151. if (this._pointerOverSprite === sprite) {
  54152. return;
  54153. }
  54154. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54155. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54156. }
  54157. this._pointerOverSprite = sprite;
  54158. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54159. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54160. }
  54161. };
  54162. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54163. return this._pointerOverSprite;
  54164. };
  54165. /**
  54166. * Defines the sprite scene component responsible to manage sprites
  54167. * in a given scene.
  54168. */
  54169. var SpriteSceneComponent = /** @class */ (function () {
  54170. /**
  54171. * Creates a new instance of the component for the given scene
  54172. * @param scene Defines the scene to register the component in
  54173. */
  54174. function SpriteSceneComponent(scene) {
  54175. /**
  54176. * The component name helpfull to identify the component in the list of scene components.
  54177. */
  54178. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54179. this.scene = scene;
  54180. this.scene.spriteManagers = new Array();
  54181. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54182. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54183. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54184. this._spritePredicate = function (sprite) {
  54185. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54186. };
  54187. }
  54188. /**
  54189. * Registers the component in a given scene
  54190. */
  54191. SpriteSceneComponent.prototype.register = function () {
  54192. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54193. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54194. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54195. };
  54196. /**
  54197. * Rebuilds the elements related to this component in case of
  54198. * context lost for instance.
  54199. */
  54200. SpriteSceneComponent.prototype.rebuild = function () {
  54201. /** Nothing to do for sprites */
  54202. };
  54203. /**
  54204. * Disposes the component and the associated ressources.
  54205. */
  54206. SpriteSceneComponent.prototype.dispose = function () {
  54207. this.scene.onBeforeSpritesRenderingObservable.clear();
  54208. this.scene.onAfterSpritesRenderingObservable.clear();
  54209. var spriteManagers = this.scene.spriteManagers;
  54210. while (spriteManagers.length) {
  54211. spriteManagers[0].dispose();
  54212. }
  54213. };
  54214. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54215. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54216. if (result) {
  54217. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54218. }
  54219. return result;
  54220. };
  54221. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54222. var scene = this.scene;
  54223. if (isMeshPicked) {
  54224. scene.setPointerOverSprite(null);
  54225. }
  54226. else {
  54227. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54228. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54229. scene.setPointerOverSprite(pickResult.pickedSprite);
  54230. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54231. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54232. }
  54233. else {
  54234. canvas.style.cursor = scene.hoverCursor;
  54235. }
  54236. }
  54237. else {
  54238. scene.setPointerOverSprite(null);
  54239. }
  54240. }
  54241. return pickResult;
  54242. };
  54243. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54244. var scene = this.scene;
  54245. scene._pickedDownSprite = null;
  54246. if (scene.spriteManagers.length > 0) {
  54247. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54248. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54249. if (pickResult.pickedSprite.actionManager) {
  54250. scene._pickedDownSprite = pickResult.pickedSprite;
  54251. switch (evt.button) {
  54252. case 0:
  54253. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54254. break;
  54255. case 1:
  54256. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54257. break;
  54258. case 2:
  54259. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54260. break;
  54261. }
  54262. if (pickResult.pickedSprite.actionManager) {
  54263. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54264. }
  54265. }
  54266. }
  54267. }
  54268. return pickResult;
  54269. };
  54270. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54271. var scene = this.scene;
  54272. if (scene.spriteManagers.length > 0) {
  54273. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54274. if (spritePickResult) {
  54275. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54276. if (spritePickResult.pickedSprite.actionManager) {
  54277. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54278. if (spritePickResult.pickedSprite.actionManager) {
  54279. if (!this.scene._isPointerSwiping()) {
  54280. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54281. }
  54282. }
  54283. }
  54284. }
  54285. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54286. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54287. }
  54288. }
  54289. }
  54290. return pickResult;
  54291. };
  54292. return SpriteSceneComponent;
  54293. }());
  54294. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54295. })(BABYLON || (BABYLON = {}));
  54296. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54297. var BABYLON;
  54298. (function (BABYLON) {
  54299. var IntersectionInfo = /** @class */ (function () {
  54300. function IntersectionInfo(bu, bv, distance) {
  54301. this.bu = bu;
  54302. this.bv = bv;
  54303. this.distance = distance;
  54304. this.faceId = 0;
  54305. this.subMeshId = 0;
  54306. }
  54307. return IntersectionInfo;
  54308. }());
  54309. BABYLON.IntersectionInfo = IntersectionInfo;
  54310. /**
  54311. * Information about the result of picking within a scene
  54312. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54313. */
  54314. var PickingInfo = /** @class */ (function () {
  54315. function PickingInfo() {
  54316. /**
  54317. * If the pick collided with an object
  54318. */
  54319. this.hit = false;
  54320. /**
  54321. * Distance away where the pick collided
  54322. */
  54323. this.distance = 0;
  54324. /**
  54325. * The location of pick collision
  54326. */
  54327. this.pickedPoint = null;
  54328. /**
  54329. * The mesh corresponding the the pick collision
  54330. */
  54331. this.pickedMesh = null;
  54332. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54333. this.bu = 0;
  54334. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54335. this.bv = 0;
  54336. /** The id of the face on the mesh that was picked */
  54337. this.faceId = -1;
  54338. /** Id of the the submesh that was picked */
  54339. this.subMeshId = 0;
  54340. /** If a sprite was picked, this will be the sprite the pick collided with */
  54341. this.pickedSprite = null;
  54342. /**
  54343. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54344. */
  54345. this.originMesh = null;
  54346. /**
  54347. * The ray that was used to perform the picking.
  54348. */
  54349. this.ray = null;
  54350. }
  54351. /**
  54352. * Gets the normal correspodning to the face the pick collided with
  54353. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54354. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54355. * @returns The normal correspodning to the face the pick collided with
  54356. */
  54357. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54358. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54359. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54360. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54361. return null;
  54362. }
  54363. var indices = this.pickedMesh.getIndices();
  54364. if (!indices) {
  54365. return null;
  54366. }
  54367. var result;
  54368. if (useVerticesNormals) {
  54369. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54370. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54371. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54372. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54373. normal0 = normal0.scale(this.bu);
  54374. normal1 = normal1.scale(this.bv);
  54375. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54376. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54377. }
  54378. else {
  54379. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54380. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54381. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54382. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54383. var p1p2 = vertex1.subtract(vertex2);
  54384. var p3p2 = vertex3.subtract(vertex2);
  54385. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54386. }
  54387. if (useWorldCoordinates) {
  54388. var wm = this.pickedMesh.getWorldMatrix();
  54389. if (this.pickedMesh.nonUniformScaling) {
  54390. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54391. wm = BABYLON.Tmp.Matrix[0];
  54392. wm.setTranslationFromFloats(0, 0, 0);
  54393. wm.invert();
  54394. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54395. wm = BABYLON.Tmp.Matrix[1];
  54396. }
  54397. result = BABYLON.Vector3.TransformNormal(result, wm);
  54398. }
  54399. result.normalize();
  54400. return result;
  54401. };
  54402. /**
  54403. * Gets the texture coordinates of where the pick occured
  54404. * @returns the vector containing the coordnates of the texture
  54405. */
  54406. PickingInfo.prototype.getTextureCoordinates = function () {
  54407. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54408. return null;
  54409. }
  54410. var indices = this.pickedMesh.getIndices();
  54411. if (!indices) {
  54412. return null;
  54413. }
  54414. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54415. if (!uvs) {
  54416. return null;
  54417. }
  54418. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54419. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54420. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54421. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54422. uv1 = uv1.scale(this.bu);
  54423. uv2 = uv2.scale(this.bv);
  54424. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54425. };
  54426. return PickingInfo;
  54427. }());
  54428. BABYLON.PickingInfo = PickingInfo;
  54429. })(BABYLON || (BABYLON = {}));
  54430. //# sourceMappingURL=babylon.pickingInfo.js.map
  54431. var BABYLON;
  54432. (function (BABYLON) {
  54433. var Ray = /** @class */ (function () {
  54434. function Ray(origin, direction, length) {
  54435. if (length === void 0) { length = Number.MAX_VALUE; }
  54436. this.origin = origin;
  54437. this.direction = direction;
  54438. this.length = length;
  54439. }
  54440. // Methods
  54441. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54442. var d = 0.0;
  54443. var maxValue = Number.MAX_VALUE;
  54444. var inv;
  54445. var min;
  54446. var max;
  54447. var temp;
  54448. if (Math.abs(this.direction.x) < 0.0000001) {
  54449. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54450. return false;
  54451. }
  54452. }
  54453. else {
  54454. inv = 1.0 / this.direction.x;
  54455. min = (minimum.x - this.origin.x) * inv;
  54456. max = (maximum.x - this.origin.x) * inv;
  54457. if (max === -Infinity) {
  54458. max = Infinity;
  54459. }
  54460. if (min > max) {
  54461. temp = min;
  54462. min = max;
  54463. max = temp;
  54464. }
  54465. d = Math.max(min, d);
  54466. maxValue = Math.min(max, maxValue);
  54467. if (d > maxValue) {
  54468. return false;
  54469. }
  54470. }
  54471. if (Math.abs(this.direction.y) < 0.0000001) {
  54472. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54473. return false;
  54474. }
  54475. }
  54476. else {
  54477. inv = 1.0 / this.direction.y;
  54478. min = (minimum.y - this.origin.y) * inv;
  54479. max = (maximum.y - this.origin.y) * inv;
  54480. if (max === -Infinity) {
  54481. max = Infinity;
  54482. }
  54483. if (min > max) {
  54484. temp = min;
  54485. min = max;
  54486. max = temp;
  54487. }
  54488. d = Math.max(min, d);
  54489. maxValue = Math.min(max, maxValue);
  54490. if (d > maxValue) {
  54491. return false;
  54492. }
  54493. }
  54494. if (Math.abs(this.direction.z) < 0.0000001) {
  54495. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54496. return false;
  54497. }
  54498. }
  54499. else {
  54500. inv = 1.0 / this.direction.z;
  54501. min = (minimum.z - this.origin.z) * inv;
  54502. max = (maximum.z - this.origin.z) * inv;
  54503. if (max === -Infinity) {
  54504. max = Infinity;
  54505. }
  54506. if (min > max) {
  54507. temp = min;
  54508. min = max;
  54509. max = temp;
  54510. }
  54511. d = Math.max(min, d);
  54512. maxValue = Math.min(max, maxValue);
  54513. if (d > maxValue) {
  54514. return false;
  54515. }
  54516. }
  54517. return true;
  54518. };
  54519. Ray.prototype.intersectsBox = function (box) {
  54520. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54521. };
  54522. Ray.prototype.intersectsSphere = function (sphere) {
  54523. var x = sphere.center.x - this.origin.x;
  54524. var y = sphere.center.y - this.origin.y;
  54525. var z = sphere.center.z - this.origin.z;
  54526. var pyth = (x * x) + (y * y) + (z * z);
  54527. var rr = sphere.radius * sphere.radius;
  54528. if (pyth <= rr) {
  54529. return true;
  54530. }
  54531. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54532. if (dot < 0.0) {
  54533. return false;
  54534. }
  54535. var temp = pyth - (dot * dot);
  54536. return temp <= rr;
  54537. };
  54538. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54539. if (!this._edge1) {
  54540. this._edge1 = BABYLON.Vector3.Zero();
  54541. this._edge2 = BABYLON.Vector3.Zero();
  54542. this._pvec = BABYLON.Vector3.Zero();
  54543. this._tvec = BABYLON.Vector3.Zero();
  54544. this._qvec = BABYLON.Vector3.Zero();
  54545. }
  54546. vertex1.subtractToRef(vertex0, this._edge1);
  54547. vertex2.subtractToRef(vertex0, this._edge2);
  54548. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54549. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54550. if (det === 0) {
  54551. return null;
  54552. }
  54553. var invdet = 1 / det;
  54554. this.origin.subtractToRef(vertex0, this._tvec);
  54555. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54556. if (bu < 0 || bu > 1.0) {
  54557. return null;
  54558. }
  54559. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54560. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54561. if (bv < 0 || bu + bv > 1.0) {
  54562. return null;
  54563. }
  54564. //check if the distance is longer than the predefined length.
  54565. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54566. if (distance > this.length) {
  54567. return null;
  54568. }
  54569. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54570. };
  54571. Ray.prototype.intersectsPlane = function (plane) {
  54572. var distance;
  54573. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54574. if (Math.abs(result1) < 9.99999997475243E-07) {
  54575. return null;
  54576. }
  54577. else {
  54578. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54579. distance = (-plane.d - result2) / result1;
  54580. if (distance < 0.0) {
  54581. if (distance < -9.99999997475243E-07) {
  54582. return null;
  54583. }
  54584. else {
  54585. return 0;
  54586. }
  54587. }
  54588. return distance;
  54589. }
  54590. };
  54591. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54592. var tm = BABYLON.Tmp.Matrix[0];
  54593. mesh.getWorldMatrix().invertToRef(tm);
  54594. if (this._tmpRay) {
  54595. Ray.TransformToRef(this, tm, this._tmpRay);
  54596. }
  54597. else {
  54598. this._tmpRay = Ray.Transform(this, tm);
  54599. }
  54600. return mesh.intersects(this._tmpRay, fastCheck);
  54601. };
  54602. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54603. if (results) {
  54604. results.length = 0;
  54605. }
  54606. else {
  54607. results = [];
  54608. }
  54609. for (var i = 0; i < meshes.length; i++) {
  54610. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54611. if (pickInfo.hit) {
  54612. results.push(pickInfo);
  54613. }
  54614. }
  54615. results.sort(this._comparePickingInfo);
  54616. return results;
  54617. };
  54618. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54619. if (pickingInfoA.distance < pickingInfoB.distance) {
  54620. return -1;
  54621. }
  54622. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54623. return 1;
  54624. }
  54625. else {
  54626. return 0;
  54627. }
  54628. };
  54629. /**
  54630. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54631. * @param sega the first point of the segment to test the intersection against
  54632. * @param segb the second point of the segment to test the intersection against
  54633. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54634. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54635. */
  54636. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54637. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54638. var u = segb.subtract(sega);
  54639. var v = rsegb.subtract(this.origin);
  54640. var w = sega.subtract(this.origin);
  54641. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54642. var b = BABYLON.Vector3.Dot(u, v);
  54643. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54644. var d = BABYLON.Vector3.Dot(u, w);
  54645. var e = BABYLON.Vector3.Dot(v, w);
  54646. var D = a * c - b * b; // always >= 0
  54647. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54648. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54649. // compute the line parameters of the two closest points
  54650. if (D < Ray.smallnum) { // the lines are almost parallel
  54651. sN = 0.0; // force using point P0 on segment S1
  54652. sD = 1.0; // to prevent possible division by 0.0 later
  54653. tN = e;
  54654. tD = c;
  54655. }
  54656. else { // get the closest points on the infinite lines
  54657. sN = (b * e - c * d);
  54658. tN = (a * e - b * d);
  54659. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54660. sN = 0.0;
  54661. tN = e;
  54662. tD = c;
  54663. }
  54664. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54665. sN = sD;
  54666. tN = e + b;
  54667. tD = c;
  54668. }
  54669. }
  54670. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54671. tN = 0.0;
  54672. // recompute sc for this edge
  54673. if (-d < 0.0) {
  54674. sN = 0.0;
  54675. }
  54676. else if (-d > a)
  54677. sN = sD;
  54678. else {
  54679. sN = -d;
  54680. sD = a;
  54681. }
  54682. }
  54683. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54684. tN = tD;
  54685. // recompute sc for this edge
  54686. if ((-d + b) < 0.0) {
  54687. sN = 0;
  54688. }
  54689. else if ((-d + b) > a) {
  54690. sN = sD;
  54691. }
  54692. else {
  54693. sN = (-d + b);
  54694. sD = a;
  54695. }
  54696. }
  54697. // finally do the division to get sc and tc
  54698. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54699. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54700. // get the difference of the two closest points
  54701. var qtc = v.multiplyByFloats(tc, tc, tc);
  54702. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54703. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54704. if (isIntersected) {
  54705. return qtc.length();
  54706. }
  54707. return -1;
  54708. };
  54709. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54710. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54711. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54712. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54713. this.direction.normalize();
  54714. return this;
  54715. };
  54716. // Statics
  54717. Ray.Zero = function () {
  54718. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54719. };
  54720. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54721. var result = Ray.Zero();
  54722. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54723. };
  54724. /**
  54725. * 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
  54726. * transformed to the given world matrix.
  54727. * @param origin The origin point
  54728. * @param end The end point
  54729. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54730. */
  54731. Ray.CreateNewFromTo = function (origin, end, world) {
  54732. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54733. var direction = end.subtract(origin);
  54734. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54735. direction.normalize();
  54736. return Ray.Transform(new Ray(origin, direction, length), world);
  54737. };
  54738. Ray.Transform = function (ray, matrix) {
  54739. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54740. Ray.TransformToRef(ray, matrix, result);
  54741. return result;
  54742. };
  54743. Ray.TransformToRef = function (ray, matrix, result) {
  54744. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54745. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54746. result.length = ray.length;
  54747. var dir = result.direction;
  54748. var len = dir.length();
  54749. if (!(len === 0 || len === 1)) {
  54750. var num = 1.0 / len;
  54751. dir.x *= num;
  54752. dir.y *= num;
  54753. dir.z *= num;
  54754. result.length *= len;
  54755. }
  54756. };
  54757. Ray.smallnum = 0.00000001;
  54758. Ray.rayl = 10e8;
  54759. return Ray;
  54760. }());
  54761. BABYLON.Ray = Ray;
  54762. })(BABYLON || (BABYLON = {}));
  54763. //# sourceMappingURL=babylon.ray.js.map
  54764. var BABYLON;
  54765. (function (BABYLON) {
  54766. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54767. if (boxMin.x > sphereCenter.x + sphereRadius)
  54768. return false;
  54769. if (sphereCenter.x - sphereRadius > boxMax.x)
  54770. return false;
  54771. if (boxMin.y > sphereCenter.y + sphereRadius)
  54772. return false;
  54773. if (sphereCenter.y - sphereRadius > boxMax.y)
  54774. return false;
  54775. if (boxMin.z > sphereCenter.z + sphereRadius)
  54776. return false;
  54777. if (sphereCenter.z - sphereRadius > boxMax.z)
  54778. return false;
  54779. return true;
  54780. };
  54781. var getLowestRoot = (function () {
  54782. var result = { root: 0, found: false };
  54783. return function (a, b, c, maxR) {
  54784. result.root = 0;
  54785. result.found = false;
  54786. var determinant = b * b - 4.0 * a * c;
  54787. if (determinant < 0)
  54788. return result;
  54789. var sqrtD = Math.sqrt(determinant);
  54790. var r1 = (-b - sqrtD) / (2.0 * a);
  54791. var r2 = (-b + sqrtD) / (2.0 * a);
  54792. if (r1 > r2) {
  54793. var temp = r2;
  54794. r2 = r1;
  54795. r1 = temp;
  54796. }
  54797. if (r1 > 0 && r1 < maxR) {
  54798. result.root = r1;
  54799. result.found = true;
  54800. return result;
  54801. }
  54802. if (r2 > 0 && r2 < maxR) {
  54803. result.root = r2;
  54804. result.found = true;
  54805. return result;
  54806. }
  54807. return result;
  54808. };
  54809. })();
  54810. var Collider = /** @class */ (function () {
  54811. function Collider() {
  54812. this._collisionPoint = BABYLON.Vector3.Zero();
  54813. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54814. this._tempVector = BABYLON.Vector3.Zero();
  54815. this._tempVector2 = BABYLON.Vector3.Zero();
  54816. this._tempVector3 = BABYLON.Vector3.Zero();
  54817. this._tempVector4 = BABYLON.Vector3.Zero();
  54818. this._edge = BABYLON.Vector3.Zero();
  54819. this._baseToVertex = BABYLON.Vector3.Zero();
  54820. this._destinationPoint = BABYLON.Vector3.Zero();
  54821. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54822. this._displacementVector = BABYLON.Vector3.Zero();
  54823. /** @hidden */
  54824. this._radius = BABYLON.Vector3.One();
  54825. /** @hidden */
  54826. this._retry = 0;
  54827. /** @hidden */
  54828. this._basePointWorld = BABYLON.Vector3.Zero();
  54829. this._velocityWorld = BABYLON.Vector3.Zero();
  54830. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54831. this._collisionMask = -1;
  54832. }
  54833. Object.defineProperty(Collider.prototype, "collisionMask", {
  54834. get: function () {
  54835. return this._collisionMask;
  54836. },
  54837. set: function (mask) {
  54838. this._collisionMask = !isNaN(mask) ? mask : -1;
  54839. },
  54840. enumerable: true,
  54841. configurable: true
  54842. });
  54843. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54844. /**
  54845. * Gets the plane normal used to compute the sliding response (in local space)
  54846. */
  54847. get: function () {
  54848. return this._slidePlaneNormal;
  54849. },
  54850. enumerable: true,
  54851. configurable: true
  54852. });
  54853. // Methods
  54854. /** @hidden */
  54855. Collider.prototype._initialize = function (source, dir, e) {
  54856. this._velocity = dir;
  54857. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54858. this._basePoint = source;
  54859. source.multiplyToRef(this._radius, this._basePointWorld);
  54860. dir.multiplyToRef(this._radius, this._velocityWorld);
  54861. this._velocityWorldLength = this._velocityWorld.length();
  54862. this._epsilon = e;
  54863. this.collisionFound = false;
  54864. };
  54865. /** @hidden */
  54866. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54867. pa.subtractToRef(point, this._tempVector);
  54868. pb.subtractToRef(point, this._tempVector2);
  54869. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54870. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54871. if (d < 0)
  54872. return false;
  54873. pc.subtractToRef(point, this._tempVector3);
  54874. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54875. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54876. if (d < 0)
  54877. return false;
  54878. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54879. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54880. return d >= 0;
  54881. };
  54882. /** @hidden */
  54883. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54884. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54885. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54886. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54887. return false;
  54888. }
  54889. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54890. return false;
  54891. return true;
  54892. };
  54893. /** @hidden */
  54894. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54895. var t0;
  54896. var embeddedInPlane = false;
  54897. //defensive programming, actually not needed.
  54898. if (!trianglePlaneArray) {
  54899. trianglePlaneArray = [];
  54900. }
  54901. if (!trianglePlaneArray[faceIndex]) {
  54902. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54903. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54904. }
  54905. var trianglePlane = trianglePlaneArray[faceIndex];
  54906. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54907. return;
  54908. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54909. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54910. if (normalDotVelocity == 0) {
  54911. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54912. return;
  54913. embeddedInPlane = true;
  54914. t0 = 0;
  54915. }
  54916. else {
  54917. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54918. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54919. if (t0 > t1) {
  54920. var temp = t1;
  54921. t1 = t0;
  54922. t0 = temp;
  54923. }
  54924. if (t0 > 1.0 || t1 < 0.0)
  54925. return;
  54926. if (t0 < 0)
  54927. t0 = 0;
  54928. if (t0 > 1.0)
  54929. t0 = 1.0;
  54930. }
  54931. this._collisionPoint.copyFromFloats(0, 0, 0);
  54932. var found = false;
  54933. var t = 1.0;
  54934. if (!embeddedInPlane) {
  54935. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54936. this._velocity.scaleToRef(t0, this._tempVector);
  54937. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54938. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54939. found = true;
  54940. t = t0;
  54941. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54942. }
  54943. }
  54944. if (!found) {
  54945. var velocitySquaredLength = this._velocity.lengthSquared();
  54946. var a = velocitySquaredLength;
  54947. this._basePoint.subtractToRef(p1, this._tempVector);
  54948. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54949. var c = this._tempVector.lengthSquared() - 1.0;
  54950. var lowestRoot = getLowestRoot(a, b, c, t);
  54951. if (lowestRoot.found) {
  54952. t = lowestRoot.root;
  54953. found = true;
  54954. this._collisionPoint.copyFrom(p1);
  54955. }
  54956. this._basePoint.subtractToRef(p2, this._tempVector);
  54957. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54958. c = this._tempVector.lengthSquared() - 1.0;
  54959. lowestRoot = getLowestRoot(a, b, c, t);
  54960. if (lowestRoot.found) {
  54961. t = lowestRoot.root;
  54962. found = true;
  54963. this._collisionPoint.copyFrom(p2);
  54964. }
  54965. this._basePoint.subtractToRef(p3, this._tempVector);
  54966. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54967. c = this._tempVector.lengthSquared() - 1.0;
  54968. lowestRoot = getLowestRoot(a, b, c, t);
  54969. if (lowestRoot.found) {
  54970. t = lowestRoot.root;
  54971. found = true;
  54972. this._collisionPoint.copyFrom(p3);
  54973. }
  54974. p2.subtractToRef(p1, this._edge);
  54975. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54976. var edgeSquaredLength = this._edge.lengthSquared();
  54977. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54978. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54979. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54980. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54981. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54982. lowestRoot = getLowestRoot(a, b, c, t);
  54983. if (lowestRoot.found) {
  54984. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54985. if (f >= 0.0 && f <= 1.0) {
  54986. t = lowestRoot.root;
  54987. found = true;
  54988. this._edge.scaleInPlace(f);
  54989. p1.addToRef(this._edge, this._collisionPoint);
  54990. }
  54991. }
  54992. p3.subtractToRef(p2, this._edge);
  54993. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54994. edgeSquaredLength = this._edge.lengthSquared();
  54995. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54996. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54997. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54998. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54999. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55000. lowestRoot = getLowestRoot(a, b, c, t);
  55001. if (lowestRoot.found) {
  55002. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55003. if (f >= 0.0 && f <= 1.0) {
  55004. t = lowestRoot.root;
  55005. found = true;
  55006. this._edge.scaleInPlace(f);
  55007. p2.addToRef(this._edge, this._collisionPoint);
  55008. }
  55009. }
  55010. p1.subtractToRef(p3, this._edge);
  55011. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55012. edgeSquaredLength = this._edge.lengthSquared();
  55013. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55014. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55015. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55016. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55017. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55018. lowestRoot = getLowestRoot(a, b, c, t);
  55019. if (lowestRoot.found) {
  55020. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55021. if (f >= 0.0 && f <= 1.0) {
  55022. t = lowestRoot.root;
  55023. found = true;
  55024. this._edge.scaleInPlace(f);
  55025. p3.addToRef(this._edge, this._collisionPoint);
  55026. }
  55027. }
  55028. }
  55029. if (found) {
  55030. var distToCollision = t * this._velocity.length();
  55031. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55032. if (!this.intersectionPoint) {
  55033. this.intersectionPoint = this._collisionPoint.clone();
  55034. }
  55035. else {
  55036. this.intersectionPoint.copyFrom(this._collisionPoint);
  55037. }
  55038. this._nearestDistance = distToCollision;
  55039. this.collisionFound = true;
  55040. }
  55041. }
  55042. };
  55043. /** @hidden */
  55044. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55045. for (var i = indexStart; i < indexEnd; i += 3) {
  55046. var p1 = pts[indices[i] - decal];
  55047. var p2 = pts[indices[i + 1] - decal];
  55048. var p3 = pts[indices[i + 2] - decal];
  55049. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55050. }
  55051. };
  55052. /** @hidden */
  55053. Collider.prototype._getResponse = function (pos, vel) {
  55054. pos.addToRef(vel, this._destinationPoint);
  55055. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55056. this._basePoint.addToRef(vel, pos);
  55057. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55058. this._slidePlaneNormal.normalize();
  55059. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55060. pos.addInPlace(this._displacementVector);
  55061. this.intersectionPoint.addInPlace(this._displacementVector);
  55062. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55063. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55064. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55065. };
  55066. return Collider;
  55067. }());
  55068. BABYLON.Collider = Collider;
  55069. })(BABYLON || (BABYLON = {}));
  55070. //# sourceMappingURL=babylon.collider.js.map
  55071. var BABYLON;
  55072. (function (BABYLON) {
  55073. //WebWorker code will be inserted to this variable.
  55074. BABYLON.CollisionWorker = "";
  55075. /** Defines supported task for worker process */
  55076. var WorkerTaskType;
  55077. (function (WorkerTaskType) {
  55078. /** Initialization */
  55079. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55080. /** Update of geometry */
  55081. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55082. /** Evaluate collision */
  55083. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55084. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55085. /** Defines kind of replies returned by worker */
  55086. var WorkerReplyType;
  55087. (function (WorkerReplyType) {
  55088. /** Success */
  55089. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55090. /** Unkown error */
  55091. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55092. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55093. var CollisionCoordinatorWorker = /** @class */ (function () {
  55094. function CollisionCoordinatorWorker() {
  55095. var _this = this;
  55096. this._scaledPosition = BABYLON.Vector3.Zero();
  55097. this._scaledVelocity = BABYLON.Vector3.Zero();
  55098. this.onMeshUpdated = function (transformNode) {
  55099. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55100. };
  55101. this.onGeometryUpdated = function (geometry) {
  55102. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55103. };
  55104. this._afterRender = function () {
  55105. if (!_this._init)
  55106. return;
  55107. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55108. return;
  55109. }
  55110. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55111. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55112. if (_this._runningUpdated > 4) {
  55113. return;
  55114. }
  55115. ++_this._runningUpdated;
  55116. var payload = {
  55117. updatedMeshes: _this._addUpdateMeshesList,
  55118. updatedGeometries: _this._addUpdateGeometriesList,
  55119. removedGeometries: _this._toRemoveGeometryArray,
  55120. removedMeshes: _this._toRemoveMeshesArray
  55121. };
  55122. var message = {
  55123. payload: payload,
  55124. taskType: WorkerTaskType.UPDATE
  55125. };
  55126. var serializable = [];
  55127. for (var id in payload.updatedGeometries) {
  55128. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55129. //prepare transferables
  55130. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55131. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55132. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55133. }
  55134. }
  55135. _this._worker.postMessage(message, serializable);
  55136. _this._addUpdateMeshesList = {};
  55137. _this._addUpdateGeometriesList = {};
  55138. _this._toRemoveGeometryArray = [];
  55139. _this._toRemoveMeshesArray = [];
  55140. };
  55141. this._onMessageFromWorker = function (e) {
  55142. var returnData = e.data;
  55143. if (returnData.error != WorkerReplyType.SUCCESS) {
  55144. //TODO what errors can be returned from the worker?
  55145. BABYLON.Tools.Warn("error returned from worker!");
  55146. return;
  55147. }
  55148. switch (returnData.taskType) {
  55149. case WorkerTaskType.INIT:
  55150. _this._init = true;
  55151. //Update the worked with ALL of the scene's current state
  55152. _this._scene.meshes.forEach(function (mesh) {
  55153. _this.onMeshAdded(mesh);
  55154. });
  55155. _this._scene.getGeometries().forEach(function (geometry) {
  55156. _this.onGeometryAdded(geometry);
  55157. });
  55158. break;
  55159. case WorkerTaskType.UPDATE:
  55160. _this._runningUpdated--;
  55161. break;
  55162. case WorkerTaskType.COLLIDE:
  55163. var returnPayload = returnData.payload;
  55164. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55165. return;
  55166. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55167. if (callback) {
  55168. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55169. if (mesh) {
  55170. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55171. }
  55172. }
  55173. //cleanup
  55174. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55175. break;
  55176. }
  55177. };
  55178. this._collisionsCallbackArray = [];
  55179. this._init = false;
  55180. this._runningUpdated = 0;
  55181. this._addUpdateMeshesList = {};
  55182. this._addUpdateGeometriesList = {};
  55183. this._toRemoveGeometryArray = [];
  55184. this._toRemoveMeshesArray = [];
  55185. }
  55186. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55187. if (!this._init)
  55188. return;
  55189. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55190. return;
  55191. position.divideToRef(collider._radius, this._scaledPosition);
  55192. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55193. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55194. var payload = {
  55195. collider: {
  55196. position: this._scaledPosition.asArray(),
  55197. velocity: this._scaledVelocity.asArray(),
  55198. radius: collider._radius.asArray()
  55199. },
  55200. collisionId: collisionIndex,
  55201. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55202. maximumRetry: maximumRetry
  55203. };
  55204. var message = {
  55205. payload: payload,
  55206. taskType: WorkerTaskType.COLLIDE
  55207. };
  55208. this._worker.postMessage(message);
  55209. };
  55210. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55211. this._scene = scene;
  55212. this._scene.registerAfterRender(this._afterRender);
  55213. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55214. this._worker = new Worker(workerUrl);
  55215. this._worker.onmessage = this._onMessageFromWorker;
  55216. var message = {
  55217. payload: {},
  55218. taskType: WorkerTaskType.INIT
  55219. };
  55220. this._worker.postMessage(message);
  55221. };
  55222. CollisionCoordinatorWorker.prototype.destroy = function () {
  55223. this._scene.unregisterAfterRender(this._afterRender);
  55224. this._worker.terminate();
  55225. };
  55226. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55227. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55228. this.onMeshUpdated(mesh);
  55229. };
  55230. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55231. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55232. };
  55233. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55234. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55235. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55236. this.onGeometryUpdated(geometry);
  55237. };
  55238. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55239. this._toRemoveGeometryArray.push(geometry.id);
  55240. };
  55241. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55242. var submeshes = [];
  55243. if (mesh.subMeshes) {
  55244. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55245. var boundingInfo = sm.getBoundingInfo();
  55246. return {
  55247. position: idx,
  55248. verticesStart: sm.verticesStart,
  55249. verticesCount: sm.verticesCount,
  55250. indexStart: sm.indexStart,
  55251. indexCount: sm.indexCount,
  55252. hasMaterial: !!sm.getMaterial(),
  55253. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55254. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55255. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55256. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55257. };
  55258. });
  55259. }
  55260. var geometryId = null;
  55261. if (mesh instanceof BABYLON.Mesh) {
  55262. var geometry = mesh.geometry;
  55263. geometryId = geometry ? geometry.id : null;
  55264. }
  55265. else if (mesh instanceof BABYLON.InstancedMesh) {
  55266. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55267. geometryId = geometry ? geometry.id : null;
  55268. }
  55269. var boundingInfo = mesh.getBoundingInfo();
  55270. return {
  55271. uniqueId: mesh.uniqueId,
  55272. id: mesh.id,
  55273. name: mesh.name,
  55274. geometryId: geometryId,
  55275. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55276. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55277. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55278. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55279. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55280. subMeshes: submeshes,
  55281. checkCollisions: mesh.checkCollisions
  55282. };
  55283. };
  55284. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55285. return {
  55286. id: geometry.id,
  55287. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55288. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55289. indices: new Uint32Array(geometry.getIndices() || []),
  55290. };
  55291. };
  55292. return CollisionCoordinatorWorker;
  55293. }());
  55294. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55295. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55296. function CollisionCoordinatorLegacy() {
  55297. this._scaledPosition = BABYLON.Vector3.Zero();
  55298. this._scaledVelocity = BABYLON.Vector3.Zero();
  55299. this._finalPosition = BABYLON.Vector3.Zero();
  55300. }
  55301. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55302. position.divideToRef(collider._radius, this._scaledPosition);
  55303. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55304. collider.collidedMesh = null;
  55305. collider._retry = 0;
  55306. collider._initialVelocity = this._scaledVelocity;
  55307. collider._initialPosition = this._scaledPosition;
  55308. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55309. this._finalPosition.multiplyInPlace(collider._radius);
  55310. //run the callback
  55311. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55312. };
  55313. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55314. this._scene = scene;
  55315. };
  55316. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55317. //Legacy need no destruction method.
  55318. };
  55319. //No update in legacy mode
  55320. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55321. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55322. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55323. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55324. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55325. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55326. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55327. if (excludedMesh === void 0) { excludedMesh = null; }
  55328. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55329. if (collider._retry >= maximumRetry) {
  55330. finalPosition.copyFrom(position);
  55331. return;
  55332. }
  55333. // Check if this is a mesh else camera or -1
  55334. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55335. collider._initialize(position, velocity, closeDistance);
  55336. // Check all meshes
  55337. for (var index = 0; index < this._scene.meshes.length; index++) {
  55338. var mesh = this._scene.meshes[index];
  55339. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55340. mesh._checkCollision(collider);
  55341. }
  55342. }
  55343. if (!collider.collisionFound) {
  55344. position.addToRef(velocity, finalPosition);
  55345. return;
  55346. }
  55347. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55348. collider._getResponse(position, velocity);
  55349. }
  55350. if (velocity.length() <= closeDistance) {
  55351. finalPosition.copyFrom(position);
  55352. return;
  55353. }
  55354. collider._retry++;
  55355. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55356. };
  55357. return CollisionCoordinatorLegacy;
  55358. }());
  55359. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55360. })(BABYLON || (BABYLON = {}));
  55361. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55362. var BABYLON;
  55363. (function (BABYLON) {
  55364. /**
  55365. * A particle represents one of the element emitted by a particle system.
  55366. * This is mainly define by its coordinates, direction, velocity and age.
  55367. */
  55368. var Particle = /** @class */ (function () {
  55369. /**
  55370. * Creates a new instance Particle
  55371. * @param particleSystem the particle system the particle belongs to
  55372. */
  55373. function Particle(
  55374. /**
  55375. * The particle system the particle belongs to.
  55376. */
  55377. particleSystem) {
  55378. this.particleSystem = particleSystem;
  55379. /**
  55380. * The world position of the particle in the scene.
  55381. */
  55382. this.position = BABYLON.Vector3.Zero();
  55383. /**
  55384. * The world direction of the particle in the scene.
  55385. */
  55386. this.direction = BABYLON.Vector3.Zero();
  55387. /**
  55388. * The color of the particle.
  55389. */
  55390. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55391. /**
  55392. * The color change of the particle per step.
  55393. */
  55394. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55395. /**
  55396. * Defines how long will the life of the particle be.
  55397. */
  55398. this.lifeTime = 1.0;
  55399. /**
  55400. * The current age of the particle.
  55401. */
  55402. this.age = 0;
  55403. /**
  55404. * The current size of the particle.
  55405. */
  55406. this.size = 0;
  55407. /**
  55408. * The current scale of the particle.
  55409. */
  55410. this.scale = new BABYLON.Vector2(1, 1);
  55411. /**
  55412. * The current angle of the particle.
  55413. */
  55414. this.angle = 0;
  55415. /**
  55416. * Defines how fast is the angle changing.
  55417. */
  55418. this.angularSpeed = 0;
  55419. /**
  55420. * Defines the cell index used by the particle to be rendered from a sprite.
  55421. */
  55422. this.cellIndex = 0;
  55423. /** @hidden */
  55424. this._attachedSubEmitters = null;
  55425. /** @hidden */
  55426. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55427. /** @hidden */
  55428. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55429. /** @hidden */
  55430. this._currentSize1 = 0;
  55431. /** @hidden */
  55432. this._currentSize2 = 0;
  55433. /** @hidden */
  55434. this._currentAngularSpeed1 = 0;
  55435. /** @hidden */
  55436. this._currentAngularSpeed2 = 0;
  55437. /** @hidden */
  55438. this._currentVelocity1 = 0;
  55439. /** @hidden */
  55440. this._currentVelocity2 = 0;
  55441. /** @hidden */
  55442. this._currentLimitVelocity1 = 0;
  55443. /** @hidden */
  55444. this._currentLimitVelocity2 = 0;
  55445. /** @hidden */
  55446. this._currentDrag1 = 0;
  55447. /** @hidden */
  55448. this._currentDrag2 = 0;
  55449. this.id = Particle._Count++;
  55450. if (!this.particleSystem.isAnimationSheetEnabled) {
  55451. return;
  55452. }
  55453. this.updateCellInfoFromSystem();
  55454. }
  55455. Particle.prototype.updateCellInfoFromSystem = function () {
  55456. this.cellIndex = this.particleSystem.startSpriteCellID;
  55457. };
  55458. /**
  55459. * Defines how the sprite cell index is updated for the particle
  55460. */
  55461. Particle.prototype.updateCellIndex = function () {
  55462. var offsetAge = this.age;
  55463. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  55464. if (this.particleSystem.spriteRandomStartCell) {
  55465. if (this._randomCellOffset === undefined) {
  55466. this._randomCellOffset = Math.random() * this.lifeTime;
  55467. }
  55468. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  55469. changeSpeed = 1;
  55470. offsetAge = this._randomCellOffset;
  55471. }
  55472. else {
  55473. offsetAge += this._randomCellOffset;
  55474. }
  55475. }
  55476. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55477. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  55478. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55479. };
  55480. /** @hidden */
  55481. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  55482. if (subEmitter.particleSystem.emitter.position) {
  55483. var emitterMesh = subEmitter.particleSystem.emitter;
  55484. emitterMesh.position.copyFrom(this.position);
  55485. if (subEmitter.inheritDirection) {
  55486. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  55487. // Look at using Y as forward
  55488. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  55489. }
  55490. emitterMesh.computeWorldMatrix(true);
  55491. }
  55492. else {
  55493. var emitterPosition = subEmitter.particleSystem.emitter;
  55494. emitterPosition.copyFrom(this.position);
  55495. }
  55496. // Set inheritedVelocityOffset to be used when new particles are created
  55497. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  55498. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  55499. };
  55500. /** @hidden */
  55501. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  55502. var _this = this;
  55503. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  55504. this._attachedSubEmitters.forEach(function (subEmitter) {
  55505. _this, _this._inheritParticleInfoToSubEmitter(subEmitter);
  55506. });
  55507. }
  55508. };
  55509. /** @hidden */
  55510. Particle.prototype._reset = function () {
  55511. this.age = 0;
  55512. this._currentColorGradient = null;
  55513. this._currentSizeGradient = null;
  55514. this._currentAngularSpeedGradient = null;
  55515. this._currentVelocityGradient = null;
  55516. this._currentLimitVelocityGradient = null;
  55517. this._currentDragGradient = null;
  55518. this.cellIndex = this.particleSystem.startSpriteCellID;
  55519. this._randomCellOffset = undefined;
  55520. };
  55521. /**
  55522. * Copy the properties of particle to another one.
  55523. * @param other the particle to copy the information to.
  55524. */
  55525. Particle.prototype.copyTo = function (other) {
  55526. other.position.copyFrom(this.position);
  55527. if (this._initialDirection) {
  55528. if (other._initialDirection) {
  55529. other._initialDirection.copyFrom(this._initialDirection);
  55530. }
  55531. else {
  55532. other._initialDirection = this._initialDirection.clone();
  55533. }
  55534. }
  55535. else {
  55536. other._initialDirection = null;
  55537. }
  55538. other.direction.copyFrom(this.direction);
  55539. other.color.copyFrom(this.color);
  55540. other.colorStep.copyFrom(this.colorStep);
  55541. other.lifeTime = this.lifeTime;
  55542. other.age = this.age;
  55543. other._randomCellOffset = undefined;
  55544. other.size = this.size;
  55545. other.scale.copyFrom(this.scale);
  55546. other.angle = this.angle;
  55547. other.angularSpeed = this.angularSpeed;
  55548. other.particleSystem = this.particleSystem;
  55549. other.cellIndex = this.cellIndex;
  55550. other.id = this.id;
  55551. other._attachedSubEmitters = this._attachedSubEmitters;
  55552. if (this._currentColorGradient) {
  55553. other._currentColorGradient = this._currentColorGradient;
  55554. other._currentColor1.copyFrom(this._currentColor1);
  55555. other._currentColor2.copyFrom(this._currentColor2);
  55556. }
  55557. if (this._currentSizeGradient) {
  55558. other._currentSizeGradient = this._currentSizeGradient;
  55559. other._currentSize1 = this._currentSize1;
  55560. other._currentSize2 = this._currentSize2;
  55561. }
  55562. if (this._currentAngularSpeedGradient) {
  55563. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55564. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55565. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55566. }
  55567. if (this._currentVelocityGradient) {
  55568. other._currentVelocityGradient = this._currentVelocityGradient;
  55569. other._currentVelocity1 = this._currentVelocity1;
  55570. other._currentVelocity2 = this._currentVelocity2;
  55571. }
  55572. if (this._currentLimitVelocityGradient) {
  55573. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55574. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55575. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55576. }
  55577. if (this._currentDragGradient) {
  55578. other._currentDragGradient = this._currentDragGradient;
  55579. other._currentDrag1 = this._currentDrag1;
  55580. other._currentDrag2 = this._currentDrag2;
  55581. }
  55582. if (this.particleSystem.isAnimationSheetEnabled) {
  55583. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55584. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55585. }
  55586. if (this.particleSystem.useRampGradients) {
  55587. other.remapData.copyFrom(this.remapData);
  55588. }
  55589. if (this._randomNoiseCoordinates1) {
  55590. if (other._randomNoiseCoordinates1) {
  55591. other._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  55592. other._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  55593. }
  55594. else {
  55595. other._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55596. other._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55597. }
  55598. }
  55599. };
  55600. Particle._Count = 0;
  55601. return Particle;
  55602. }());
  55603. BABYLON.Particle = Particle;
  55604. })(BABYLON || (BABYLON = {}));
  55605. //# sourceMappingURL=babylon.particle.js.map
  55606. var BABYLON;
  55607. (function (BABYLON) {
  55608. /**
  55609. * This represents the base class for particle system in Babylon.
  55610. * 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.
  55611. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55612. * @example https://doc.babylonjs.com/babylon101/particles
  55613. */
  55614. var BaseParticleSystem = /** @class */ (function () {
  55615. /**
  55616. * Instantiates a particle system.
  55617. * 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.
  55618. * @param name The name of the particle system
  55619. */
  55620. function BaseParticleSystem(name) {
  55621. /**
  55622. * List of animations used by the particle system.
  55623. */
  55624. this.animations = [];
  55625. /**
  55626. * The rendering group used by the Particle system to chose when to render.
  55627. */
  55628. this.renderingGroupId = 0;
  55629. /**
  55630. * The emitter represents the Mesh or position we are attaching the particle system to.
  55631. */
  55632. this.emitter = null;
  55633. /**
  55634. * The maximum number of particles to emit per frame
  55635. */
  55636. this.emitRate = 10;
  55637. /**
  55638. * If you want to launch only a few particles at once, that can be done, as well.
  55639. */
  55640. this.manualEmitCount = -1;
  55641. /**
  55642. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55643. */
  55644. this.updateSpeed = 0.01;
  55645. /**
  55646. * The amount of time the particle system is running (depends of the overall update speed).
  55647. */
  55648. this.targetStopDuration = 0;
  55649. /**
  55650. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55651. */
  55652. this.disposeOnStop = false;
  55653. /**
  55654. * Minimum power of emitting particles.
  55655. */
  55656. this.minEmitPower = 1;
  55657. /**
  55658. * Maximum power of emitting particles.
  55659. */
  55660. this.maxEmitPower = 1;
  55661. /**
  55662. * Minimum life time of emitting particles.
  55663. */
  55664. this.minLifeTime = 1;
  55665. /**
  55666. * Maximum life time of emitting particles.
  55667. */
  55668. this.maxLifeTime = 1;
  55669. /**
  55670. * Minimum Size of emitting particles.
  55671. */
  55672. this.minSize = 1;
  55673. /**
  55674. * Maximum Size of emitting particles.
  55675. */
  55676. this.maxSize = 1;
  55677. /**
  55678. * Minimum scale of emitting particles on X axis.
  55679. */
  55680. this.minScaleX = 1;
  55681. /**
  55682. * Maximum scale of emitting particles on X axis.
  55683. */
  55684. this.maxScaleX = 1;
  55685. /**
  55686. * Minimum scale of emitting particles on Y axis.
  55687. */
  55688. this.minScaleY = 1;
  55689. /**
  55690. * Maximum scale of emitting particles on Y axis.
  55691. */
  55692. this.maxScaleY = 1;
  55693. /**
  55694. * Gets or sets the minimal initial rotation in radians.
  55695. */
  55696. this.minInitialRotation = 0;
  55697. /**
  55698. * Gets or sets the maximal initial rotation in radians.
  55699. */
  55700. this.maxInitialRotation = 0;
  55701. /**
  55702. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55703. */
  55704. this.minAngularSpeed = 0;
  55705. /**
  55706. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55707. */
  55708. this.maxAngularSpeed = 0;
  55709. /**
  55710. * The layer mask we are rendering the particles through.
  55711. */
  55712. this.layerMask = 0x0FFFFFFF;
  55713. /**
  55714. * This can help using your own shader to render the particle system.
  55715. * The according effect will be created
  55716. */
  55717. this.customShader = null;
  55718. /**
  55719. * By default particle system starts as soon as they are created. This prevents the
  55720. * automatic start to happen and let you decide when to start emitting particles.
  55721. */
  55722. this.preventAutoStart = false;
  55723. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55724. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55725. /**
  55726. * Callback triggered when the particle animation is ending.
  55727. */
  55728. this.onAnimationEnd = null;
  55729. /**
  55730. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55731. */
  55732. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55733. /**
  55734. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55735. * to override the particles.
  55736. */
  55737. this.forceDepthWrite = false;
  55738. /** 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 */
  55739. this.preWarmCycles = 0;
  55740. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55741. this.preWarmStepOffset = 1;
  55742. /**
  55743. * 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)
  55744. */
  55745. this.spriteCellChangeSpeed = 1;
  55746. /**
  55747. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55748. */
  55749. this.startSpriteCellID = 0;
  55750. /**
  55751. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55752. */
  55753. this.endSpriteCellID = 0;
  55754. /**
  55755. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55756. */
  55757. this.spriteCellWidth = 0;
  55758. /**
  55759. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55760. */
  55761. this.spriteCellHeight = 0;
  55762. /**
  55763. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55764. */
  55765. this.spriteRandomStartCell = false;
  55766. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55767. this.translationPivot = new BABYLON.Vector2(0, 0);
  55768. /**
  55769. * You can use gravity if you want to give an orientation to your particles.
  55770. */
  55771. this.gravity = BABYLON.Vector3.Zero();
  55772. this._colorGradients = null;
  55773. this._sizeGradients = null;
  55774. this._lifeTimeGradients = null;
  55775. this._angularSpeedGradients = null;
  55776. this._velocityGradients = null;
  55777. this._limitVelocityGradients = null;
  55778. this._dragGradients = null;
  55779. this._emitRateGradients = null;
  55780. this._startSizeGradients = null;
  55781. this._rampGradients = null;
  55782. this._colorRemapGradients = null;
  55783. this._alphaRemapGradients = null;
  55784. /**
  55785. * Defines the delay in milliseconds before starting the system (0 by default)
  55786. */
  55787. this.startDelay = 0;
  55788. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55789. this.limitVelocityDamping = 0.4;
  55790. /**
  55791. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55792. */
  55793. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55794. /**
  55795. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55796. */
  55797. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55798. /**
  55799. * Color the particle will have at the end of its lifetime
  55800. */
  55801. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55802. /**
  55803. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55804. */
  55805. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55806. /**
  55807. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55808. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55809. */
  55810. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55811. this._isBillboardBased = true;
  55812. /**
  55813. * Local cache of defines for image processing.
  55814. */
  55815. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55816. this.id = name;
  55817. this.name = name;
  55818. }
  55819. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55820. /**
  55821. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55822. */
  55823. get: function () {
  55824. return this._isAnimationSheetEnabled;
  55825. },
  55826. set: function (value) {
  55827. if (this._isAnimationSheetEnabled == value) {
  55828. return;
  55829. }
  55830. this._isAnimationSheetEnabled = value;
  55831. this._reset();
  55832. },
  55833. enumerable: true,
  55834. configurable: true
  55835. });
  55836. /**
  55837. * Get hosting scene
  55838. * @returns the scene
  55839. */
  55840. BaseParticleSystem.prototype.getScene = function () {
  55841. return this._scene;
  55842. };
  55843. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  55844. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  55845. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  55846. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  55847. };
  55848. /**
  55849. * Gets the current list of drag gradients.
  55850. * You must use addDragGradient and removeDragGradient to udpate this list
  55851. * @returns the list of drag gradients
  55852. */
  55853. BaseParticleSystem.prototype.getDragGradients = function () {
  55854. return this._dragGradients;
  55855. };
  55856. /**
  55857. * Gets the current list of limit velocity gradients.
  55858. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55859. * @returns the list of limit velocity gradients
  55860. */
  55861. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55862. return this._limitVelocityGradients;
  55863. };
  55864. /**
  55865. * Gets the current list of color gradients.
  55866. * You must use addColorGradient and removeColorGradient to udpate this list
  55867. * @returns the list of color gradients
  55868. */
  55869. BaseParticleSystem.prototype.getColorGradients = function () {
  55870. return this._colorGradients;
  55871. };
  55872. /**
  55873. * Gets the current list of size gradients.
  55874. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55875. * @returns the list of size gradients
  55876. */
  55877. BaseParticleSystem.prototype.getSizeGradients = function () {
  55878. return this._sizeGradients;
  55879. };
  55880. /**
  55881. * Gets the current list of color remap gradients.
  55882. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55883. * @returns the list of color remap gradients
  55884. */
  55885. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55886. return this._colorRemapGradients;
  55887. };
  55888. /**
  55889. * Gets the current list of alpha remap gradients.
  55890. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55891. * @returns the list of alpha remap gradients
  55892. */
  55893. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55894. return this._alphaRemapGradients;
  55895. };
  55896. /**
  55897. * Gets the current list of life time gradients.
  55898. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55899. * @returns the list of life time gradients
  55900. */
  55901. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55902. return this._lifeTimeGradients;
  55903. };
  55904. /**
  55905. * Gets the current list of angular speed gradients.
  55906. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55907. * @returns the list of angular speed gradients
  55908. */
  55909. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55910. return this._angularSpeedGradients;
  55911. };
  55912. /**
  55913. * Gets the current list of velocity gradients.
  55914. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55915. * @returns the list of velocity gradients
  55916. */
  55917. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55918. return this._velocityGradients;
  55919. };
  55920. /**
  55921. * Gets the current list of start size gradients.
  55922. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55923. * @returns the list of start size gradients
  55924. */
  55925. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55926. return this._startSizeGradients;
  55927. };
  55928. /**
  55929. * Gets the current list of emit rate gradients.
  55930. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55931. * @returns the list of emit rate gradients
  55932. */
  55933. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55934. return this._emitRateGradients;
  55935. };
  55936. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55937. /**
  55938. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55939. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55940. */
  55941. get: function () {
  55942. if (this.particleEmitterType.direction1) {
  55943. return this.particleEmitterType.direction1;
  55944. }
  55945. return BABYLON.Vector3.Zero();
  55946. },
  55947. set: function (value) {
  55948. if (this.particleEmitterType.direction1) {
  55949. this.particleEmitterType.direction1 = value;
  55950. }
  55951. },
  55952. enumerable: true,
  55953. configurable: true
  55954. });
  55955. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55956. /**
  55957. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55958. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55959. */
  55960. get: function () {
  55961. if (this.particleEmitterType.direction2) {
  55962. return this.particleEmitterType.direction2;
  55963. }
  55964. return BABYLON.Vector3.Zero();
  55965. },
  55966. set: function (value) {
  55967. if (this.particleEmitterType.direction2) {
  55968. this.particleEmitterType.direction2 = value;
  55969. }
  55970. },
  55971. enumerable: true,
  55972. configurable: true
  55973. });
  55974. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55975. /**
  55976. * 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.
  55977. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55978. */
  55979. get: function () {
  55980. if (this.particleEmitterType.minEmitBox) {
  55981. return this.particleEmitterType.minEmitBox;
  55982. }
  55983. return BABYLON.Vector3.Zero();
  55984. },
  55985. set: function (value) {
  55986. if (this.particleEmitterType.minEmitBox) {
  55987. this.particleEmitterType.minEmitBox = value;
  55988. }
  55989. },
  55990. enumerable: true,
  55991. configurable: true
  55992. });
  55993. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55994. /**
  55995. * 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.
  55996. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55997. */
  55998. get: function () {
  55999. if (this.particleEmitterType.maxEmitBox) {
  56000. return this.particleEmitterType.maxEmitBox;
  56001. }
  56002. return BABYLON.Vector3.Zero();
  56003. },
  56004. set: function (value) {
  56005. if (this.particleEmitterType.maxEmitBox) {
  56006. this.particleEmitterType.maxEmitBox = value;
  56007. }
  56008. },
  56009. enumerable: true,
  56010. configurable: true
  56011. });
  56012. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56013. /**
  56014. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56015. */
  56016. get: function () {
  56017. return this._isBillboardBased;
  56018. },
  56019. set: function (value) {
  56020. if (this._isBillboardBased === value) {
  56021. return;
  56022. }
  56023. this._isBillboardBased = value;
  56024. this._reset();
  56025. },
  56026. enumerable: true,
  56027. configurable: true
  56028. });
  56029. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56030. /**
  56031. * Gets the image processing configuration used either in this material.
  56032. */
  56033. get: function () {
  56034. return this._imageProcessingConfiguration;
  56035. },
  56036. /**
  56037. * Sets the Default image processing configuration used either in the this material.
  56038. *
  56039. * If sets to null, the scene one is in use.
  56040. */
  56041. set: function (value) {
  56042. this._attachImageProcessingConfiguration(value);
  56043. },
  56044. enumerable: true,
  56045. configurable: true
  56046. });
  56047. /**
  56048. * Attaches a new image processing configuration to the Standard Material.
  56049. * @param configuration
  56050. */
  56051. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56052. if (configuration === this._imageProcessingConfiguration) {
  56053. return;
  56054. }
  56055. // Pick the scene configuration if needed.
  56056. if (!configuration) {
  56057. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56058. }
  56059. else {
  56060. this._imageProcessingConfiguration = configuration;
  56061. }
  56062. };
  56063. /** @hidden */
  56064. BaseParticleSystem.prototype._reset = function () {
  56065. };
  56066. /** @hidden */
  56067. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  56068. if (!gradients) {
  56069. return this;
  56070. }
  56071. var index = 0;
  56072. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56073. var valueGradient = gradients_1[_i];
  56074. if (valueGradient.gradient === gradient) {
  56075. gradients.splice(index, 1);
  56076. break;
  56077. }
  56078. index++;
  56079. }
  56080. if (texture) {
  56081. texture.dispose();
  56082. }
  56083. return this;
  56084. };
  56085. /**
  56086. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56087. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56088. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56089. * @returns the emitter
  56090. */
  56091. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56092. var particleEmitter = new BABYLON.PointParticleEmitter();
  56093. particleEmitter.direction1 = direction1;
  56094. particleEmitter.direction2 = direction2;
  56095. this.particleEmitterType = particleEmitter;
  56096. return particleEmitter;
  56097. };
  56098. /**
  56099. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56100. * @param radius The radius of the hemisphere to emit from
  56101. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56102. * @returns the emitter
  56103. */
  56104. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56105. if (radius === void 0) { radius = 1; }
  56106. if (radiusRange === void 0) { radiusRange = 1; }
  56107. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56108. this.particleEmitterType = particleEmitter;
  56109. return particleEmitter;
  56110. };
  56111. /**
  56112. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56113. * @param radius The radius of the sphere to emit from
  56114. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56115. * @returns the emitter
  56116. */
  56117. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56118. if (radius === void 0) { radius = 1; }
  56119. if (radiusRange === void 0) { radiusRange = 1; }
  56120. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56121. this.particleEmitterType = particleEmitter;
  56122. return particleEmitter;
  56123. };
  56124. /**
  56125. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56126. * @param radius The radius of the sphere to emit from
  56127. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56128. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56129. * @returns the emitter
  56130. */
  56131. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56132. if (radius === void 0) { radius = 1; }
  56133. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56134. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56135. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56136. this.particleEmitterType = particleEmitter;
  56137. return particleEmitter;
  56138. };
  56139. /**
  56140. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56141. * @param radius The radius of the emission cylinder
  56142. * @param height The height of the emission cylinder
  56143. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56144. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56145. * @returns the emitter
  56146. */
  56147. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56148. if (radius === void 0) { radius = 1; }
  56149. if (height === void 0) { height = 1; }
  56150. if (radiusRange === void 0) { radiusRange = 1; }
  56151. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56152. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56153. this.particleEmitterType = particleEmitter;
  56154. return particleEmitter;
  56155. };
  56156. /**
  56157. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56158. * @param radius The radius of the cylinder to emit from
  56159. * @param height The height of the emission cylinder
  56160. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56161. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56162. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56163. * @returns the emitter
  56164. */
  56165. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56166. if (radius === void 0) { radius = 1; }
  56167. if (height === void 0) { height = 1; }
  56168. if (radiusRange === void 0) { radiusRange = 1; }
  56169. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56170. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56171. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56172. this.particleEmitterType = particleEmitter;
  56173. return particleEmitter;
  56174. };
  56175. /**
  56176. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56177. * @param radius The radius of the cone to emit from
  56178. * @param angle The base angle of the cone
  56179. * @returns the emitter
  56180. */
  56181. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56182. if (radius === void 0) { radius = 1; }
  56183. if (angle === void 0) { angle = Math.PI / 4; }
  56184. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56185. this.particleEmitterType = particleEmitter;
  56186. return particleEmitter;
  56187. };
  56188. /**
  56189. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56190. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56191. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56192. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56193. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56194. * @returns the emitter
  56195. */
  56196. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56197. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56198. this.particleEmitterType = particleEmitter;
  56199. this.direction1 = direction1;
  56200. this.direction2 = direction2;
  56201. this.minEmitBox = minEmitBox;
  56202. this.maxEmitBox = maxEmitBox;
  56203. return particleEmitter;
  56204. };
  56205. /**
  56206. * Source color is added to the destination color without alpha affecting the result
  56207. */
  56208. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56209. /**
  56210. * Blend current color and particle color using particle’s alpha
  56211. */
  56212. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56213. /**
  56214. * Add current color and particle color multiplied by particle’s alpha
  56215. */
  56216. BaseParticleSystem.BLENDMODE_ADD = 2;
  56217. /**
  56218. * Multiply current color with particle color
  56219. */
  56220. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56221. /**
  56222. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  56223. */
  56224. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  56225. return BaseParticleSystem;
  56226. }());
  56227. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56228. })(BABYLON || (BABYLON = {}));
  56229. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56230. var BABYLON;
  56231. (function (BABYLON) {
  56232. /**
  56233. * This represents a particle system in Babylon.
  56234. * 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.
  56235. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56236. * @example https://doc.babylonjs.com/babylon101/particles
  56237. */
  56238. var ParticleSystem = /** @class */ (function (_super) {
  56239. __extends(ParticleSystem, _super);
  56240. /**
  56241. * Instantiates a particle system.
  56242. * 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.
  56243. * @param name The name of the particle system
  56244. * @param capacity The max number of particles alive at the same time
  56245. * @param scene The scene the particle system belongs to
  56246. * @param customEffect a custom effect used to change the way particles are rendered by default
  56247. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56248. * @param epsilon Offset used to render the particles
  56249. */
  56250. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56251. if (customEffect === void 0) { customEffect = null; }
  56252. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56253. if (epsilon === void 0) { epsilon = 0.01; }
  56254. var _this = _super.call(this, name) || this;
  56255. /**
  56256. * @hidden
  56257. */
  56258. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56259. /**
  56260. * An event triggered when the system is disposed
  56261. */
  56262. _this.onDisposeObservable = new BABYLON.Observable();
  56263. _this._particles = new Array();
  56264. _this._stockParticles = new Array();
  56265. _this._newPartsExcess = 0;
  56266. _this._vertexBuffers = {};
  56267. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56268. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56269. _this._scaledDirection = BABYLON.Vector3.Zero();
  56270. _this._scaledGravity = BABYLON.Vector3.Zero();
  56271. _this._currentRenderId = -1;
  56272. _this._useInstancing = false;
  56273. _this._started = false;
  56274. _this._stopped = false;
  56275. _this._actualFrame = 0;
  56276. /** @hidden */
  56277. _this._currentEmitRate1 = 0;
  56278. /** @hidden */
  56279. _this._currentEmitRate2 = 0;
  56280. /** @hidden */
  56281. _this._currentStartSize1 = 0;
  56282. /** @hidden */
  56283. _this._currentStartSize2 = 0;
  56284. _this._rawTextureWidth = 256;
  56285. _this._useRampGradients = false;
  56286. /**
  56287. * @hidden
  56288. * If the particle systems emitter should be disposed when the particle system is disposed
  56289. */
  56290. _this._disposeEmitterOnDispose = false;
  56291. // start of sub system methods
  56292. /**
  56293. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56294. * Its lifetime will start back at 0.
  56295. */
  56296. _this.recycleParticle = function (particle) {
  56297. // move particle from activeParticle list to stock particles
  56298. var lastParticle = _this._particles.pop();
  56299. if (lastParticle !== particle) {
  56300. lastParticle.copyTo(particle);
  56301. }
  56302. _this._stockParticles.push(lastParticle);
  56303. };
  56304. _this._createParticle = function () {
  56305. var particle;
  56306. if (_this._stockParticles.length !== 0) {
  56307. particle = _this._stockParticles.pop();
  56308. particle._reset();
  56309. }
  56310. else {
  56311. particle = new BABYLON.Particle(_this);
  56312. }
  56313. // Attach emitters
  56314. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56315. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56316. particle._attachedSubEmitters = [];
  56317. subEmitters.forEach(function (subEmitter) {
  56318. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56319. var newEmitter = subEmitter.clone();
  56320. particle._attachedSubEmitters.push(newEmitter);
  56321. newEmitter.particleSystem.start();
  56322. }
  56323. });
  56324. }
  56325. return particle;
  56326. };
  56327. _this._emitFromParticle = function (particle) {
  56328. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56329. return;
  56330. }
  56331. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56332. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56333. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56334. var subSystem = subEmitter.clone();
  56335. particle._inheritParticleInfoToSubEmitter(subSystem);
  56336. subSystem.particleSystem._rootParticleSystem = _this;
  56337. _this.activeSubSystems.push(subSystem.particleSystem);
  56338. subSystem.particleSystem.start();
  56339. }
  56340. });
  56341. };
  56342. _this._capacity = capacity;
  56343. _this._epsilon = epsilon;
  56344. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56345. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56346. // Setup the default processing configuration to the scene.
  56347. _this._attachImageProcessingConfiguration(null);
  56348. _this._customEffect = customEffect;
  56349. _this._scene.particleSystems.push(_this);
  56350. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56351. _this._createIndexBuffer();
  56352. _this._createVertexBuffers();
  56353. // Default emitter type
  56354. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56355. // Update
  56356. _this.updateFunction = function (particles) {
  56357. var noiseTextureSize = null;
  56358. var noiseTextureData = null;
  56359. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56360. noiseTextureSize = _this.noiseTexture.getSize();
  56361. noiseTextureData = (_this.noiseTexture.getContent());
  56362. }
  56363. var _loop_1 = function () {
  56364. particle = particles[index];
  56365. particle.age += _this._scaledUpdateSpeed;
  56366. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56367. _this._emitFromParticle(particle);
  56368. if (particle._attachedSubEmitters) {
  56369. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56370. subEmitter.particleSystem.disposeOnStop = true;
  56371. subEmitter.particleSystem.stop();
  56372. });
  56373. particle._attachedSubEmitters = null;
  56374. }
  56375. _this.recycleParticle(particle);
  56376. index--;
  56377. return "continue";
  56378. }
  56379. else {
  56380. var ratio = particle.age / particle.lifeTime;
  56381. // Color
  56382. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56383. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56384. if (currentGradient !== particle._currentColorGradient) {
  56385. particle._currentColor1.copyFrom(particle._currentColor2);
  56386. nextGradient.getColorToRef(particle._currentColor2);
  56387. particle._currentColorGradient = currentGradient;
  56388. }
  56389. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56390. });
  56391. }
  56392. else {
  56393. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56394. particle.color.addInPlace(_this._scaledColorStep);
  56395. if (particle.color.a < 0) {
  56396. particle.color.a = 0;
  56397. }
  56398. }
  56399. // Angular speed
  56400. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56401. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56402. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56403. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56404. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56405. particle._currentAngularSpeedGradient = currentGradient;
  56406. }
  56407. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56408. });
  56409. }
  56410. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56411. // Direction
  56412. var directionScale_1 = _this._scaledUpdateSpeed;
  56413. /// Velocity
  56414. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56415. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56416. if (currentGradient !== particle._currentVelocityGradient) {
  56417. particle._currentVelocity1 = particle._currentVelocity2;
  56418. particle._currentVelocity2 = nextGradient.getFactor();
  56419. particle._currentVelocityGradient = currentGradient;
  56420. }
  56421. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56422. });
  56423. }
  56424. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56425. /// Limit velocity
  56426. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56427. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56428. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56429. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56430. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56431. particle._currentLimitVelocityGradient = currentGradient;
  56432. }
  56433. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56434. var currentVelocity = particle.direction.length();
  56435. if (currentVelocity > limitVelocity) {
  56436. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56437. }
  56438. });
  56439. }
  56440. /// Drag
  56441. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56442. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56443. if (currentGradient !== particle._currentDragGradient) {
  56444. particle._currentDrag1 = particle._currentDrag2;
  56445. particle._currentDrag2 = nextGradient.getFactor();
  56446. particle._currentDragGradient = currentGradient;
  56447. }
  56448. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56449. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56450. });
  56451. }
  56452. particle.position.addInPlace(_this._scaledDirection);
  56453. // Noise
  56454. if (noiseTextureData && noiseTextureSize) {
  56455. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56456. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56457. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56458. var force = BABYLON.Tmp.Vector3[0];
  56459. var scaledForce = BABYLON.Tmp.Vector3[1];
  56460. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56461. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56462. particle.direction.addInPlace(scaledForce);
  56463. }
  56464. // Gravity
  56465. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56466. particle.direction.addInPlace(_this._scaledGravity);
  56467. // Size
  56468. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56469. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56470. if (currentGradient !== particle._currentSizeGradient) {
  56471. particle._currentSize1 = particle._currentSize2;
  56472. particle._currentSize2 = nextGradient.getFactor();
  56473. particle._currentSizeGradient = currentGradient;
  56474. }
  56475. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56476. });
  56477. }
  56478. // Remap data
  56479. if (_this._useRampGradients) {
  56480. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56481. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56482. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56483. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56484. particle.remapData.x = min;
  56485. particle.remapData.y = max - min;
  56486. });
  56487. }
  56488. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56489. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56490. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56491. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56492. particle.remapData.z = min;
  56493. particle.remapData.w = max - min;
  56494. });
  56495. }
  56496. }
  56497. if (_this._isAnimationSheetEnabled) {
  56498. particle.updateCellIndex();
  56499. }
  56500. // Update the position of the attached sub-emitters to match their attached particle
  56501. particle._inheritParticleInfoToSubEmitters();
  56502. }
  56503. };
  56504. var particle;
  56505. for (var index = 0; index < particles.length; index++) {
  56506. _loop_1();
  56507. }
  56508. };
  56509. return _this;
  56510. }
  56511. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56512. /**
  56513. * Sets a callback that will be triggered when the system is disposed
  56514. */
  56515. set: function (callback) {
  56516. if (this._onDisposeObserver) {
  56517. this.onDisposeObservable.remove(this._onDisposeObserver);
  56518. }
  56519. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56525. /** Gets or sets a boolean indicating that ramp gradients must be used
  56526. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56527. */
  56528. get: function () {
  56529. return this._useRampGradients;
  56530. },
  56531. set: function (value) {
  56532. if (this._useRampGradients === value) {
  56533. return;
  56534. }
  56535. this._useRampGradients = value;
  56536. this._resetEffect();
  56537. },
  56538. enumerable: true,
  56539. configurable: true
  56540. });
  56541. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56542. //end of Sub-emitter
  56543. /**
  56544. * Gets the current list of active particles
  56545. */
  56546. get: function () {
  56547. return this._particles;
  56548. },
  56549. enumerable: true,
  56550. configurable: true
  56551. });
  56552. /**
  56553. * Returns the string "ParticleSystem"
  56554. * @returns a string containing the class name
  56555. */
  56556. ParticleSystem.prototype.getClassName = function () {
  56557. return "ParticleSystem";
  56558. };
  56559. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56560. var newGradient = new BABYLON.FactorGradient();
  56561. newGradient.gradient = gradient;
  56562. newGradient.factor1 = factor;
  56563. newGradient.factor2 = factor2;
  56564. factorGradients.push(newGradient);
  56565. factorGradients.sort(function (a, b) {
  56566. if (a.gradient < b.gradient) {
  56567. return -1;
  56568. }
  56569. else if (a.gradient > b.gradient) {
  56570. return 1;
  56571. }
  56572. return 0;
  56573. });
  56574. };
  56575. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56576. if (!factorGradients) {
  56577. return;
  56578. }
  56579. var index = 0;
  56580. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56581. var factorGradient = factorGradients_1[_i];
  56582. if (factorGradient.gradient === gradient) {
  56583. factorGradients.splice(index, 1);
  56584. break;
  56585. }
  56586. index++;
  56587. }
  56588. };
  56589. /**
  56590. * Adds a new life time gradient
  56591. * @param gradient defines the gradient to use (between 0 and 1)
  56592. * @param factor defines the life time factor to affect to the specified gradient
  56593. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56594. * @returns the current particle system
  56595. */
  56596. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56597. if (!this._lifeTimeGradients) {
  56598. this._lifeTimeGradients = [];
  56599. }
  56600. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56601. return this;
  56602. };
  56603. /**
  56604. * Remove a specific life time gradient
  56605. * @param gradient defines the gradient to remove
  56606. * @returns the current particle system
  56607. */
  56608. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56609. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56610. return this;
  56611. };
  56612. /**
  56613. * Adds a new size gradient
  56614. * @param gradient defines the gradient to use (between 0 and 1)
  56615. * @param factor defines the size factor to affect to the specified gradient
  56616. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56617. * @returns the current particle system
  56618. */
  56619. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56620. if (!this._sizeGradients) {
  56621. this._sizeGradients = [];
  56622. }
  56623. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56624. return this;
  56625. };
  56626. /**
  56627. * Remove a specific size gradient
  56628. * @param gradient defines the gradient to remove
  56629. * @returns the current particle system
  56630. */
  56631. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56632. this._removeFactorGradient(this._sizeGradients, gradient);
  56633. return this;
  56634. };
  56635. /**
  56636. * Adds a new color remap gradient
  56637. * @param gradient defines the gradient to use (between 0 and 1)
  56638. * @param min defines the color remap minimal range
  56639. * @param max defines the color remap maximal range
  56640. * @returns the current particle system
  56641. */
  56642. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56643. if (!this._colorRemapGradients) {
  56644. this._colorRemapGradients = [];
  56645. }
  56646. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56647. return this;
  56648. };
  56649. /**
  56650. * Remove a specific color remap gradient
  56651. * @param gradient defines the gradient to remove
  56652. * @returns the current particle system
  56653. */
  56654. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56655. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56656. return this;
  56657. };
  56658. /**
  56659. * Adds a new alpha remap gradient
  56660. * @param gradient defines the gradient to use (between 0 and 1)
  56661. * @param min defines the alpha remap minimal range
  56662. * @param max defines the alpha remap maximal range
  56663. * @returns the current particle system
  56664. */
  56665. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56666. if (!this._alphaRemapGradients) {
  56667. this._alphaRemapGradients = [];
  56668. }
  56669. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56670. return this;
  56671. };
  56672. /**
  56673. * Remove a specific alpha remap gradient
  56674. * @param gradient defines the gradient to remove
  56675. * @returns the current particle system
  56676. */
  56677. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56678. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56679. return this;
  56680. };
  56681. /**
  56682. * Adds a new angular speed gradient
  56683. * @param gradient defines the gradient to use (between 0 and 1)
  56684. * @param factor defines the angular speed to affect to the specified gradient
  56685. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56686. * @returns the current particle system
  56687. */
  56688. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56689. if (!this._angularSpeedGradients) {
  56690. this._angularSpeedGradients = [];
  56691. }
  56692. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56693. return this;
  56694. };
  56695. /**
  56696. * Remove a specific angular speed gradient
  56697. * @param gradient defines the gradient to remove
  56698. * @returns the current particle system
  56699. */
  56700. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56701. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56702. return this;
  56703. };
  56704. /**
  56705. * Adds a new velocity gradient
  56706. * @param gradient defines the gradient to use (between 0 and 1)
  56707. * @param factor defines the velocity to affect to the specified gradient
  56708. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56709. * @returns the current particle system
  56710. */
  56711. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56712. if (!this._velocityGradients) {
  56713. this._velocityGradients = [];
  56714. }
  56715. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56716. return this;
  56717. };
  56718. /**
  56719. * Remove a specific velocity gradient
  56720. * @param gradient defines the gradient to remove
  56721. * @returns the current particle system
  56722. */
  56723. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56724. this._removeFactorGradient(this._velocityGradients, gradient);
  56725. return this;
  56726. };
  56727. /**
  56728. * Adds a new limit velocity gradient
  56729. * @param gradient defines the gradient to use (between 0 and 1)
  56730. * @param factor defines the limit velocity value to affect to the specified gradient
  56731. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56732. * @returns the current particle system
  56733. */
  56734. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56735. if (!this._limitVelocityGradients) {
  56736. this._limitVelocityGradients = [];
  56737. }
  56738. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56739. return this;
  56740. };
  56741. /**
  56742. * Remove a specific limit velocity gradient
  56743. * @param gradient defines the gradient to remove
  56744. * @returns the current particle system
  56745. */
  56746. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56747. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56748. return this;
  56749. };
  56750. /**
  56751. * Adds a new drag gradient
  56752. * @param gradient defines the gradient to use (between 0 and 1)
  56753. * @param factor defines the drag value to affect to the specified gradient
  56754. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56755. * @returns the current particle system
  56756. */
  56757. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56758. if (!this._dragGradients) {
  56759. this._dragGradients = [];
  56760. }
  56761. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56762. return this;
  56763. };
  56764. /**
  56765. * Remove a specific drag gradient
  56766. * @param gradient defines the gradient to remove
  56767. * @returns the current particle system
  56768. */
  56769. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56770. this._removeFactorGradient(this._dragGradients, gradient);
  56771. return this;
  56772. };
  56773. /**
  56774. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56775. * @param gradient defines the gradient to use (between 0 and 1)
  56776. * @param factor defines the emit rate value to affect to the specified gradient
  56777. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56778. * @returns the current particle system
  56779. */
  56780. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56781. if (!this._emitRateGradients) {
  56782. this._emitRateGradients = [];
  56783. }
  56784. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56785. if (!this._currentEmitRateGradient) {
  56786. this._currentEmitRateGradient = this._emitRateGradients[0];
  56787. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56788. this._currentEmitRate2 = this._currentEmitRate1;
  56789. }
  56790. if (this._emitRateGradients.length === 2) {
  56791. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56792. }
  56793. return this;
  56794. };
  56795. /**
  56796. * Remove a specific emit rate gradient
  56797. * @param gradient defines the gradient to remove
  56798. * @returns the current particle system
  56799. */
  56800. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56801. this._removeFactorGradient(this._emitRateGradients, gradient);
  56802. return this;
  56803. };
  56804. /**
  56805. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56806. * @param gradient defines the gradient to use (between 0 and 1)
  56807. * @param factor defines the start size value to affect to the specified gradient
  56808. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56809. * @returns the current particle system
  56810. */
  56811. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56812. if (!this._startSizeGradients) {
  56813. this._startSizeGradients = [];
  56814. }
  56815. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56816. if (!this._currentStartSizeGradient) {
  56817. this._currentStartSizeGradient = this._startSizeGradients[0];
  56818. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56819. this._currentStartSize2 = this._currentStartSize1;
  56820. }
  56821. if (this._startSizeGradients.length === 2) {
  56822. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56823. }
  56824. return this;
  56825. };
  56826. /**
  56827. * Remove a specific start size gradient
  56828. * @param gradient defines the gradient to remove
  56829. * @returns the current particle system
  56830. */
  56831. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56832. this._removeFactorGradient(this._emitRateGradients, gradient);
  56833. return this;
  56834. };
  56835. ParticleSystem.prototype._createRampGradientTexture = function () {
  56836. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56837. return;
  56838. }
  56839. var data = new Uint8Array(this._rawTextureWidth * 4);
  56840. var tmpColor = BABYLON.Tmp.Color3[0];
  56841. for (var x = 0; x < this._rawTextureWidth; x++) {
  56842. var ratio = x / this._rawTextureWidth;
  56843. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56844. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56845. data[x * 4] = tmpColor.r * 255;
  56846. data[x * 4 + 1] = tmpColor.g * 255;
  56847. data[x * 4 + 2] = tmpColor.b * 255;
  56848. data[x * 4 + 3] = 255;
  56849. });
  56850. }
  56851. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56852. };
  56853. /**
  56854. * Gets the current list of ramp gradients.
  56855. * You must use addRampGradient and removeRampGradient to udpate this list
  56856. * @returns the list of ramp gradients
  56857. */
  56858. ParticleSystem.prototype.getRampGradients = function () {
  56859. return this._rampGradients;
  56860. };
  56861. /**
  56862. * Adds a new ramp gradient used to remap particle colors
  56863. * @param gradient defines the gradient to use (between 0 and 1)
  56864. * @param color defines the color to affect to the specified gradient
  56865. * @returns the current particle system
  56866. */
  56867. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56868. if (!this._rampGradients) {
  56869. this._rampGradients = [];
  56870. }
  56871. var rampGradient = new BABYLON.Color3Gradient();
  56872. rampGradient.gradient = gradient;
  56873. rampGradient.color = color;
  56874. this._rampGradients.push(rampGradient);
  56875. this._rampGradients.sort(function (a, b) {
  56876. if (a.gradient < b.gradient) {
  56877. return -1;
  56878. }
  56879. else if (a.gradient > b.gradient) {
  56880. return 1;
  56881. }
  56882. return 0;
  56883. });
  56884. if (this._rampGradientsTexture) {
  56885. this._rampGradientsTexture.dispose();
  56886. this._rampGradientsTexture = null;
  56887. }
  56888. this._createRampGradientTexture();
  56889. return this;
  56890. };
  56891. /**
  56892. * Remove a specific ramp gradient
  56893. * @param gradient defines the gradient to remove
  56894. * @returns the current particle system
  56895. */
  56896. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56897. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56898. this._rampGradientsTexture = null;
  56899. if (this._rampGradients && this._rampGradients.length > 0) {
  56900. this._createRampGradientTexture();
  56901. }
  56902. return this;
  56903. };
  56904. /**
  56905. * Adds a new color gradient
  56906. * @param gradient defines the gradient to use (between 0 and 1)
  56907. * @param color defines the color to affect to the specified gradient
  56908. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56909. */
  56910. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56911. if (!this._colorGradients) {
  56912. this._colorGradients = [];
  56913. }
  56914. var colorGradient = new BABYLON.ColorGradient();
  56915. colorGradient.gradient = gradient;
  56916. colorGradient.color1 = color;
  56917. colorGradient.color2 = color2;
  56918. this._colorGradients.push(colorGradient);
  56919. this._colorGradients.sort(function (a, b) {
  56920. if (a.gradient < b.gradient) {
  56921. return -1;
  56922. }
  56923. else if (a.gradient > b.gradient) {
  56924. return 1;
  56925. }
  56926. return 0;
  56927. });
  56928. return this;
  56929. };
  56930. /**
  56931. * Remove a specific color gradient
  56932. * @param gradient defines the gradient to remove
  56933. */
  56934. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56935. if (!this._colorGradients) {
  56936. return this;
  56937. }
  56938. var index = 0;
  56939. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56940. var colorGradient = _a[_i];
  56941. if (colorGradient.gradient === gradient) {
  56942. this._colorGradients.splice(index, 1);
  56943. break;
  56944. }
  56945. index++;
  56946. }
  56947. return this;
  56948. };
  56949. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56950. u = Math.abs(u) * 0.5 + 0.5;
  56951. v = Math.abs(v) * 0.5 + 0.5;
  56952. var wrappedU = ((u * width) % width) | 0;
  56953. var wrappedV = ((v * height) % height) | 0;
  56954. var position = (wrappedU + wrappedV * width) * 4;
  56955. return pixels[position] / 255;
  56956. };
  56957. ParticleSystem.prototype._reset = function () {
  56958. this._resetEffect();
  56959. };
  56960. ParticleSystem.prototype._resetEffect = function () {
  56961. if (this._vertexBuffer) {
  56962. this._vertexBuffer.dispose();
  56963. this._vertexBuffer = null;
  56964. }
  56965. if (this._spriteBuffer) {
  56966. this._spriteBuffer.dispose();
  56967. this._spriteBuffer = null;
  56968. }
  56969. this._createVertexBuffers();
  56970. };
  56971. ParticleSystem.prototype._createVertexBuffers = function () {
  56972. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56973. if (this._isAnimationSheetEnabled) {
  56974. this._vertexBufferSize += 1;
  56975. }
  56976. if (!this._isBillboardBased) {
  56977. this._vertexBufferSize += 3;
  56978. }
  56979. if (this._useRampGradients) {
  56980. this._vertexBufferSize += 4;
  56981. }
  56982. var engine = this._scene.getEngine();
  56983. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56984. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56985. var dataOffset = 0;
  56986. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56987. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56988. dataOffset += 3;
  56989. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56990. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56991. dataOffset += 4;
  56992. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56993. this._vertexBuffers["angle"] = options;
  56994. dataOffset += 1;
  56995. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56996. this._vertexBuffers["size"] = size;
  56997. dataOffset += 2;
  56998. if (this._isAnimationSheetEnabled) {
  56999. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57000. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  57001. dataOffset += 1;
  57002. }
  57003. if (!this._isBillboardBased) {
  57004. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57005. this._vertexBuffers["direction"] = directionBuffer;
  57006. dataOffset += 3;
  57007. }
  57008. if (this._useRampGradients) {
  57009. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57010. this._vertexBuffers["remapData"] = rampDataBuffer;
  57011. dataOffset += 4;
  57012. }
  57013. var offsets;
  57014. if (this._useInstancing) {
  57015. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  57016. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  57017. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  57018. }
  57019. else {
  57020. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57021. dataOffset += 2;
  57022. }
  57023. this._vertexBuffers["offset"] = offsets;
  57024. };
  57025. ParticleSystem.prototype._createIndexBuffer = function () {
  57026. if (this._useInstancing) {
  57027. return;
  57028. }
  57029. var indices = [];
  57030. var index = 0;
  57031. for (var count = 0; count < this._capacity; count++) {
  57032. indices.push(index);
  57033. indices.push(index + 1);
  57034. indices.push(index + 2);
  57035. indices.push(index);
  57036. indices.push(index + 2);
  57037. indices.push(index + 3);
  57038. index += 4;
  57039. }
  57040. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57041. };
  57042. /**
  57043. * Gets the maximum number of particles active at the same time.
  57044. * @returns The max number of active particles.
  57045. */
  57046. ParticleSystem.prototype.getCapacity = function () {
  57047. return this._capacity;
  57048. };
  57049. /**
  57050. * Gets whether there are still active particles in the system.
  57051. * @returns True if it is alive, otherwise false.
  57052. */
  57053. ParticleSystem.prototype.isAlive = function () {
  57054. return this._alive;
  57055. };
  57056. /**
  57057. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57058. * @returns True if it has been started, otherwise false.
  57059. */
  57060. ParticleSystem.prototype.isStarted = function () {
  57061. return this._started;
  57062. };
  57063. /**
  57064. * Starts the particle system and begins to emit
  57065. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  57066. */
  57067. ParticleSystem.prototype.start = function (delay) {
  57068. var _this = this;
  57069. if (delay === void 0) { delay = this.startDelay; }
  57070. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  57071. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  57072. }
  57073. if (delay) {
  57074. setTimeout(function () {
  57075. _this.start(0);
  57076. }, delay);
  57077. return;
  57078. }
  57079. // Convert the subEmitters field to the constant type field _subEmitters
  57080. this._subEmitters = new Array();
  57081. if (this.subEmitters) {
  57082. this.subEmitters.forEach(function (subEmitter) {
  57083. if (subEmitter instanceof ParticleSystem) {
  57084. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57085. }
  57086. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57087. _this._subEmitters.push([subEmitter]);
  57088. }
  57089. else if (subEmitter instanceof Array) {
  57090. _this._subEmitters.push(subEmitter);
  57091. }
  57092. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  57093. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  57094. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  57095. }
  57096. });
  57097. });
  57098. }
  57099. this._started = true;
  57100. this._stopped = false;
  57101. this._actualFrame = 0;
  57102. if (this._subEmitters && this._subEmitters.length != 0) {
  57103. this.activeSubSystems = new Array();
  57104. }
  57105. if (this.preWarmCycles) {
  57106. var noiseTextureAsProcedural_1 = this.noiseTexture;
  57107. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  57108. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  57109. setTimeout(function () {
  57110. for (var index = 0; index < _this.preWarmCycles; index++) {
  57111. _this.animate(true);
  57112. noiseTextureAsProcedural_1.render();
  57113. }
  57114. });
  57115. });
  57116. }
  57117. else {
  57118. for (var index = 0; index < this.preWarmCycles; index++) {
  57119. this.animate(true);
  57120. }
  57121. }
  57122. }
  57123. };
  57124. /**
  57125. * Stops the particle system.
  57126. * @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.
  57127. */
  57128. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57129. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57130. this._stopped = true;
  57131. if (stopSubEmitters) {
  57132. this._stopSubEmitters();
  57133. }
  57134. };
  57135. // animation sheet
  57136. /**
  57137. * Remove all active particles
  57138. */
  57139. ParticleSystem.prototype.reset = function () {
  57140. this._stockParticles = [];
  57141. this._particles = [];
  57142. };
  57143. /**
  57144. * @hidden (for internal use only)
  57145. */
  57146. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57147. var offset = index * this._vertexBufferSize;
  57148. this._vertexData[offset++] = particle.position.x;
  57149. this._vertexData[offset++] = particle.position.y;
  57150. this._vertexData[offset++] = particle.position.z;
  57151. this._vertexData[offset++] = particle.color.r;
  57152. this._vertexData[offset++] = particle.color.g;
  57153. this._vertexData[offset++] = particle.color.b;
  57154. this._vertexData[offset++] = particle.color.a;
  57155. this._vertexData[offset++] = particle.angle;
  57156. this._vertexData[offset++] = particle.scale.x * particle.size;
  57157. this._vertexData[offset++] = particle.scale.y * particle.size;
  57158. if (this._isAnimationSheetEnabled) {
  57159. this._vertexData[offset++] = particle.cellIndex;
  57160. }
  57161. if (!this._isBillboardBased) {
  57162. if (particle._initialDirection) {
  57163. this._vertexData[offset++] = particle._initialDirection.x;
  57164. this._vertexData[offset++] = particle._initialDirection.y;
  57165. this._vertexData[offset++] = particle._initialDirection.z;
  57166. }
  57167. else {
  57168. this._vertexData[offset++] = particle.direction.x;
  57169. this._vertexData[offset++] = particle.direction.y;
  57170. this._vertexData[offset++] = particle.direction.z;
  57171. }
  57172. }
  57173. if (this._useRampGradients) {
  57174. this._vertexData[offset++] = particle.remapData.x;
  57175. this._vertexData[offset++] = particle.remapData.y;
  57176. this._vertexData[offset++] = particle.remapData.z;
  57177. this._vertexData[offset++] = particle.remapData.w;
  57178. }
  57179. if (!this._useInstancing) {
  57180. if (this._isAnimationSheetEnabled) {
  57181. if (offsetX === 0)
  57182. offsetX = this._epsilon;
  57183. else if (offsetX === 1)
  57184. offsetX = 1 - this._epsilon;
  57185. if (offsetY === 0)
  57186. offsetY = this._epsilon;
  57187. else if (offsetY === 1)
  57188. offsetY = 1 - this._epsilon;
  57189. }
  57190. this._vertexData[offset++] = offsetX;
  57191. this._vertexData[offset++] = offsetY;
  57192. }
  57193. };
  57194. ParticleSystem.prototype._stopSubEmitters = function () {
  57195. if (!this.activeSubSystems) {
  57196. return;
  57197. }
  57198. this.activeSubSystems.forEach(function (subSystem) {
  57199. subSystem.stop(true);
  57200. });
  57201. this.activeSubSystems = new Array();
  57202. };
  57203. ParticleSystem.prototype._removeFromRoot = function () {
  57204. if (!this._rootParticleSystem) {
  57205. return;
  57206. }
  57207. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57208. if (index !== -1) {
  57209. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57210. }
  57211. };
  57212. // End of sub system methods
  57213. ParticleSystem.prototype._update = function (newParticles) {
  57214. var _this = this;
  57215. // Update current
  57216. this._alive = this._particles.length > 0;
  57217. if (this.emitter.position) {
  57218. var emitterMesh = this.emitter;
  57219. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57220. }
  57221. else {
  57222. var emitterPosition = this.emitter;
  57223. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57224. }
  57225. this.updateFunction(this._particles);
  57226. // Add new ones
  57227. var particle;
  57228. var _loop_2 = function () {
  57229. if (this_1._particles.length === this_1._capacity) {
  57230. return "break";
  57231. }
  57232. particle = this_1._createParticle();
  57233. this_1._particles.push(particle);
  57234. // Emitter
  57235. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57236. if (this_1.startPositionFunction) {
  57237. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57238. }
  57239. else {
  57240. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57241. }
  57242. if (this_1.startDirectionFunction) {
  57243. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57244. }
  57245. else {
  57246. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57247. }
  57248. if (emitPower === 0) {
  57249. if (!particle._initialDirection) {
  57250. particle._initialDirection = particle.direction.clone();
  57251. }
  57252. else {
  57253. particle._initialDirection.copyFrom(particle.direction);
  57254. }
  57255. }
  57256. else {
  57257. particle._initialDirection = null;
  57258. }
  57259. particle.direction.scaleInPlace(emitPower);
  57260. // Life time
  57261. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57262. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57263. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57264. var factorGradient1 = currentGradient;
  57265. var factorGradient2 = nextGradient;
  57266. var lifeTime1 = factorGradient1.getFactor();
  57267. var lifeTime2 = factorGradient2.getFactor();
  57268. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57269. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57270. });
  57271. }
  57272. else {
  57273. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57274. }
  57275. // Size
  57276. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57277. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57278. }
  57279. else {
  57280. particle._currentSizeGradient = this_1._sizeGradients[0];
  57281. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57282. particle.size = particle._currentSize1;
  57283. if (this_1._sizeGradients.length > 1) {
  57284. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57285. }
  57286. else {
  57287. particle._currentSize2 = particle._currentSize1;
  57288. }
  57289. }
  57290. // Size and scale
  57291. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57292. // Adjust scale by start size
  57293. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  57294. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57295. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57296. if (currentGradient !== _this._currentStartSizeGradient) {
  57297. _this._currentStartSize1 = _this._currentStartSize2;
  57298. _this._currentStartSize2 = nextGradient.getFactor();
  57299. _this._currentStartSizeGradient = currentGradient;
  57300. }
  57301. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57302. particle.scale.scaleInPlace(value);
  57303. });
  57304. }
  57305. // Angle
  57306. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57307. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57308. }
  57309. else {
  57310. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57311. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57312. particle._currentAngularSpeed1 = particle.angularSpeed;
  57313. if (this_1._angularSpeedGradients.length > 1) {
  57314. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57315. }
  57316. else {
  57317. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57318. }
  57319. }
  57320. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57321. // Velocity
  57322. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57323. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57324. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57325. if (this_1._velocityGradients.length > 1) {
  57326. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57327. }
  57328. else {
  57329. particle._currentVelocity2 = particle._currentVelocity1;
  57330. }
  57331. }
  57332. // Limit velocity
  57333. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57334. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57335. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57336. if (this_1._limitVelocityGradients.length > 1) {
  57337. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57338. }
  57339. else {
  57340. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57341. }
  57342. }
  57343. // Drag
  57344. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57345. particle._currentDragGradient = this_1._dragGradients[0];
  57346. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57347. if (this_1._dragGradients.length > 1) {
  57348. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57349. }
  57350. else {
  57351. particle._currentDrag2 = particle._currentDrag1;
  57352. }
  57353. }
  57354. // Color
  57355. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57356. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57357. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57358. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57359. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57360. }
  57361. else {
  57362. particle._currentColorGradient = this_1._colorGradients[0];
  57363. particle._currentColorGradient.getColorToRef(particle.color);
  57364. particle._currentColor1.copyFrom(particle.color);
  57365. if (this_1._colorGradients.length > 1) {
  57366. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57367. }
  57368. else {
  57369. particle._currentColor2.copyFrom(particle.color);
  57370. }
  57371. }
  57372. // Sheet
  57373. if (this_1._isAnimationSheetEnabled) {
  57374. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57375. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57376. }
  57377. // Inherited Velocity
  57378. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57379. // Ramp
  57380. if (this_1._useRampGradients) {
  57381. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57382. }
  57383. // Noise texture coordinates
  57384. if (this_1.noiseTexture) {
  57385. if (particle._randomNoiseCoordinates1) {
  57386. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  57387. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  57388. }
  57389. else {
  57390. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57391. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57392. }
  57393. }
  57394. // Update the position of the attached sub-emitters to match their attached particle
  57395. particle._inheritParticleInfoToSubEmitters();
  57396. };
  57397. var this_1 = this, step;
  57398. for (var index = 0; index < newParticles; index++) {
  57399. var state_1 = _loop_2();
  57400. if (state_1 === "break")
  57401. break;
  57402. }
  57403. };
  57404. /** @hidden */
  57405. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57406. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57407. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57408. if (useRampGradients === void 0) { useRampGradients = false; }
  57409. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57410. if (isAnimationSheetEnabled) {
  57411. attributeNamesOrOptions.push("cellIndex");
  57412. }
  57413. if (!isBillboardBased) {
  57414. attributeNamesOrOptions.push("direction");
  57415. }
  57416. if (useRampGradients) {
  57417. attributeNamesOrOptions.push("remapData");
  57418. }
  57419. return attributeNamesOrOptions;
  57420. };
  57421. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57422. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57423. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57424. if (isAnimationSheetEnabled) {
  57425. effectCreationOption.push("particlesInfos");
  57426. }
  57427. return effectCreationOption;
  57428. };
  57429. ParticleSystem.prototype._getEffect = function (blendMode) {
  57430. if (this._customEffect) {
  57431. return this._customEffect;
  57432. }
  57433. ;
  57434. var defines = [];
  57435. if (this._scene.clipPlane) {
  57436. defines.push("#define CLIPPLANE");
  57437. }
  57438. if (this._scene.clipPlane2) {
  57439. defines.push("#define CLIPPLANE2");
  57440. }
  57441. if (this._scene.clipPlane3) {
  57442. defines.push("#define CLIPPLANE3");
  57443. }
  57444. if (this._scene.clipPlane4) {
  57445. defines.push("#define CLIPPLANE4");
  57446. }
  57447. if (this._isAnimationSheetEnabled) {
  57448. defines.push("#define ANIMATESHEET");
  57449. }
  57450. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57451. defines.push("#define BLENDMULTIPLYMODE");
  57452. }
  57453. if (this._useRampGradients) {
  57454. defines.push("#define RAMPGRADIENT");
  57455. }
  57456. if (this._isBillboardBased) {
  57457. defines.push("#define BILLBOARD");
  57458. switch (this.billboardMode) {
  57459. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57460. defines.push("#define BILLBOARDY");
  57461. break;
  57462. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57463. default:
  57464. break;
  57465. }
  57466. }
  57467. if (this._imageProcessingConfiguration) {
  57468. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57469. defines.push(this._imageProcessingConfigurationDefines.toString());
  57470. }
  57471. // Effect
  57472. var join = defines.join("\n");
  57473. if (this._cachedDefines !== join) {
  57474. this._cachedDefines = join;
  57475. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57476. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57477. var samplers = ["diffuseSampler", "rampSampler"];
  57478. if (BABYLON.ImageProcessingConfiguration) {
  57479. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57480. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57481. }
  57482. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57483. }
  57484. return this._effect;
  57485. };
  57486. /**
  57487. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57488. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57489. */
  57490. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57491. var _this = this;
  57492. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57493. if (!this._started)
  57494. return;
  57495. if (!preWarmOnly) {
  57496. // Check
  57497. if (!this.isReady())
  57498. return;
  57499. if (this._currentRenderId === this._scene.getRenderId()) {
  57500. return;
  57501. }
  57502. this._currentRenderId = this._scene.getRenderId();
  57503. }
  57504. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57505. // Determine the number of particles we need to create
  57506. var newParticles;
  57507. if (this.manualEmitCount > -1) {
  57508. newParticles = this.manualEmitCount;
  57509. this._newPartsExcess = 0;
  57510. this.manualEmitCount = 0;
  57511. }
  57512. else {
  57513. var rate_1 = this.emitRate;
  57514. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57515. var ratio = this._actualFrame / this.targetStopDuration;
  57516. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57517. if (currentGradient !== _this._currentEmitRateGradient) {
  57518. _this._currentEmitRate1 = _this._currentEmitRate2;
  57519. _this._currentEmitRate2 = nextGradient.getFactor();
  57520. _this._currentEmitRateGradient = currentGradient;
  57521. }
  57522. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57523. });
  57524. }
  57525. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57526. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57527. }
  57528. if (this._newPartsExcess > 1.0) {
  57529. newParticles += this._newPartsExcess >> 0;
  57530. this._newPartsExcess -= this._newPartsExcess >> 0;
  57531. }
  57532. this._alive = false;
  57533. if (!this._stopped) {
  57534. this._actualFrame += this._scaledUpdateSpeed;
  57535. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57536. this.stop();
  57537. }
  57538. else {
  57539. newParticles = 0;
  57540. }
  57541. this._update(newParticles);
  57542. // Stopped?
  57543. if (this._stopped) {
  57544. if (!this._alive) {
  57545. this._started = false;
  57546. if (this.onAnimationEnd) {
  57547. this.onAnimationEnd();
  57548. }
  57549. if (this.disposeOnStop) {
  57550. this._scene._toBeDisposed.push(this);
  57551. }
  57552. }
  57553. }
  57554. if (!preWarmOnly) {
  57555. // Update VBO
  57556. var offset = 0;
  57557. for (var index = 0; index < this._particles.length; index++) {
  57558. var particle = this._particles[index];
  57559. this._appendParticleVertices(offset, particle);
  57560. offset += this._useInstancing ? 1 : 4;
  57561. }
  57562. if (this._vertexBuffer) {
  57563. this._vertexBuffer.update(this._vertexData);
  57564. }
  57565. }
  57566. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57567. this.stop();
  57568. }
  57569. };
  57570. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57571. this._appendParticleVertex(offset++, particle, 0, 0);
  57572. if (!this._useInstancing) {
  57573. this._appendParticleVertex(offset++, particle, 1, 0);
  57574. this._appendParticleVertex(offset++, particle, 1, 1);
  57575. this._appendParticleVertex(offset++, particle, 0, 1);
  57576. }
  57577. };
  57578. /**
  57579. * Rebuilds the particle system.
  57580. */
  57581. ParticleSystem.prototype.rebuild = function () {
  57582. this._createIndexBuffer();
  57583. if (this._vertexBuffer) {
  57584. this._vertexBuffer._rebuild();
  57585. }
  57586. };
  57587. /**
  57588. * Is this system ready to be used/rendered
  57589. * @return true if the system is ready
  57590. */
  57591. ParticleSystem.prototype.isReady = function () {
  57592. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57593. return false;
  57594. }
  57595. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57596. if (!this._getEffect(this.blendMode).isReady()) {
  57597. return false;
  57598. }
  57599. }
  57600. else {
  57601. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57602. return false;
  57603. }
  57604. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57605. return false;
  57606. }
  57607. }
  57608. return true;
  57609. };
  57610. ParticleSystem.prototype._render = function (blendMode) {
  57611. var effect = this._getEffect(blendMode);
  57612. var engine = this._scene.getEngine();
  57613. // Render
  57614. engine.enableEffect(effect);
  57615. var viewMatrix = this._scene.getViewMatrix();
  57616. effect.setTexture("diffuseSampler", this.particleTexture);
  57617. effect.setMatrix("view", viewMatrix);
  57618. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57619. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57620. var baseSize = this.particleTexture.getBaseSize();
  57621. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57622. }
  57623. effect.setVector2("translationPivot", this.translationPivot);
  57624. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57625. if (this._isBillboardBased) {
  57626. var camera = this._scene.activeCamera;
  57627. effect.setVector3("eyePosition", camera.globalPosition);
  57628. }
  57629. if (this._rampGradientsTexture) {
  57630. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57631. }
  57632. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57633. var invView = viewMatrix.clone();
  57634. invView.invert();
  57635. effect.setMatrix("invView", invView);
  57636. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57637. }
  57638. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57639. // image processing
  57640. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57641. this._imageProcessingConfiguration.bind(effect);
  57642. }
  57643. // Draw order
  57644. switch (blendMode) {
  57645. case ParticleSystem.BLENDMODE_ADD:
  57646. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57647. break;
  57648. case ParticleSystem.BLENDMODE_ONEONE:
  57649. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57650. break;
  57651. case ParticleSystem.BLENDMODE_STANDARD:
  57652. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57653. break;
  57654. case ParticleSystem.BLENDMODE_MULTIPLY:
  57655. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57656. break;
  57657. }
  57658. if (this._useInstancing) {
  57659. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57660. }
  57661. else {
  57662. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57663. }
  57664. return this._particles.length;
  57665. };
  57666. /**
  57667. * Renders the particle system in its current state.
  57668. * @returns the current number of particles
  57669. */
  57670. ParticleSystem.prototype.render = function () {
  57671. // Check
  57672. if (!this.isReady() || !this._particles.length) {
  57673. return 0;
  57674. }
  57675. var engine = this._scene.getEngine();
  57676. engine.setState(false);
  57677. if (this.forceDepthWrite) {
  57678. engine.setDepthWrite(true);
  57679. }
  57680. var outparticles = 0;
  57681. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57682. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57683. }
  57684. outparticles = this._render(this.blendMode);
  57685. engine.unbindInstanceAttributes();
  57686. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57687. return outparticles;
  57688. };
  57689. /**
  57690. * Disposes the particle system and free the associated resources
  57691. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57692. */
  57693. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57694. if (disposeTexture === void 0) { disposeTexture = true; }
  57695. if (this._vertexBuffer) {
  57696. this._vertexBuffer.dispose();
  57697. this._vertexBuffer = null;
  57698. }
  57699. if (this._spriteBuffer) {
  57700. this._spriteBuffer.dispose();
  57701. this._spriteBuffer = null;
  57702. }
  57703. if (this._indexBuffer) {
  57704. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57705. this._indexBuffer = null;
  57706. }
  57707. if (disposeTexture && this.particleTexture) {
  57708. this.particleTexture.dispose();
  57709. this.particleTexture = null;
  57710. }
  57711. if (disposeTexture && this.noiseTexture) {
  57712. this.noiseTexture.dispose();
  57713. this.noiseTexture = null;
  57714. }
  57715. if (this._rampGradientsTexture) {
  57716. this._rampGradientsTexture.dispose();
  57717. this._rampGradientsTexture = null;
  57718. }
  57719. this._removeFromRoot();
  57720. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  57721. this.emitter.dispose(true);
  57722. }
  57723. // Remove from scene
  57724. var index = this._scene.particleSystems.indexOf(this);
  57725. if (index > -1) {
  57726. this._scene.particleSystems.splice(index, 1);
  57727. }
  57728. // Callback
  57729. this.onDisposeObservable.notifyObservers(this);
  57730. this.onDisposeObservable.clear();
  57731. };
  57732. // Clone
  57733. /**
  57734. * Clones the particle system.
  57735. * @param name The name of the cloned object
  57736. * @param newEmitter The new emitter to use
  57737. * @returns the cloned particle system
  57738. */
  57739. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57740. var custom = null;
  57741. var program = null;
  57742. if (this.customShader != null) {
  57743. program = this.customShader;
  57744. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57745. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57746. }
  57747. else if (this._customEffect) {
  57748. custom = this._customEffect;
  57749. }
  57750. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57751. result.customShader = program;
  57752. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  57753. if (newEmitter === undefined) {
  57754. newEmitter = this.emitter;
  57755. }
  57756. result.noiseTexture = this.noiseTexture;
  57757. result.emitter = newEmitter;
  57758. if (this.particleTexture) {
  57759. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57760. }
  57761. // Clone gradients
  57762. if (this._colorGradients) {
  57763. this._colorGradients.forEach(function (v) {
  57764. result.addColorGradient(v.gradient, v.color1, v.color2);
  57765. });
  57766. }
  57767. if (this._dragGradients) {
  57768. this._dragGradients.forEach(function (v) {
  57769. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57770. });
  57771. }
  57772. if (this._angularSpeedGradients) {
  57773. this._angularSpeedGradients.forEach(function (v) {
  57774. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57775. });
  57776. }
  57777. if (this._emitRateGradients) {
  57778. this._emitRateGradients.forEach(function (v) {
  57779. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57780. });
  57781. }
  57782. if (this._lifeTimeGradients) {
  57783. this._lifeTimeGradients.forEach(function (v) {
  57784. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57785. });
  57786. }
  57787. if (this._limitVelocityGradients) {
  57788. this._limitVelocityGradients.forEach(function (v) {
  57789. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57790. });
  57791. }
  57792. if (this._sizeGradients) {
  57793. this._sizeGradients.forEach(function (v) {
  57794. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57795. });
  57796. }
  57797. if (this._startSizeGradients) {
  57798. this._startSizeGradients.forEach(function (v) {
  57799. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57800. });
  57801. }
  57802. if (this._velocityGradients) {
  57803. this._velocityGradients.forEach(function (v) {
  57804. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57805. });
  57806. }
  57807. if (this._rampGradients) {
  57808. this._rampGradients.forEach(function (v) {
  57809. result.addRampGradient(v.gradient, v.color);
  57810. });
  57811. }
  57812. if (this._colorRemapGradients) {
  57813. this._colorRemapGradients.forEach(function (v) {
  57814. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57815. });
  57816. }
  57817. if (this._alphaRemapGradients) {
  57818. this._alphaRemapGradients.forEach(function (v) {
  57819. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57820. });
  57821. }
  57822. if (!this.preventAutoStart) {
  57823. result.start();
  57824. }
  57825. return result;
  57826. };
  57827. /**
  57828. * Serializes the particle system to a JSON object.
  57829. * @returns the JSON object
  57830. */
  57831. ParticleSystem.prototype.serialize = function () {
  57832. var serializationObject = {};
  57833. ParticleSystem._Serialize(serializationObject, this);
  57834. serializationObject.textureMask = this.textureMask.asArray();
  57835. serializationObject.customShader = this.customShader;
  57836. serializationObject.preventAutoStart = this.preventAutoStart;
  57837. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57838. return serializationObject;
  57839. };
  57840. /** @hidden */
  57841. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57842. serializationObject.name = particleSystem.name;
  57843. serializationObject.id = particleSystem.id;
  57844. serializationObject.capacity = particleSystem.getCapacity();
  57845. // Emitter
  57846. if (particleSystem.emitter.position) {
  57847. var emitterMesh = particleSystem.emitter;
  57848. serializationObject.emitterId = emitterMesh.id;
  57849. }
  57850. else {
  57851. var emitterPosition = particleSystem.emitter;
  57852. serializationObject.emitter = emitterPosition.asArray();
  57853. }
  57854. // Emitter
  57855. if (particleSystem.particleEmitterType) {
  57856. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57857. }
  57858. if (particleSystem.particleTexture) {
  57859. serializationObject.textureName = particleSystem.particleTexture.name;
  57860. }
  57861. // Animations
  57862. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57863. // Particle system
  57864. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57865. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57866. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57867. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57868. serializationObject.minSize = particleSystem.minSize;
  57869. serializationObject.maxSize = particleSystem.maxSize;
  57870. serializationObject.minScaleX = particleSystem.minScaleX;
  57871. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57872. serializationObject.minScaleY = particleSystem.minScaleY;
  57873. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57874. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57875. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57876. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57877. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57878. serializationObject.emitRate = particleSystem.emitRate;
  57879. serializationObject.gravity = particleSystem.gravity.asArray();
  57880. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57881. serializationObject.color1 = particleSystem.color1.asArray();
  57882. serializationObject.color2 = particleSystem.color2.asArray();
  57883. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57884. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57885. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57886. serializationObject.blendMode = particleSystem.blendMode;
  57887. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57888. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57889. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57890. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57891. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57892. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57893. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57894. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57895. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57896. var colorGradients = particleSystem.getColorGradients();
  57897. if (colorGradients) {
  57898. serializationObject.colorGradients = [];
  57899. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57900. var colorGradient = colorGradients_1[_i];
  57901. var serializedGradient = {
  57902. gradient: colorGradient.gradient,
  57903. color1: colorGradient.color1.asArray()
  57904. };
  57905. if (colorGradient.color2) {
  57906. serializedGradient.color2 = colorGradient.color2.asArray();
  57907. }
  57908. serializationObject.colorGradients.push(serializedGradient);
  57909. }
  57910. }
  57911. var rampGradients = particleSystem.getRampGradients();
  57912. if (rampGradients) {
  57913. serializationObject.rampGradients = [];
  57914. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57915. var rampGradient = rampGradients_1[_a];
  57916. var serializedGradient = {
  57917. gradient: rampGradient.gradient,
  57918. color: rampGradient.color.asArray()
  57919. };
  57920. serializationObject.rampGradients.push(serializedGradient);
  57921. }
  57922. }
  57923. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57924. if (colorRemapGradients) {
  57925. serializationObject.colorRemapGradients = [];
  57926. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57927. var colorRemapGradient = colorRemapGradients_1[_b];
  57928. var serializedGradient = {
  57929. gradient: colorRemapGradient.gradient,
  57930. factor1: colorRemapGradient.factor1
  57931. };
  57932. if (colorRemapGradient.factor2 !== undefined) {
  57933. serializedGradient.factor2 = colorRemapGradient.factor2;
  57934. }
  57935. serializationObject.colorRemapGradients.push(serializedGradient);
  57936. }
  57937. }
  57938. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57939. if (alphaRemapGradients) {
  57940. serializationObject.alphaRemapGradients = [];
  57941. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57942. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57943. var serializedGradient = {
  57944. gradient: alphaRemapGradient.gradient,
  57945. factor1: alphaRemapGradient.factor1
  57946. };
  57947. if (alphaRemapGradient.factor2 !== undefined) {
  57948. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57949. }
  57950. serializationObject.alphaRemapGradients.push(serializedGradient);
  57951. }
  57952. }
  57953. var sizeGradients = particleSystem.getSizeGradients();
  57954. if (sizeGradients) {
  57955. serializationObject.sizeGradients = [];
  57956. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57957. var sizeGradient = sizeGradients_1[_d];
  57958. var serializedGradient = {
  57959. gradient: sizeGradient.gradient,
  57960. factor1: sizeGradient.factor1
  57961. };
  57962. if (sizeGradient.factor2 !== undefined) {
  57963. serializedGradient.factor2 = sizeGradient.factor2;
  57964. }
  57965. serializationObject.sizeGradients.push(serializedGradient);
  57966. }
  57967. }
  57968. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57969. if (angularSpeedGradients) {
  57970. serializationObject.angularSpeedGradients = [];
  57971. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57972. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57973. var serializedGradient = {
  57974. gradient: angularSpeedGradient.gradient,
  57975. factor1: angularSpeedGradient.factor1
  57976. };
  57977. if (angularSpeedGradient.factor2 !== undefined) {
  57978. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57979. }
  57980. serializationObject.angularSpeedGradients.push(serializedGradient);
  57981. }
  57982. }
  57983. var velocityGradients = particleSystem.getVelocityGradients();
  57984. if (velocityGradients) {
  57985. serializationObject.velocityGradients = [];
  57986. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57987. var velocityGradient = velocityGradients_1[_f];
  57988. var serializedGradient = {
  57989. gradient: velocityGradient.gradient,
  57990. factor1: velocityGradient.factor1
  57991. };
  57992. if (velocityGradient.factor2 !== undefined) {
  57993. serializedGradient.factor2 = velocityGradient.factor2;
  57994. }
  57995. serializationObject.velocityGradients.push(serializedGradient);
  57996. }
  57997. }
  57998. var dragGradients = particleSystem.getDragGradients();
  57999. if (dragGradients) {
  58000. serializationObject.dragyGradients = [];
  58001. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  58002. var dragGradient = dragGradients_1[_g];
  58003. var serializedGradient = {
  58004. gradient: dragGradient.gradient,
  58005. factor1: dragGradient.factor1
  58006. };
  58007. if (dragGradient.factor2 !== undefined) {
  58008. serializedGradient.factor2 = dragGradient.factor2;
  58009. }
  58010. serializationObject.dragGradients.push(serializedGradient);
  58011. }
  58012. }
  58013. var emitRateGradients = particleSystem.getEmitRateGradients();
  58014. if (emitRateGradients) {
  58015. serializationObject.emitRateGradients = [];
  58016. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  58017. var emitRateGradient = emitRateGradients_1[_h];
  58018. var serializedGradient = {
  58019. gradient: emitRateGradient.gradient,
  58020. factor1: emitRateGradient.factor1
  58021. };
  58022. if (emitRateGradient.factor2 !== undefined) {
  58023. serializedGradient.factor2 = emitRateGradient.factor2;
  58024. }
  58025. serializationObject.emitRateGradients.push(serializedGradient);
  58026. }
  58027. }
  58028. var startSizeGradients = particleSystem.getStartSizeGradients();
  58029. if (startSizeGradients) {
  58030. serializationObject.startSizeGradients = [];
  58031. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  58032. var startSizeGradient = startSizeGradients_1[_j];
  58033. var serializedGradient = {
  58034. gradient: startSizeGradient.gradient,
  58035. factor1: startSizeGradient.factor1
  58036. };
  58037. if (startSizeGradient.factor2 !== undefined) {
  58038. serializedGradient.factor2 = startSizeGradient.factor2;
  58039. }
  58040. serializationObject.startSizeGradients.push(serializedGradient);
  58041. }
  58042. }
  58043. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  58044. if (limitVelocityGradients) {
  58045. serializationObject.limitVelocityGradients = [];
  58046. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  58047. var limitVelocityGradient = limitVelocityGradients_1[_k];
  58048. var serializedGradient = {
  58049. gradient: limitVelocityGradient.gradient,
  58050. factor1: limitVelocityGradient.factor1
  58051. };
  58052. if (limitVelocityGradient.factor2 !== undefined) {
  58053. serializedGradient.factor2 = limitVelocityGradient.factor2;
  58054. }
  58055. serializationObject.limitVelocityGradients.push(serializedGradient);
  58056. }
  58057. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  58058. }
  58059. if (particleSystem.noiseTexture) {
  58060. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  58061. }
  58062. };
  58063. /** @hidden */
  58064. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  58065. // Texture
  58066. if (parsedParticleSystem.textureName) {
  58067. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58068. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58069. }
  58070. // Emitter
  58071. if (parsedParticleSystem.emitterId === undefined) {
  58072. particleSystem.emitter = BABYLON.Vector3.Zero();
  58073. }
  58074. else if (parsedParticleSystem.emitterId) {
  58075. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58076. }
  58077. else {
  58078. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58079. }
  58080. // Misc.
  58081. if (parsedParticleSystem.renderingGroupId !== undefined) {
  58082. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  58083. }
  58084. if (parsedParticleSystem.isBillboardBased !== undefined) {
  58085. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  58086. }
  58087. // Animations
  58088. if (parsedParticleSystem.animations) {
  58089. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58090. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58091. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58092. }
  58093. }
  58094. if (parsedParticleSystem.autoAnimate) {
  58095. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  58096. }
  58097. // Particle system
  58098. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58099. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58100. particleSystem.minSize = parsedParticleSystem.minSize;
  58101. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58102. if (parsedParticleSystem.minScaleX) {
  58103. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  58104. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  58105. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  58106. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  58107. }
  58108. if (parsedParticleSystem.preWarmCycles !== undefined) {
  58109. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  58110. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  58111. }
  58112. if (parsedParticleSystem.minInitialRotation !== undefined) {
  58113. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  58114. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  58115. }
  58116. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58117. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58118. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58119. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58120. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58121. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58122. if (parsedParticleSystem.noiseStrength) {
  58123. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  58124. }
  58125. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58126. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58127. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58128. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58129. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58130. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58131. if (parsedParticleSystem.colorGradients) {
  58132. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  58133. var colorGradient = _a[_i];
  58134. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  58135. }
  58136. }
  58137. if (parsedParticleSystem.rampGradients) {
  58138. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  58139. var rampGradient = _c[_b];
  58140. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  58141. }
  58142. }
  58143. if (parsedParticleSystem.colorRemapGradients) {
  58144. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  58145. var colorRemapGradient = _e[_d];
  58146. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  58147. }
  58148. }
  58149. if (parsedParticleSystem.alphaRemapGradients) {
  58150. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  58151. var alphaRemapGradient = _g[_f];
  58152. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  58153. }
  58154. }
  58155. if (parsedParticleSystem.sizeGradients) {
  58156. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  58157. var sizeGradient = _j[_h];
  58158. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58159. }
  58160. }
  58161. if (parsedParticleSystem.sizeGradients) {
  58162. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  58163. var sizeGradient = _l[_k];
  58164. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58165. }
  58166. }
  58167. if (parsedParticleSystem.angularSpeedGradients) {
  58168. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58169. var angularSpeedGradient = _o[_m];
  58170. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58171. }
  58172. }
  58173. if (parsedParticleSystem.velocityGradients) {
  58174. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58175. var velocityGradient = _q[_p];
  58176. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58177. }
  58178. }
  58179. if (parsedParticleSystem.dragGradients) {
  58180. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58181. var dragGradient = _s[_r];
  58182. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58183. }
  58184. }
  58185. if (parsedParticleSystem.emitRateGradients) {
  58186. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58187. var emitRateGradient = _u[_t];
  58188. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58189. }
  58190. }
  58191. if (parsedParticleSystem.startSizeGradients) {
  58192. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58193. var startSizeGradient = _w[_v];
  58194. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58195. }
  58196. }
  58197. if (parsedParticleSystem.limitVelocityGradients) {
  58198. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58199. var limitVelocityGradient = _y[_x];
  58200. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58201. }
  58202. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58203. }
  58204. if (parsedParticleSystem.noiseTexture) {
  58205. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58206. }
  58207. // Emitter
  58208. var emitterType;
  58209. if (parsedParticleSystem.particleEmitterType) {
  58210. switch (parsedParticleSystem.particleEmitterType.type) {
  58211. case "SphereParticleEmitter":
  58212. emitterType = new BABYLON.SphereParticleEmitter();
  58213. break;
  58214. case "SphereDirectedParticleEmitter":
  58215. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58216. break;
  58217. case "ConeEmitter":
  58218. case "ConeParticleEmitter":
  58219. emitterType = new BABYLON.ConeParticleEmitter();
  58220. break;
  58221. case "BoxEmitter":
  58222. case "BoxParticleEmitter":
  58223. default:
  58224. emitterType = new BABYLON.BoxParticleEmitter();
  58225. break;
  58226. }
  58227. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58228. }
  58229. else {
  58230. emitterType = new BABYLON.BoxParticleEmitter();
  58231. emitterType.parse(parsedParticleSystem);
  58232. }
  58233. particleSystem.particleEmitterType = emitterType;
  58234. // Animation sheet
  58235. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58236. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58237. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58238. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58239. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58240. };
  58241. /**
  58242. * Parses a JSON object to create a particle system.
  58243. * @param parsedParticleSystem The JSON object to parse
  58244. * @param scene The scene to create the particle system in
  58245. * @param rootUrl The root url to use to load external dependencies like texture
  58246. * @returns the Parsed particle system
  58247. */
  58248. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58249. var name = parsedParticleSystem.name;
  58250. var custom = null;
  58251. var program = null;
  58252. if (parsedParticleSystem.customShader) {
  58253. program = parsedParticleSystem.customShader;
  58254. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58255. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58256. }
  58257. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58258. particleSystem.customShader = program;
  58259. if (parsedParticleSystem.id) {
  58260. particleSystem.id = parsedParticleSystem.id;
  58261. }
  58262. // Auto start
  58263. if (parsedParticleSystem.preventAutoStart) {
  58264. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58265. }
  58266. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58267. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58268. if (!particleSystem.preventAutoStart) {
  58269. particleSystem.start();
  58270. }
  58271. return particleSystem;
  58272. };
  58273. return ParticleSystem;
  58274. }(BABYLON.BaseParticleSystem));
  58275. BABYLON.ParticleSystem = ParticleSystem;
  58276. })(BABYLON || (BABYLON = {}));
  58277. //# sourceMappingURL=babylon.particleSystem.js.map
  58278. var BABYLON;
  58279. (function (BABYLON) {
  58280. /**
  58281. * Particle emitter emitting particles from the inside of a box.
  58282. * It emits the particles randomly between 2 given directions.
  58283. */
  58284. var BoxParticleEmitter = /** @class */ (function () {
  58285. /**
  58286. * Creates a new instance BoxParticleEmitter
  58287. */
  58288. function BoxParticleEmitter() {
  58289. /**
  58290. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58291. */
  58292. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58293. /**
  58294. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58295. */
  58296. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58297. /**
  58298. * 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.
  58299. */
  58300. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58301. /**
  58302. * 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.
  58303. */
  58304. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58305. }
  58306. /**
  58307. * Called by the particle System when the direction is computed for the created particle.
  58308. * @param worldMatrix is the world matrix of the particle system
  58309. * @param directionToUpdate is the direction vector to update with the result
  58310. * @param particle is the particle we are computed the direction for
  58311. */
  58312. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58313. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58314. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58315. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58316. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58317. };
  58318. /**
  58319. * Called by the particle System when the position is computed for the created particle.
  58320. * @param worldMatrix is the world matrix of the particle system
  58321. * @param positionToUpdate is the position vector to update with the result
  58322. * @param particle is the particle we are computed the position for
  58323. */
  58324. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58325. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58326. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58327. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58328. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58329. };
  58330. /**
  58331. * Clones the current emitter and returns a copy of it
  58332. * @returns the new emitter
  58333. */
  58334. BoxParticleEmitter.prototype.clone = function () {
  58335. var newOne = new BoxParticleEmitter();
  58336. BABYLON.Tools.DeepCopy(this, newOne);
  58337. return newOne;
  58338. };
  58339. /**
  58340. * Called by the GPUParticleSystem to setup the update shader
  58341. * @param effect defines the update shader
  58342. */
  58343. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58344. effect.setVector3("direction1", this.direction1);
  58345. effect.setVector3("direction2", this.direction2);
  58346. effect.setVector3("minEmitBox", this.minEmitBox);
  58347. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58348. };
  58349. /**
  58350. * Returns a string to use to update the GPU particles update shader
  58351. * @returns a string containng the defines string
  58352. */
  58353. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58354. return "#define BOXEMITTER";
  58355. };
  58356. /**
  58357. * Returns the string "BoxParticleEmitter"
  58358. * @returns a string containing the class name
  58359. */
  58360. BoxParticleEmitter.prototype.getClassName = function () {
  58361. return "BoxParticleEmitter";
  58362. };
  58363. /**
  58364. * Serializes the particle system to a JSON object.
  58365. * @returns the JSON object
  58366. */
  58367. BoxParticleEmitter.prototype.serialize = function () {
  58368. var serializationObject = {};
  58369. serializationObject.type = this.getClassName();
  58370. serializationObject.direction1 = this.direction1.asArray();
  58371. serializationObject.direction2 = this.direction2.asArray();
  58372. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58373. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58374. return serializationObject;
  58375. };
  58376. /**
  58377. * Parse properties from a JSON object
  58378. * @param serializationObject defines the JSON object
  58379. */
  58380. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58381. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58382. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58383. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58384. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58385. };
  58386. return BoxParticleEmitter;
  58387. }());
  58388. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58389. })(BABYLON || (BABYLON = {}));
  58390. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58391. var BABYLON;
  58392. (function (BABYLON) {
  58393. /**
  58394. * Particle emitter emitting particles from the inside of a cylinder.
  58395. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58396. */
  58397. var CylinderParticleEmitter = /** @class */ (function () {
  58398. /**
  58399. * Creates a new instance CylinderParticleEmitter
  58400. * @param radius the radius of the emission cylinder (1 by default)
  58401. * @param height the height of the emission cylinder (1 by default)
  58402. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58403. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58404. */
  58405. function CylinderParticleEmitter(
  58406. /**
  58407. * The radius of the emission cylinder.
  58408. */
  58409. radius,
  58410. /**
  58411. * The height of the emission cylinder.
  58412. */
  58413. height,
  58414. /**
  58415. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58416. */
  58417. radiusRange,
  58418. /**
  58419. * How much to randomize the particle direction [0-1].
  58420. */
  58421. directionRandomizer) {
  58422. if (radius === void 0) { radius = 1; }
  58423. if (height === void 0) { height = 1; }
  58424. if (radiusRange === void 0) { radiusRange = 1; }
  58425. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58426. this.radius = radius;
  58427. this.height = height;
  58428. this.radiusRange = radiusRange;
  58429. this.directionRandomizer = directionRandomizer;
  58430. }
  58431. /**
  58432. * Called by the particle System when the direction is computed for the created particle.
  58433. * @param worldMatrix is the world matrix of the particle system
  58434. * @param directionToUpdate is the direction vector to update with the result
  58435. * @param particle is the particle we are computed the direction for
  58436. */
  58437. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58438. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58439. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58440. var angle = Math.atan2(direction.x, direction.z);
  58441. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58442. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58443. direction.x = Math.sin(angle);
  58444. direction.z = Math.cos(angle);
  58445. direction.normalize();
  58446. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58447. };
  58448. /**
  58449. * Called by the particle System when the position is computed for the created particle.
  58450. * @param worldMatrix is the world matrix of the particle system
  58451. * @param positionToUpdate is the position vector to update with the result
  58452. * @param particle is the particle we are computed the position for
  58453. */
  58454. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58455. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58456. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58457. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58458. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58459. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58460. var xPos = positionRadius * Math.cos(angle);
  58461. var zPos = positionRadius * Math.sin(angle);
  58462. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58463. };
  58464. /**
  58465. * Clones the current emitter and returns a copy of it
  58466. * @returns the new emitter
  58467. */
  58468. CylinderParticleEmitter.prototype.clone = function () {
  58469. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58470. BABYLON.Tools.DeepCopy(this, newOne);
  58471. return newOne;
  58472. };
  58473. /**
  58474. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58475. * @param effect defines the update shader
  58476. */
  58477. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58478. effect.setFloat("radius", this.radius);
  58479. effect.setFloat("height", this.height);
  58480. effect.setFloat("radiusRange", this.radiusRange);
  58481. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58482. };
  58483. /**
  58484. * Returns a string to use to update the GPU particles update shader
  58485. * @returns a string containng the defines string
  58486. */
  58487. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58488. return "#define CYLINDEREMITTER";
  58489. };
  58490. /**
  58491. * Returns the string "CylinderParticleEmitter"
  58492. * @returns a string containing the class name
  58493. */
  58494. CylinderParticleEmitter.prototype.getClassName = function () {
  58495. return "CylinderParticleEmitter";
  58496. };
  58497. /**
  58498. * Serializes the particle system to a JSON object.
  58499. * @returns the JSON object
  58500. */
  58501. CylinderParticleEmitter.prototype.serialize = function () {
  58502. var serializationObject = {};
  58503. serializationObject.type = this.getClassName();
  58504. serializationObject.radius = this.radius;
  58505. serializationObject.height = this.height;
  58506. serializationObject.radiusRange = this.radiusRange;
  58507. serializationObject.directionRandomizer = this.directionRandomizer;
  58508. return serializationObject;
  58509. };
  58510. /**
  58511. * Parse properties from a JSON object
  58512. * @param serializationObject defines the JSON object
  58513. */
  58514. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58515. this.radius = serializationObject.radius;
  58516. this.height = serializationObject.height;
  58517. this.radiusRange = serializationObject.radiusRange;
  58518. this.directionRandomizer = serializationObject.directionRandomizer;
  58519. };
  58520. return CylinderParticleEmitter;
  58521. }());
  58522. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58523. /**
  58524. * Particle emitter emitting particles from the inside of a cylinder.
  58525. * It emits the particles randomly between two vectors.
  58526. */
  58527. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58528. __extends(CylinderDirectedParticleEmitter, _super);
  58529. /**
  58530. * Creates a new instance CylinderDirectedParticleEmitter
  58531. * @param radius the radius of the emission cylinder (1 by default)
  58532. * @param height the height of the emission cylinder (1 by default)
  58533. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58534. * @param direction1 the min limit of the emission direction (up vector by default)
  58535. * @param direction2 the max limit of the emission direction (up vector by default)
  58536. */
  58537. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58538. /**
  58539. * The min limit of the emission direction.
  58540. */
  58541. direction1,
  58542. /**
  58543. * The max limit of the emission direction.
  58544. */
  58545. direction2) {
  58546. if (radius === void 0) { radius = 1; }
  58547. if (height === void 0) { height = 1; }
  58548. if (radiusRange === void 0) { radiusRange = 1; }
  58549. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58550. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58551. var _this = _super.call(this, radius, height, radiusRange) || this;
  58552. _this.direction1 = direction1;
  58553. _this.direction2 = direction2;
  58554. return _this;
  58555. }
  58556. /**
  58557. * Called by the particle System when the direction is computed for the created particle.
  58558. * @param worldMatrix is the world matrix of the particle system
  58559. * @param directionToUpdate is the direction vector to update with the result
  58560. * @param particle is the particle we are computed the direction for
  58561. */
  58562. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58563. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58564. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58565. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58566. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58567. };
  58568. /**
  58569. * Clones the current emitter and returns a copy of it
  58570. * @returns the new emitter
  58571. */
  58572. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58573. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58574. BABYLON.Tools.DeepCopy(this, newOne);
  58575. return newOne;
  58576. };
  58577. /**
  58578. * Called by the GPUParticleSystem to setup the update shader
  58579. * @param effect defines the update shader
  58580. */
  58581. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58582. effect.setFloat("radius", this.radius);
  58583. effect.setFloat("height", this.height);
  58584. effect.setFloat("radiusRange", this.radiusRange);
  58585. effect.setVector3("direction1", this.direction1);
  58586. effect.setVector3("direction2", this.direction2);
  58587. };
  58588. /**
  58589. * Returns a string to use to update the GPU particles update shader
  58590. * @returns a string containng the defines string
  58591. */
  58592. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58593. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58594. };
  58595. /**
  58596. * Returns the string "CylinderDirectedParticleEmitter"
  58597. * @returns a string containing the class name
  58598. */
  58599. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58600. return "CylinderDirectedParticleEmitter";
  58601. };
  58602. /**
  58603. * Serializes the particle system to a JSON object.
  58604. * @returns the JSON object
  58605. */
  58606. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58607. var serializationObject = _super.prototype.serialize.call(this);
  58608. serializationObject.direction1 = this.direction1.asArray();
  58609. serializationObject.direction2 = this.direction2.asArray();
  58610. return serializationObject;
  58611. };
  58612. /**
  58613. * Parse properties from a JSON object
  58614. * @param serializationObject defines the JSON object
  58615. */
  58616. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58617. _super.prototype.parse.call(this, serializationObject);
  58618. this.direction1.copyFrom(serializationObject.direction1);
  58619. this.direction2.copyFrom(serializationObject.direction2);
  58620. };
  58621. return CylinderDirectedParticleEmitter;
  58622. }(CylinderParticleEmitter));
  58623. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58624. })(BABYLON || (BABYLON = {}));
  58625. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58626. var BABYLON;
  58627. (function (BABYLON) {
  58628. /**
  58629. * Particle emitter emitting particles from the inside of a cone.
  58630. * It emits the particles alongside the cone volume from the base to the particle.
  58631. * The emission direction might be randomized.
  58632. */
  58633. var ConeParticleEmitter = /** @class */ (function () {
  58634. /**
  58635. * Creates a new instance ConeParticleEmitter
  58636. * @param radius the radius of the emission cone (1 by default)
  58637. * @param angles the cone base angle (PI by default)
  58638. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58639. */
  58640. function ConeParticleEmitter(radius, angle,
  58641. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58642. directionRandomizer) {
  58643. if (radius === void 0) { radius = 1; }
  58644. if (angle === void 0) { angle = Math.PI; }
  58645. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58646. this.directionRandomizer = directionRandomizer;
  58647. /**
  58648. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58649. */
  58650. this.radiusRange = 1;
  58651. /**
  58652. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58653. */
  58654. this.heightRange = 1;
  58655. /**
  58656. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58657. */
  58658. this.emitFromSpawnPointOnly = false;
  58659. this.angle = angle;
  58660. this.radius = radius;
  58661. }
  58662. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58663. /**
  58664. * Gets or sets the radius of the emission cone
  58665. */
  58666. get: function () {
  58667. return this._radius;
  58668. },
  58669. set: function (value) {
  58670. this._radius = value;
  58671. this._buildHeight();
  58672. },
  58673. enumerable: true,
  58674. configurable: true
  58675. });
  58676. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58677. /**
  58678. * Gets or sets the angle of the emission cone
  58679. */
  58680. get: function () {
  58681. return this._angle;
  58682. },
  58683. set: function (value) {
  58684. this._angle = value;
  58685. this._buildHeight();
  58686. },
  58687. enumerable: true,
  58688. configurable: true
  58689. });
  58690. ConeParticleEmitter.prototype._buildHeight = function () {
  58691. if (this._angle !== 0) {
  58692. this._height = this._radius / Math.tan(this._angle / 2);
  58693. }
  58694. else {
  58695. this._height = 1;
  58696. }
  58697. };
  58698. /**
  58699. * Called by the particle System when the direction is computed for the created particle.
  58700. * @param worldMatrix is the world matrix of the particle system
  58701. * @param directionToUpdate is the direction vector to update with the result
  58702. * @param particle is the particle we are computed the direction for
  58703. */
  58704. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58705. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58706. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58707. }
  58708. else {
  58709. // measure the direction Vector from the emitter to the particle.
  58710. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58711. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58712. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58713. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58714. direction.x += randX;
  58715. direction.y += randY;
  58716. direction.z += randZ;
  58717. direction.normalize();
  58718. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58719. }
  58720. };
  58721. /**
  58722. * Called by the particle System when the position is computed for the created particle.
  58723. * @param worldMatrix is the world matrix of the particle system
  58724. * @param positionToUpdate is the position vector to update with the result
  58725. * @param particle is the particle we are computed the position for
  58726. */
  58727. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58728. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58729. var h;
  58730. if (!this.emitFromSpawnPointOnly) {
  58731. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58732. // Better distribution in a cone at normal angles.
  58733. h = 1 - h * h;
  58734. }
  58735. else {
  58736. h = 0.0001;
  58737. }
  58738. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58739. radius = radius * h;
  58740. var randX = radius * Math.sin(s);
  58741. var randZ = radius * Math.cos(s);
  58742. var randY = h * this._height;
  58743. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58744. };
  58745. /**
  58746. * Clones the current emitter and returns a copy of it
  58747. * @returns the new emitter
  58748. */
  58749. ConeParticleEmitter.prototype.clone = function () {
  58750. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58751. BABYLON.Tools.DeepCopy(this, newOne);
  58752. return newOne;
  58753. };
  58754. /**
  58755. * Called by the GPUParticleSystem to setup the update shader
  58756. * @param effect defines the update shader
  58757. */
  58758. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58759. effect.setFloat2("radius", this._radius, this.radiusRange);
  58760. effect.setFloat("coneAngle", this._angle);
  58761. effect.setFloat2("height", this._height, this.heightRange);
  58762. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58763. };
  58764. /**
  58765. * Returns a string to use to update the GPU particles update shader
  58766. * @returns a string containng the defines string
  58767. */
  58768. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58769. var defines = "#define CONEEMITTER";
  58770. if (this.emitFromSpawnPointOnly) {
  58771. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58772. }
  58773. return defines;
  58774. };
  58775. /**
  58776. * Returns the string "ConeParticleEmitter"
  58777. * @returns a string containing the class name
  58778. */
  58779. ConeParticleEmitter.prototype.getClassName = function () {
  58780. return "ConeParticleEmitter";
  58781. };
  58782. /**
  58783. * Serializes the particle system to a JSON object.
  58784. * @returns the JSON object
  58785. */
  58786. ConeParticleEmitter.prototype.serialize = function () {
  58787. var serializationObject = {};
  58788. serializationObject.type = this.getClassName();
  58789. serializationObject.radius = this._radius;
  58790. serializationObject.angle = this._angle;
  58791. serializationObject.directionRandomizer = this.directionRandomizer;
  58792. return serializationObject;
  58793. };
  58794. /**
  58795. * Parse properties from a JSON object
  58796. * @param serializationObject defines the JSON object
  58797. */
  58798. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58799. this.radius = serializationObject.radius;
  58800. this.angle = serializationObject.angle;
  58801. this.directionRandomizer = serializationObject.directionRandomizer;
  58802. };
  58803. return ConeParticleEmitter;
  58804. }());
  58805. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58806. })(BABYLON || (BABYLON = {}));
  58807. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58808. var BABYLON;
  58809. (function (BABYLON) {
  58810. /**
  58811. * Particle emitter emitting particles from the inside of a sphere.
  58812. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58813. */
  58814. var SphereParticleEmitter = /** @class */ (function () {
  58815. /**
  58816. * Creates a new instance SphereParticleEmitter
  58817. * @param radius the radius of the emission sphere (1 by default)
  58818. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58819. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58820. */
  58821. function SphereParticleEmitter(
  58822. /**
  58823. * The radius of the emission sphere.
  58824. */
  58825. radius,
  58826. /**
  58827. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58828. */
  58829. radiusRange,
  58830. /**
  58831. * How much to randomize the particle direction [0-1].
  58832. */
  58833. directionRandomizer) {
  58834. if (radius === void 0) { radius = 1; }
  58835. if (radiusRange === void 0) { radiusRange = 1; }
  58836. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58837. this.radius = radius;
  58838. this.radiusRange = radiusRange;
  58839. this.directionRandomizer = directionRandomizer;
  58840. }
  58841. /**
  58842. * Called by the particle System when the direction is computed for the created particle.
  58843. * @param worldMatrix is the world matrix of the particle system
  58844. * @param directionToUpdate is the direction vector to update with the result
  58845. * @param particle is the particle we are computed the direction for
  58846. */
  58847. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58848. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58849. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58850. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58851. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58852. direction.x += randX;
  58853. direction.y += randY;
  58854. direction.z += randZ;
  58855. direction.normalize();
  58856. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58857. };
  58858. /**
  58859. * Called by the particle System when the position is computed for the created particle.
  58860. * @param worldMatrix is the world matrix of the particle system
  58861. * @param positionToUpdate is the position vector to update with the result
  58862. * @param particle is the particle we are computed the position for
  58863. */
  58864. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58865. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58866. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58867. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58868. var theta = Math.acos(2 * v - 1);
  58869. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58870. var randY = randRadius * Math.cos(theta);
  58871. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58872. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58873. };
  58874. /**
  58875. * Clones the current emitter and returns a copy of it
  58876. * @returns the new emitter
  58877. */
  58878. SphereParticleEmitter.prototype.clone = function () {
  58879. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58880. BABYLON.Tools.DeepCopy(this, newOne);
  58881. return newOne;
  58882. };
  58883. /**
  58884. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58885. * @param effect defines the update shader
  58886. */
  58887. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58888. effect.setFloat("radius", this.radius);
  58889. effect.setFloat("radiusRange", this.radiusRange);
  58890. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58891. };
  58892. /**
  58893. * Returns a string to use to update the GPU particles update shader
  58894. * @returns a string containng the defines string
  58895. */
  58896. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58897. return "#define SPHEREEMITTER";
  58898. };
  58899. /**
  58900. * Returns the string "SphereParticleEmitter"
  58901. * @returns a string containing the class name
  58902. */
  58903. SphereParticleEmitter.prototype.getClassName = function () {
  58904. return "SphereParticleEmitter";
  58905. };
  58906. /**
  58907. * Serializes the particle system to a JSON object.
  58908. * @returns the JSON object
  58909. */
  58910. SphereParticleEmitter.prototype.serialize = function () {
  58911. var serializationObject = {};
  58912. serializationObject.type = this.getClassName();
  58913. serializationObject.radius = this.radius;
  58914. serializationObject.radiusRange = this.radiusRange;
  58915. serializationObject.directionRandomizer = this.directionRandomizer;
  58916. return serializationObject;
  58917. };
  58918. /**
  58919. * Parse properties from a JSON object
  58920. * @param serializationObject defines the JSON object
  58921. */
  58922. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58923. this.radius = serializationObject.radius;
  58924. this.radiusRange = serializationObject.radiusRange;
  58925. this.directionRandomizer = serializationObject.directionRandomizer;
  58926. };
  58927. return SphereParticleEmitter;
  58928. }());
  58929. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58930. /**
  58931. * Particle emitter emitting particles from the inside of a sphere.
  58932. * It emits the particles randomly between two vectors.
  58933. */
  58934. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58935. __extends(SphereDirectedParticleEmitter, _super);
  58936. /**
  58937. * Creates a new instance SphereDirectedParticleEmitter
  58938. * @param radius the radius of the emission sphere (1 by default)
  58939. * @param direction1 the min limit of the emission direction (up vector by default)
  58940. * @param direction2 the max limit of the emission direction (up vector by default)
  58941. */
  58942. function SphereDirectedParticleEmitter(radius,
  58943. /**
  58944. * The min limit of the emission direction.
  58945. */
  58946. direction1,
  58947. /**
  58948. * The max limit of the emission direction.
  58949. */
  58950. direction2) {
  58951. if (radius === void 0) { radius = 1; }
  58952. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58953. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58954. var _this = _super.call(this, radius) || this;
  58955. _this.direction1 = direction1;
  58956. _this.direction2 = direction2;
  58957. return _this;
  58958. }
  58959. /**
  58960. * Called by the particle System when the direction is computed for the created particle.
  58961. * @param worldMatrix is the world matrix of the particle system
  58962. * @param directionToUpdate is the direction vector to update with the result
  58963. * @param particle is the particle we are computed the direction for
  58964. */
  58965. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58966. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58967. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58968. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58969. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58970. };
  58971. /**
  58972. * Clones the current emitter and returns a copy of it
  58973. * @returns the new emitter
  58974. */
  58975. SphereDirectedParticleEmitter.prototype.clone = function () {
  58976. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58977. BABYLON.Tools.DeepCopy(this, newOne);
  58978. return newOne;
  58979. };
  58980. /**
  58981. * Called by the GPUParticleSystem to setup the update shader
  58982. * @param effect defines the update shader
  58983. */
  58984. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58985. effect.setFloat("radius", this.radius);
  58986. effect.setFloat("radiusRange", this.radiusRange);
  58987. effect.setVector3("direction1", this.direction1);
  58988. effect.setVector3("direction2", this.direction2);
  58989. };
  58990. /**
  58991. * Returns a string to use to update the GPU particles update shader
  58992. * @returns a string containng the defines string
  58993. */
  58994. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58995. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58996. };
  58997. /**
  58998. * Returns the string "SphereDirectedParticleEmitter"
  58999. * @returns a string containing the class name
  59000. */
  59001. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  59002. return "SphereDirectedParticleEmitter";
  59003. };
  59004. /**
  59005. * Serializes the particle system to a JSON object.
  59006. * @returns the JSON object
  59007. */
  59008. SphereDirectedParticleEmitter.prototype.serialize = function () {
  59009. var serializationObject = _super.prototype.serialize.call(this);
  59010. serializationObject.direction1 = this.direction1.asArray();
  59011. serializationObject.direction2 = this.direction2.asArray();
  59012. return serializationObject;
  59013. };
  59014. /**
  59015. * Parse properties from a JSON object
  59016. * @param serializationObject defines the JSON object
  59017. */
  59018. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59019. _super.prototype.parse.call(this, serializationObject);
  59020. this.direction1.copyFrom(serializationObject.direction1);
  59021. this.direction2.copyFrom(serializationObject.direction2);
  59022. };
  59023. return SphereDirectedParticleEmitter;
  59024. }(SphereParticleEmitter));
  59025. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  59026. })(BABYLON || (BABYLON = {}));
  59027. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  59028. var BABYLON;
  59029. (function (BABYLON) {
  59030. /**
  59031. * Particle emitter emitting particles from the inside of a hemisphere.
  59032. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  59033. */
  59034. var HemisphericParticleEmitter = /** @class */ (function () {
  59035. /**
  59036. * Creates a new instance HemisphericParticleEmitter
  59037. * @param radius the radius of the emission hemisphere (1 by default)
  59038. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59039. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59040. */
  59041. function HemisphericParticleEmitter(
  59042. /**
  59043. * The radius of the emission hemisphere.
  59044. */
  59045. radius,
  59046. /**
  59047. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59048. */
  59049. radiusRange,
  59050. /**
  59051. * How much to randomize the particle direction [0-1].
  59052. */
  59053. directionRandomizer) {
  59054. if (radius === void 0) { radius = 1; }
  59055. if (radiusRange === void 0) { radiusRange = 1; }
  59056. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59057. this.radius = radius;
  59058. this.radiusRange = radiusRange;
  59059. this.directionRandomizer = directionRandomizer;
  59060. }
  59061. /**
  59062. * Called by the particle System when the direction is computed for the created particle.
  59063. * @param worldMatrix is the world matrix of the particle system
  59064. * @param directionToUpdate is the direction vector to update with the result
  59065. * @param particle is the particle we are computed the direction for
  59066. */
  59067. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59068. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59069. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59070. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59071. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59072. direction.x += randX;
  59073. direction.y += randY;
  59074. direction.z += randZ;
  59075. direction.normalize();
  59076. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59077. };
  59078. /**
  59079. * Called by the particle System when the position is computed for the created particle.
  59080. * @param worldMatrix is the world matrix of the particle system
  59081. * @param positionToUpdate is the position vector to update with the result
  59082. * @param particle is the particle we are computed the position for
  59083. */
  59084. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59085. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59086. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59087. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59088. var theta = Math.acos(2 * v - 1);
  59089. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59090. var randY = randRadius * Math.cos(theta);
  59091. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59092. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  59093. };
  59094. /**
  59095. * Clones the current emitter and returns a copy of it
  59096. * @returns the new emitter
  59097. */
  59098. HemisphericParticleEmitter.prototype.clone = function () {
  59099. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  59100. BABYLON.Tools.DeepCopy(this, newOne);
  59101. return newOne;
  59102. };
  59103. /**
  59104. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59105. * @param effect defines the update shader
  59106. */
  59107. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  59108. effect.setFloat("radius", this.radius);
  59109. effect.setFloat("radiusRange", this.radiusRange);
  59110. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59111. };
  59112. /**
  59113. * Returns a string to use to update the GPU particles update shader
  59114. * @returns a string containng the defines string
  59115. */
  59116. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  59117. return "#define HEMISPHERICEMITTER";
  59118. };
  59119. /**
  59120. * Returns the string "HemisphericParticleEmitter"
  59121. * @returns a string containing the class name
  59122. */
  59123. HemisphericParticleEmitter.prototype.getClassName = function () {
  59124. return "HemisphericParticleEmitter";
  59125. };
  59126. /**
  59127. * Serializes the particle system to a JSON object.
  59128. * @returns the JSON object
  59129. */
  59130. HemisphericParticleEmitter.prototype.serialize = function () {
  59131. var serializationObject = {};
  59132. serializationObject.type = this.getClassName();
  59133. serializationObject.radius = this.radius;
  59134. serializationObject.radiusRange = this.radiusRange;
  59135. serializationObject.directionRandomizer = this.directionRandomizer;
  59136. return serializationObject;
  59137. };
  59138. /**
  59139. * Parse properties from a JSON object
  59140. * @param serializationObject defines the JSON object
  59141. */
  59142. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  59143. this.radius = serializationObject.radius;
  59144. this.radiusRange = serializationObject.radiusRange;
  59145. this.directionRandomizer = serializationObject.directionRandomizer;
  59146. };
  59147. return HemisphericParticleEmitter;
  59148. }());
  59149. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  59150. })(BABYLON || (BABYLON = {}));
  59151. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  59152. var BABYLON;
  59153. (function (BABYLON) {
  59154. /**
  59155. * Particle emitter emitting particles from a point.
  59156. * It emits the particles randomly between 2 given directions.
  59157. */
  59158. var PointParticleEmitter = /** @class */ (function () {
  59159. /**
  59160. * Creates a new instance PointParticleEmitter
  59161. */
  59162. function PointParticleEmitter() {
  59163. /**
  59164. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59165. */
  59166. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59167. /**
  59168. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59169. */
  59170. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59171. }
  59172. /**
  59173. * Called by the particle System when the direction is computed for the created particle.
  59174. * @param worldMatrix is the world matrix of the particle system
  59175. * @param directionToUpdate is the direction vector to update with the result
  59176. * @param particle is the particle we are computed the direction for
  59177. */
  59178. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59179. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59180. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59181. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59182. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59183. };
  59184. /**
  59185. * Called by the particle System when the position is computed for the created particle.
  59186. * @param worldMatrix is the world matrix of the particle system
  59187. * @param positionToUpdate is the position vector to update with the result
  59188. * @param particle is the particle we are computed the position for
  59189. */
  59190. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59192. };
  59193. /**
  59194. * Clones the current emitter and returns a copy of it
  59195. * @returns the new emitter
  59196. */
  59197. PointParticleEmitter.prototype.clone = function () {
  59198. var newOne = new PointParticleEmitter();
  59199. BABYLON.Tools.DeepCopy(this, newOne);
  59200. return newOne;
  59201. };
  59202. /**
  59203. * Called by the GPUParticleSystem to setup the update shader
  59204. * @param effect defines the update shader
  59205. */
  59206. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59207. effect.setVector3("direction1", this.direction1);
  59208. effect.setVector3("direction2", this.direction2);
  59209. };
  59210. /**
  59211. * Returns a string to use to update the GPU particles update shader
  59212. * @returns a string containng the defines string
  59213. */
  59214. PointParticleEmitter.prototype.getEffectDefines = function () {
  59215. return "#define POINTEMITTER";
  59216. };
  59217. /**
  59218. * Returns the string "PointParticleEmitter"
  59219. * @returns a string containing the class name
  59220. */
  59221. PointParticleEmitter.prototype.getClassName = function () {
  59222. return "PointParticleEmitter";
  59223. };
  59224. /**
  59225. * Serializes the particle system to a JSON object.
  59226. * @returns the JSON object
  59227. */
  59228. PointParticleEmitter.prototype.serialize = function () {
  59229. var serializationObject = {};
  59230. serializationObject.type = this.getClassName();
  59231. serializationObject.direction1 = this.direction1.asArray();
  59232. serializationObject.direction2 = this.direction2.asArray();
  59233. return serializationObject;
  59234. };
  59235. /**
  59236. * Parse properties from a JSON object
  59237. * @param serializationObject defines the JSON object
  59238. */
  59239. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59240. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59241. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59242. };
  59243. return PointParticleEmitter;
  59244. }());
  59245. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59246. })(BABYLON || (BABYLON = {}));
  59247. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59248. var BABYLON;
  59249. (function (BABYLON) {
  59250. // Adds the parsers to the scene parsers.
  59251. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59252. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59253. if (!individualParser) {
  59254. return;
  59255. }
  59256. // Particles Systems
  59257. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59258. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59259. var parsedParticleSystem = parsedData.particleSystems[index];
  59260. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59261. }
  59262. }
  59263. });
  59264. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59265. if (parsedParticleSystem.activeParticleCount) {
  59266. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59267. return ps;
  59268. }
  59269. else {
  59270. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59271. return ps;
  59272. }
  59273. });
  59274. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59275. if (uniformsNames === void 0) { uniformsNames = []; }
  59276. if (samplers === void 0) { samplers = []; }
  59277. if (defines === void 0) { defines = ""; }
  59278. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59279. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59280. if (defines.indexOf(" BILLBOARD") === -1) {
  59281. defines += "\n#define BILLBOARD\n";
  59282. }
  59283. if (samplers.indexOf("diffuseSampler") === -1) {
  59284. samplers.push("diffuseSampler");
  59285. }
  59286. return this.createEffect({
  59287. vertex: "particles",
  59288. fragmentElement: fragmentName
  59289. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59290. };
  59291. })(BABYLON || (BABYLON = {}));
  59292. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59293. var BABYLON;
  59294. (function (BABYLON) {
  59295. /**
  59296. * Type of sub emitter
  59297. */
  59298. var SubEmitterType;
  59299. (function (SubEmitterType) {
  59300. /**
  59301. * Attached to the particle over it's lifetime
  59302. */
  59303. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59304. /**
  59305. * Created when the particle dies
  59306. */
  59307. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59308. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59309. /**
  59310. * Sub emitter class used to emit particles from an existing particle
  59311. */
  59312. var SubEmitter = /** @class */ (function () {
  59313. /**
  59314. * Creates a sub emitter
  59315. * @param particleSystem the particle system to be used by the sub emitter
  59316. */
  59317. function SubEmitter(
  59318. /**
  59319. * the particle system to be used by the sub emitter
  59320. */
  59321. particleSystem) {
  59322. this.particleSystem = particleSystem;
  59323. /**
  59324. * Type of the submitter (Default: END)
  59325. */
  59326. this.type = SubEmitterType.END;
  59327. /**
  59328. * 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)
  59329. * Note: This only is supported when using an emitter of type Mesh
  59330. */
  59331. this.inheritDirection = false;
  59332. /**
  59333. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59334. */
  59335. this.inheritedVelocityAmount = 0;
  59336. }
  59337. /**
  59338. * Clones the sub emitter
  59339. * @returns the cloned sub emitter
  59340. */
  59341. SubEmitter.prototype.clone = function () {
  59342. // Clone particle system
  59343. var emitter = this.particleSystem.emitter;
  59344. if (!emitter) {
  59345. emitter = new BABYLON.Vector3();
  59346. }
  59347. else if (emitter instanceof BABYLON.Vector3) {
  59348. emitter = emitter.clone();
  59349. }
  59350. else if (emitter instanceof BABYLON.AbstractMesh) {
  59351. emitter = new BABYLON.Mesh("", emitter._scene);
  59352. }
  59353. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59354. // Clone properties
  59355. clone.type = this.type;
  59356. clone.inheritDirection = this.inheritDirection;
  59357. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59358. clone.particleSystem._disposeEmitterOnDispose = true;
  59359. return clone;
  59360. };
  59361. return SubEmitter;
  59362. }());
  59363. BABYLON.SubEmitter = SubEmitter;
  59364. })(BABYLON || (BABYLON = {}));
  59365. //# sourceMappingURL=babylon.subEmitter.js.map
  59366. var BABYLON;
  59367. (function (BABYLON) {
  59368. var ShaderMaterial = /** @class */ (function (_super) {
  59369. __extends(ShaderMaterial, _super);
  59370. function ShaderMaterial(name, scene, shaderPath, options) {
  59371. var _this = _super.call(this, name, scene) || this;
  59372. _this._textures = {};
  59373. _this._textureArrays = {};
  59374. _this._floats = {};
  59375. _this._ints = {};
  59376. _this._floatsArrays = {};
  59377. _this._colors3 = {};
  59378. _this._colors3Arrays = {};
  59379. _this._colors4 = {};
  59380. _this._vectors2 = {};
  59381. _this._vectors3 = {};
  59382. _this._vectors4 = {};
  59383. _this._matrices = {};
  59384. _this._matrices3x3 = {};
  59385. _this._matrices2x2 = {};
  59386. _this._vectors2Arrays = {};
  59387. _this._vectors3Arrays = {};
  59388. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59389. _this._shaderPath = shaderPath;
  59390. options.needAlphaBlending = options.needAlphaBlending || false;
  59391. options.needAlphaTesting = options.needAlphaTesting || false;
  59392. options.attributes = options.attributes || ["position", "normal", "uv"];
  59393. options.uniforms = options.uniforms || ["worldViewProjection"];
  59394. options.uniformBuffers = options.uniformBuffers || [];
  59395. options.samplers = options.samplers || [];
  59396. options.defines = options.defines || [];
  59397. _this._options = options;
  59398. return _this;
  59399. }
  59400. ShaderMaterial.prototype.getClassName = function () {
  59401. return "ShaderMaterial";
  59402. };
  59403. ShaderMaterial.prototype.needAlphaBlending = function () {
  59404. return this._options.needAlphaBlending;
  59405. };
  59406. ShaderMaterial.prototype.needAlphaTesting = function () {
  59407. return this._options.needAlphaTesting;
  59408. };
  59409. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59410. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59411. this._options.uniforms.push(uniformName);
  59412. }
  59413. };
  59414. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59415. if (this._options.samplers.indexOf(name) === -1) {
  59416. this._options.samplers.push(name);
  59417. }
  59418. this._textures[name] = texture;
  59419. return this;
  59420. };
  59421. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59422. if (this._options.samplers.indexOf(name) === -1) {
  59423. this._options.samplers.push(name);
  59424. }
  59425. this._checkUniform(name);
  59426. this._textureArrays[name] = textures;
  59427. return this;
  59428. };
  59429. ShaderMaterial.prototype.setFloat = function (name, value) {
  59430. this._checkUniform(name);
  59431. this._floats[name] = value;
  59432. return this;
  59433. };
  59434. ShaderMaterial.prototype.setInt = function (name, value) {
  59435. this._checkUniform(name);
  59436. this._ints[name] = value;
  59437. return this;
  59438. };
  59439. ShaderMaterial.prototype.setFloats = function (name, value) {
  59440. this._checkUniform(name);
  59441. this._floatsArrays[name] = value;
  59442. return this;
  59443. };
  59444. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59445. this._checkUniform(name);
  59446. this._colors3[name] = value;
  59447. return this;
  59448. };
  59449. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59450. this._checkUniform(name);
  59451. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59452. color.toArray(arr, arr.length);
  59453. return arr;
  59454. }, []);
  59455. return this;
  59456. };
  59457. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59458. this._checkUniform(name);
  59459. this._colors4[name] = value;
  59460. return this;
  59461. };
  59462. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59463. this._checkUniform(name);
  59464. this._vectors2[name] = value;
  59465. return this;
  59466. };
  59467. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59468. this._checkUniform(name);
  59469. this._vectors3[name] = value;
  59470. return this;
  59471. };
  59472. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59473. this._checkUniform(name);
  59474. this._vectors4[name] = value;
  59475. return this;
  59476. };
  59477. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59478. this._checkUniform(name);
  59479. this._matrices[name] = value;
  59480. return this;
  59481. };
  59482. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59483. this._checkUniform(name);
  59484. this._matrices3x3[name] = value;
  59485. return this;
  59486. };
  59487. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59488. this._checkUniform(name);
  59489. this._matrices2x2[name] = value;
  59490. return this;
  59491. };
  59492. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59493. this._checkUniform(name);
  59494. this._vectors2Arrays[name] = value;
  59495. return this;
  59496. };
  59497. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59498. this._checkUniform(name);
  59499. this._vectors3Arrays[name] = value;
  59500. return this;
  59501. };
  59502. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59503. if (!mesh) {
  59504. return true;
  59505. }
  59506. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59507. return false;
  59508. }
  59509. return false;
  59510. };
  59511. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59512. var scene = this.getScene();
  59513. var engine = scene.getEngine();
  59514. if (!this.checkReadyOnEveryCall) {
  59515. if (this._renderId === scene.getRenderId()) {
  59516. if (this._checkCache(scene, mesh, useInstances)) {
  59517. return true;
  59518. }
  59519. }
  59520. }
  59521. // Instances
  59522. var defines = [];
  59523. var attribs = [];
  59524. var fallbacks = new BABYLON.EffectFallbacks();
  59525. if (useInstances) {
  59526. defines.push("#define INSTANCES");
  59527. }
  59528. for (var index = 0; index < this._options.defines.length; index++) {
  59529. defines.push(this._options.defines[index]);
  59530. }
  59531. for (var index = 0; index < this._options.attributes.length; index++) {
  59532. attribs.push(this._options.attributes[index]);
  59533. }
  59534. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59535. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59536. defines.push("#define VERTEXCOLOR");
  59537. }
  59538. // Bones
  59539. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59542. if (mesh.numBoneInfluencers > 4) {
  59543. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59544. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59545. }
  59546. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59547. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59548. fallbacks.addCPUSkinningFallback(0, mesh);
  59549. if (this._options.uniforms.indexOf("mBones") === -1) {
  59550. this._options.uniforms.push("mBones");
  59551. }
  59552. }
  59553. else {
  59554. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59555. }
  59556. // Textures
  59557. for (var name in this._textures) {
  59558. if (!this._textures[name].isReady()) {
  59559. return false;
  59560. }
  59561. }
  59562. // Alpha test
  59563. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59564. defines.push("#define ALPHATEST");
  59565. }
  59566. var previousEffect = this._effect;
  59567. var join = defines.join("\n");
  59568. this._effect = engine.createEffect(this._shaderPath, {
  59569. attributes: attribs,
  59570. uniformsNames: this._options.uniforms,
  59571. uniformBuffersNames: this._options.uniformBuffers,
  59572. samplers: this._options.samplers,
  59573. defines: join,
  59574. fallbacks: fallbacks,
  59575. onCompiled: this.onCompiled,
  59576. onError: this.onError
  59577. }, engine);
  59578. if (!this._effect.isReady()) {
  59579. return false;
  59580. }
  59581. if (previousEffect !== this._effect) {
  59582. scene.resetCachedMaterial();
  59583. }
  59584. this._renderId = scene.getRenderId();
  59585. return true;
  59586. };
  59587. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59588. var scene = this.getScene();
  59589. if (!this._effect) {
  59590. return;
  59591. }
  59592. if (this._options.uniforms.indexOf("world") !== -1) {
  59593. this._effect.setMatrix("world", world);
  59594. }
  59595. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59596. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59597. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59598. }
  59599. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59600. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59601. }
  59602. };
  59603. ShaderMaterial.prototype.bind = function (world, mesh) {
  59604. // Std values
  59605. this.bindOnlyWorldMatrix(world);
  59606. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59607. if (this._options.uniforms.indexOf("view") !== -1) {
  59608. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59609. }
  59610. if (this._options.uniforms.indexOf("projection") !== -1) {
  59611. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59612. }
  59613. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59614. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59615. }
  59616. // Bones
  59617. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59618. var name;
  59619. // Texture
  59620. for (name in this._textures) {
  59621. this._effect.setTexture(name, this._textures[name]);
  59622. }
  59623. // Texture arrays
  59624. for (name in this._textureArrays) {
  59625. this._effect.setTextureArray(name, this._textureArrays[name]);
  59626. }
  59627. // Int
  59628. for (name in this._ints) {
  59629. this._effect.setInt(name, this._ints[name]);
  59630. }
  59631. // Float
  59632. for (name in this._floats) {
  59633. this._effect.setFloat(name, this._floats[name]);
  59634. }
  59635. // Floats
  59636. for (name in this._floatsArrays) {
  59637. this._effect.setArray(name, this._floatsArrays[name]);
  59638. }
  59639. // Color3
  59640. for (name in this._colors3) {
  59641. this._effect.setColor3(name, this._colors3[name]);
  59642. }
  59643. for (name in this._colors3Arrays) {
  59644. this._effect.setArray3(name, this._colors3Arrays[name]);
  59645. }
  59646. // Color4
  59647. for (name in this._colors4) {
  59648. var color = this._colors4[name];
  59649. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59650. }
  59651. // Vector2
  59652. for (name in this._vectors2) {
  59653. this._effect.setVector2(name, this._vectors2[name]);
  59654. }
  59655. // Vector3
  59656. for (name in this._vectors3) {
  59657. this._effect.setVector3(name, this._vectors3[name]);
  59658. }
  59659. // Vector4
  59660. for (name in this._vectors4) {
  59661. this._effect.setVector4(name, this._vectors4[name]);
  59662. }
  59663. // Matrix
  59664. for (name in this._matrices) {
  59665. this._effect.setMatrix(name, this._matrices[name]);
  59666. }
  59667. // Matrix 3x3
  59668. for (name in this._matrices3x3) {
  59669. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59670. }
  59671. // Matrix 2x2
  59672. for (name in this._matrices2x2) {
  59673. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59674. }
  59675. // Vector2Array
  59676. for (name in this._vectors2Arrays) {
  59677. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59678. }
  59679. // Vector3Array
  59680. for (name in this._vectors3Arrays) {
  59681. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59682. }
  59683. }
  59684. this._afterBind(mesh);
  59685. };
  59686. ShaderMaterial.prototype.getActiveTextures = function () {
  59687. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59688. for (var name in this._textures) {
  59689. activeTextures.push(this._textures[name]);
  59690. }
  59691. for (var name in this._textureArrays) {
  59692. var array = this._textureArrays[name];
  59693. for (var index = 0; index < array.length; index++) {
  59694. activeTextures.push(array[index]);
  59695. }
  59696. }
  59697. return activeTextures;
  59698. };
  59699. ShaderMaterial.prototype.hasTexture = function (texture) {
  59700. if (_super.prototype.hasTexture.call(this, texture)) {
  59701. return true;
  59702. }
  59703. for (var name in this._textures) {
  59704. if (this._textures[name] === texture) {
  59705. return true;
  59706. }
  59707. }
  59708. for (var name in this._textureArrays) {
  59709. var array = this._textureArrays[name];
  59710. for (var index = 0; index < array.length; index++) {
  59711. if (array[index] === texture) {
  59712. return true;
  59713. }
  59714. }
  59715. }
  59716. return false;
  59717. };
  59718. ShaderMaterial.prototype.clone = function (name) {
  59719. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59720. return newShaderMaterial;
  59721. };
  59722. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59723. if (forceDisposeTextures) {
  59724. var name;
  59725. for (name in this._textures) {
  59726. this._textures[name].dispose();
  59727. }
  59728. for (name in this._textureArrays) {
  59729. var array = this._textureArrays[name];
  59730. for (var index = 0; index < array.length; index++) {
  59731. array[index].dispose();
  59732. }
  59733. }
  59734. }
  59735. this._textures = {};
  59736. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59737. };
  59738. ShaderMaterial.prototype.serialize = function () {
  59739. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59740. serializationObject.customType = "BABYLON.ShaderMaterial";
  59741. serializationObject.options = this._options;
  59742. serializationObject.shaderPath = this._shaderPath;
  59743. var name;
  59744. // Texture
  59745. serializationObject.textures = {};
  59746. for (name in this._textures) {
  59747. serializationObject.textures[name] = this._textures[name].serialize();
  59748. }
  59749. // Texture arrays
  59750. serializationObject.textureArrays = {};
  59751. for (name in this._textureArrays) {
  59752. serializationObject.textureArrays[name] = [];
  59753. var array = this._textureArrays[name];
  59754. for (var index = 0; index < array.length; index++) {
  59755. serializationObject.textureArrays[name].push(array[index].serialize());
  59756. }
  59757. }
  59758. // Float
  59759. serializationObject.floats = {};
  59760. for (name in this._floats) {
  59761. serializationObject.floats[name] = this._floats[name];
  59762. }
  59763. // Float s
  59764. serializationObject.FloatArrays = {};
  59765. for (name in this._floatsArrays) {
  59766. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59767. }
  59768. // Color3
  59769. serializationObject.colors3 = {};
  59770. for (name in this._colors3) {
  59771. serializationObject.colors3[name] = this._colors3[name].asArray();
  59772. }
  59773. // Color3 array
  59774. serializationObject.colors3Arrays = {};
  59775. for (name in this._colors3Arrays) {
  59776. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59777. }
  59778. // Color4
  59779. serializationObject.colors4 = {};
  59780. for (name in this._colors4) {
  59781. serializationObject.colors4[name] = this._colors4[name].asArray();
  59782. }
  59783. // Vector2
  59784. serializationObject.vectors2 = {};
  59785. for (name in this._vectors2) {
  59786. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59787. }
  59788. // Vector3
  59789. serializationObject.vectors3 = {};
  59790. for (name in this._vectors3) {
  59791. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59792. }
  59793. // Vector4
  59794. serializationObject.vectors4 = {};
  59795. for (name in this._vectors4) {
  59796. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59797. }
  59798. // Matrix
  59799. serializationObject.matrices = {};
  59800. for (name in this._matrices) {
  59801. serializationObject.matrices[name] = this._matrices[name].asArray();
  59802. }
  59803. // Matrix 3x3
  59804. serializationObject.matrices3x3 = {};
  59805. for (name in this._matrices3x3) {
  59806. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59807. }
  59808. // Matrix 2x2
  59809. serializationObject.matrices2x2 = {};
  59810. for (name in this._matrices2x2) {
  59811. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59812. }
  59813. // Vector2Array
  59814. serializationObject.vectors2Arrays = {};
  59815. for (name in this._vectors2Arrays) {
  59816. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59817. }
  59818. // Vector3Array
  59819. serializationObject.vectors3Arrays = {};
  59820. for (name in this._vectors3Arrays) {
  59821. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59822. }
  59823. return serializationObject;
  59824. };
  59825. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59826. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59827. var name;
  59828. // Texture
  59829. for (name in source.textures) {
  59830. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59831. }
  59832. // Texture arrays
  59833. for (name in source.textureArrays) {
  59834. var array = source.textureArrays[name];
  59835. var textureArray = new Array();
  59836. for (var index = 0; index < array.length; index++) {
  59837. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59838. }
  59839. material.setTextureArray(name, textureArray);
  59840. }
  59841. // Float
  59842. for (name in source.floats) {
  59843. material.setFloat(name, source.floats[name]);
  59844. }
  59845. // Float s
  59846. for (name in source.floatsArrays) {
  59847. material.setFloats(name, source.floatsArrays[name]);
  59848. }
  59849. // Color3
  59850. for (name in source.colors3) {
  59851. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59852. }
  59853. // Color3 arrays
  59854. for (name in source.colors3Arrays) {
  59855. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59856. if (i % 3 === 0) {
  59857. arr.push([num]);
  59858. }
  59859. else {
  59860. arr[arr.length - 1].push(num);
  59861. }
  59862. return arr;
  59863. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59864. material.setColor3Array(name, colors);
  59865. }
  59866. // Color4
  59867. for (name in source.colors4) {
  59868. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59869. }
  59870. // Vector2
  59871. for (name in source.vectors2) {
  59872. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59873. }
  59874. // Vector3
  59875. for (name in source.vectors3) {
  59876. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59877. }
  59878. // Vector4
  59879. for (name in source.vectors4) {
  59880. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59881. }
  59882. // Matrix
  59883. for (name in source.matrices) {
  59884. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59885. }
  59886. // Matrix 3x3
  59887. for (name in source.matrices3x3) {
  59888. material.setMatrix3x3(name, source.matrices3x3[name]);
  59889. }
  59890. // Matrix 2x2
  59891. for (name in source.matrices2x2) {
  59892. material.setMatrix2x2(name, source.matrices2x2[name]);
  59893. }
  59894. // Vector2Array
  59895. for (name in source.vectors2Arrays) {
  59896. material.setArray2(name, source.vectors2Arrays[name]);
  59897. }
  59898. // Vector3Array
  59899. for (name in source.vectors3Arrays) {
  59900. material.setArray3(name, source.vectors3Arrays[name]);
  59901. }
  59902. return material;
  59903. };
  59904. return ShaderMaterial;
  59905. }(BABYLON.Material));
  59906. BABYLON.ShaderMaterial = ShaderMaterial;
  59907. })(BABYLON || (BABYLON = {}));
  59908. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59909. var BABYLON;
  59910. (function (BABYLON) {
  59911. var GroundMesh = /** @class */ (function (_super) {
  59912. __extends(GroundMesh, _super);
  59913. function GroundMesh(name, scene) {
  59914. var _this = _super.call(this, name, scene) || this;
  59915. _this.generateOctree = false;
  59916. return _this;
  59917. }
  59918. GroundMesh.prototype.getClassName = function () {
  59919. return "GroundMesh";
  59920. };
  59921. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59922. get: function () {
  59923. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59924. },
  59925. enumerable: true,
  59926. configurable: true
  59927. });
  59928. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59929. get: function () {
  59930. return this._subdivisionsX;
  59931. },
  59932. enumerable: true,
  59933. configurable: true
  59934. });
  59935. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59936. get: function () {
  59937. return this._subdivisionsY;
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59943. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59944. this._subdivisionsX = chunksCount;
  59945. this._subdivisionsY = chunksCount;
  59946. this.subdivide(chunksCount);
  59947. // Call the octree system optimization if it is defined.
  59948. var thisAsAny = this;
  59949. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59950. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59951. }
  59952. };
  59953. /**
  59954. * Returns a height (y) value in the Worl system :
  59955. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59956. * Returns the ground y position if (x, z) are outside the ground surface.
  59957. */
  59958. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59959. var world = this.getWorldMatrix();
  59960. var invMat = BABYLON.Tmp.Matrix[5];
  59961. world.invertToRef(invMat);
  59962. var tmpVect = BABYLON.Tmp.Vector3[8];
  59963. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59964. x = tmpVect.x;
  59965. z = tmpVect.z;
  59966. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59967. return this.position.y;
  59968. }
  59969. if (!this._heightQuads || this._heightQuads.length == 0) {
  59970. this._initHeightQuads();
  59971. this._computeHeightQuads();
  59972. }
  59973. var facet = this._getFacetAt(x, z);
  59974. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59975. // return y in the World system
  59976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59977. return tmpVect.y;
  59978. };
  59979. /**
  59980. * Returns a normalized vector (Vector3) orthogonal to the ground
  59981. * at the ground coordinates (x, z) expressed in the World system.
  59982. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59983. */
  59984. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59985. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59986. this.getNormalAtCoordinatesToRef(x, z, normal);
  59987. return normal;
  59988. };
  59989. /**
  59990. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59991. * at the ground coordinates (x, z) expressed in the World system.
  59992. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59993. * Returns the GroundMesh.
  59994. */
  59995. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59996. var world = this.getWorldMatrix();
  59997. var tmpMat = BABYLON.Tmp.Matrix[5];
  59998. world.invertToRef(tmpMat);
  59999. var tmpVect = BABYLON.Tmp.Vector3[8];
  60000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60001. x = tmpVect.x;
  60002. z = tmpVect.z;
  60003. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60004. return this;
  60005. }
  60006. if (!this._heightQuads || this._heightQuads.length == 0) {
  60007. this._initHeightQuads();
  60008. this._computeHeightQuads();
  60009. }
  60010. var facet = this._getFacetAt(x, z);
  60011. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60012. return this;
  60013. };
  60014. /**
  60015. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60016. * if the ground has been updated.
  60017. * This can be used in the render loop.
  60018. * Returns the GroundMesh.
  60019. */
  60020. GroundMesh.prototype.updateCoordinateHeights = function () {
  60021. if (!this._heightQuads || this._heightQuads.length == 0) {
  60022. this._initHeightQuads();
  60023. }
  60024. this._computeHeightQuads();
  60025. return this;
  60026. };
  60027. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60028. GroundMesh.prototype._getFacetAt = function (x, z) {
  60029. // retrieve col and row from x, z coordinates in the ground local system
  60030. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60031. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60032. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60033. var facet;
  60034. if (z < quad.slope.x * x + quad.slope.y) {
  60035. facet = quad.facet1;
  60036. }
  60037. else {
  60038. facet = quad.facet2;
  60039. }
  60040. return facet;
  60041. };
  60042. // Creates and populates the heightMap array with "facet" elements :
  60043. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60044. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60045. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60046. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60047. // Returns the GroundMesh.
  60048. GroundMesh.prototype._initHeightQuads = function () {
  60049. var subdivisionsX = this._subdivisionsX;
  60050. var subdivisionsY = this._subdivisionsY;
  60051. this._heightQuads = new Array();
  60052. for (var row = 0; row < subdivisionsY; row++) {
  60053. for (var col = 0; col < subdivisionsX; col++) {
  60054. 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) };
  60055. this._heightQuads[row * subdivisionsX + col] = quad;
  60056. }
  60057. }
  60058. return this;
  60059. };
  60060. // Compute each quad element values and update the the heightMap array :
  60061. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60062. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60063. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60064. // Returns the GroundMesh.
  60065. GroundMesh.prototype._computeHeightQuads = function () {
  60066. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60067. if (!positions) {
  60068. return this;
  60069. }
  60070. var v1 = BABYLON.Tmp.Vector3[3];
  60071. var v2 = BABYLON.Tmp.Vector3[2];
  60072. var v3 = BABYLON.Tmp.Vector3[1];
  60073. var v4 = BABYLON.Tmp.Vector3[0];
  60074. var v1v2 = BABYLON.Tmp.Vector3[4];
  60075. var v1v3 = BABYLON.Tmp.Vector3[5];
  60076. var v1v4 = BABYLON.Tmp.Vector3[6];
  60077. var norm1 = BABYLON.Tmp.Vector3[7];
  60078. var norm2 = BABYLON.Tmp.Vector3[8];
  60079. var i = 0;
  60080. var j = 0;
  60081. var k = 0;
  60082. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60083. var h = 0;
  60084. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60085. var d2 = 0;
  60086. var subdivisionsX = this._subdivisionsX;
  60087. var subdivisionsY = this._subdivisionsY;
  60088. for (var row = 0; row < subdivisionsY; row++) {
  60089. for (var col = 0; col < subdivisionsX; col++) {
  60090. i = col * 3;
  60091. j = row * (subdivisionsX + 1) * 3;
  60092. k = (row + 1) * (subdivisionsX + 1) * 3;
  60093. v1.x = positions[j + i];
  60094. v1.y = positions[j + i + 1];
  60095. v1.z = positions[j + i + 2];
  60096. v2.x = positions[j + i + 3];
  60097. v2.y = positions[j + i + 4];
  60098. v2.z = positions[j + i + 5];
  60099. v3.x = positions[k + i];
  60100. v3.y = positions[k + i + 1];
  60101. v3.z = positions[k + i + 2];
  60102. v4.x = positions[k + i + 3];
  60103. v4.y = positions[k + i + 4];
  60104. v4.z = positions[k + i + 5];
  60105. // 2D slope V1V4
  60106. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60107. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60108. // facet equations :
  60109. // we compute each facet normal vector
  60110. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60111. // we compute the value d by applying the equation to v1 which belongs to the plane
  60112. // then we store the facet equation in a Vector4
  60113. v2.subtractToRef(v1, v1v2);
  60114. v3.subtractToRef(v1, v1v3);
  60115. v4.subtractToRef(v1, v1v4);
  60116. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60117. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60118. norm1.normalize();
  60119. norm2.normalize();
  60120. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60121. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60122. var quad = this._heightQuads[row * subdivisionsX + col];
  60123. quad.slope.copyFromFloats(cd, h);
  60124. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60125. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60126. }
  60127. }
  60128. return this;
  60129. };
  60130. GroundMesh.prototype.serialize = function (serializationObject) {
  60131. _super.prototype.serialize.call(this, serializationObject);
  60132. serializationObject.subdivisionsX = this._subdivisionsX;
  60133. serializationObject.subdivisionsY = this._subdivisionsY;
  60134. serializationObject.minX = this._minX;
  60135. serializationObject.maxX = this._maxX;
  60136. serializationObject.minZ = this._minZ;
  60137. serializationObject.maxZ = this._maxZ;
  60138. serializationObject.width = this._width;
  60139. serializationObject.height = this._height;
  60140. };
  60141. GroundMesh.Parse = function (parsedMesh, scene) {
  60142. var result = new GroundMesh(parsedMesh.name, scene);
  60143. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60144. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60145. result._minX = parsedMesh.minX;
  60146. result._maxX = parsedMesh.maxX;
  60147. result._minZ = parsedMesh.minZ;
  60148. result._maxZ = parsedMesh.maxZ;
  60149. result._width = parsedMesh.width;
  60150. result._height = parsedMesh.height;
  60151. return result;
  60152. };
  60153. return GroundMesh;
  60154. }(BABYLON.Mesh));
  60155. BABYLON.GroundMesh = GroundMesh;
  60156. })(BABYLON || (BABYLON = {}));
  60157. //# sourceMappingURL=babylon.groundMesh.js.map
  60158. var BABYLON;
  60159. (function (BABYLON) {
  60160. /**
  60161. * Creates an instance based on a source mesh.
  60162. */
  60163. var InstancedMesh = /** @class */ (function (_super) {
  60164. __extends(InstancedMesh, _super);
  60165. function InstancedMesh(name, source) {
  60166. var _this = _super.call(this, name, source.getScene()) || this;
  60167. source.instances.push(_this);
  60168. _this._sourceMesh = source;
  60169. _this.position.copyFrom(source.position);
  60170. _this.rotation.copyFrom(source.rotation);
  60171. _this.scaling.copyFrom(source.scaling);
  60172. if (source.rotationQuaternion) {
  60173. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60174. }
  60175. _this.infiniteDistance = source.infiniteDistance;
  60176. _this.setPivotMatrix(source.getPivotMatrix());
  60177. _this.refreshBoundingInfo();
  60178. _this._syncSubMeshes();
  60179. return _this;
  60180. }
  60181. /**
  60182. * Returns the string "InstancedMesh".
  60183. */
  60184. InstancedMesh.prototype.getClassName = function () {
  60185. return "InstancedMesh";
  60186. };
  60187. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60188. // Methods
  60189. get: function () {
  60190. return this._sourceMesh.receiveShadows;
  60191. },
  60192. enumerable: true,
  60193. configurable: true
  60194. });
  60195. Object.defineProperty(InstancedMesh.prototype, "material", {
  60196. get: function () {
  60197. return this._sourceMesh.material;
  60198. },
  60199. enumerable: true,
  60200. configurable: true
  60201. });
  60202. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60203. get: function () {
  60204. return this._sourceMesh.visibility;
  60205. },
  60206. enumerable: true,
  60207. configurable: true
  60208. });
  60209. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60210. get: function () {
  60211. return this._sourceMesh.skeleton;
  60212. },
  60213. enumerable: true,
  60214. configurable: true
  60215. });
  60216. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60217. get: function () {
  60218. return this._sourceMesh.renderingGroupId;
  60219. },
  60220. set: function (value) {
  60221. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60222. return;
  60223. }
  60224. //no-op with warning
  60225. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60226. },
  60227. enumerable: true,
  60228. configurable: true
  60229. });
  60230. /**
  60231. * Returns the total number of vertices (integer).
  60232. */
  60233. InstancedMesh.prototype.getTotalVertices = function () {
  60234. return this._sourceMesh.getTotalVertices();
  60235. };
  60236. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60237. get: function () {
  60238. return this._sourceMesh;
  60239. },
  60240. enumerable: true,
  60241. configurable: true
  60242. });
  60243. /**
  60244. * Is this node ready to be used/rendered
  60245. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60246. * @return {boolean} is it ready
  60247. */
  60248. InstancedMesh.prototype.isReady = function (completeCheck) {
  60249. if (completeCheck === void 0) { completeCheck = false; }
  60250. return this._sourceMesh.isReady(completeCheck, true);
  60251. };
  60252. /**
  60253. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60254. */
  60255. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60256. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60257. };
  60258. /**
  60259. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60260. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60261. * The `data` are either a numeric array either a Float32Array.
  60262. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60263. * 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).
  60264. * Note that a new underlying VertexBuffer object is created each call.
  60265. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60266. *
  60267. * Possible `kind` values :
  60268. * - BABYLON.VertexBuffer.PositionKind
  60269. * - BABYLON.VertexBuffer.UVKind
  60270. * - BABYLON.VertexBuffer.UV2Kind
  60271. * - BABYLON.VertexBuffer.UV3Kind
  60272. * - BABYLON.VertexBuffer.UV4Kind
  60273. * - BABYLON.VertexBuffer.UV5Kind
  60274. * - BABYLON.VertexBuffer.UV6Kind
  60275. * - BABYLON.VertexBuffer.ColorKind
  60276. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60277. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60278. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60279. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60280. *
  60281. * Returns the Mesh.
  60282. */
  60283. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60284. if (this.sourceMesh) {
  60285. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60286. }
  60287. return this.sourceMesh;
  60288. };
  60289. /**
  60290. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60291. * If the mesh has no geometry, it is simply returned as it is.
  60292. * The `data` are either a numeric array either a Float32Array.
  60293. * No new underlying VertexBuffer object is created.
  60294. * 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.
  60295. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60296. *
  60297. * Possible `kind` values :
  60298. * - BABYLON.VertexBuffer.PositionKind
  60299. * - BABYLON.VertexBuffer.UVKind
  60300. * - BABYLON.VertexBuffer.UV2Kind
  60301. * - BABYLON.VertexBuffer.UV3Kind
  60302. * - BABYLON.VertexBuffer.UV4Kind
  60303. * - BABYLON.VertexBuffer.UV5Kind
  60304. * - BABYLON.VertexBuffer.UV6Kind
  60305. * - BABYLON.VertexBuffer.ColorKind
  60306. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60307. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60308. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60309. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60310. *
  60311. * Returns the Mesh.
  60312. */
  60313. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60314. if (this.sourceMesh) {
  60315. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60316. }
  60317. return this.sourceMesh;
  60318. };
  60319. /**
  60320. * Sets the mesh indices.
  60321. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60322. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60323. * This method creates a new index buffer each call.
  60324. * Returns the Mesh.
  60325. */
  60326. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60327. if (totalVertices === void 0) { totalVertices = null; }
  60328. if (this.sourceMesh) {
  60329. this.sourceMesh.setIndices(indices, totalVertices);
  60330. }
  60331. return this.sourceMesh;
  60332. };
  60333. /**
  60334. * Boolean : True if the mesh owns the requested kind of data.
  60335. */
  60336. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60337. return this._sourceMesh.isVerticesDataPresent(kind);
  60338. };
  60339. /**
  60340. * Returns an array of indices (IndicesArray).
  60341. */
  60342. InstancedMesh.prototype.getIndices = function () {
  60343. return this._sourceMesh.getIndices();
  60344. };
  60345. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60346. get: function () {
  60347. return this._sourceMesh._positions;
  60348. },
  60349. enumerable: true,
  60350. configurable: true
  60351. });
  60352. /**
  60353. * Sets a new updated BoundingInfo to the mesh.
  60354. * Returns the mesh.
  60355. */
  60356. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60357. var meshBB = this._sourceMesh.getBoundingInfo();
  60358. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60359. this._updateBoundingInfo();
  60360. return this;
  60361. };
  60362. /** @hidden */
  60363. InstancedMesh.prototype._preActivate = function () {
  60364. if (this._currentLOD) {
  60365. this._currentLOD._preActivate();
  60366. }
  60367. return this;
  60368. };
  60369. /** @hidden */
  60370. InstancedMesh.prototype._activate = function (renderId) {
  60371. if (this._currentLOD) {
  60372. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60373. }
  60374. return this;
  60375. };
  60376. /**
  60377. * Returns the current associated LOD AbstractMesh.
  60378. */
  60379. InstancedMesh.prototype.getLOD = function (camera) {
  60380. if (!camera) {
  60381. return this;
  60382. }
  60383. var boundingInfo = this.getBoundingInfo();
  60384. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60385. if (this._currentLOD === this.sourceMesh) {
  60386. return this;
  60387. }
  60388. return this._currentLOD;
  60389. };
  60390. /** @hidden */
  60391. InstancedMesh.prototype._syncSubMeshes = function () {
  60392. this.releaseSubMeshes();
  60393. if (this._sourceMesh.subMeshes) {
  60394. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60395. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60396. }
  60397. }
  60398. return this;
  60399. };
  60400. /** @hidden */
  60401. InstancedMesh.prototype._generatePointsArray = function () {
  60402. return this._sourceMesh._generatePointsArray();
  60403. };
  60404. /**
  60405. * Creates a new InstancedMesh from the current mesh.
  60406. * - name (string) : the cloned mesh name
  60407. * - newParent (optional Node) : the optional Node to parent the clone to.
  60408. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60409. *
  60410. * Returns the clone.
  60411. */
  60412. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60413. var result = this._sourceMesh.createInstance(name);
  60414. // Deep copy
  60415. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60416. // Bounding info
  60417. this.refreshBoundingInfo();
  60418. // Parent
  60419. if (newParent) {
  60420. result.parent = newParent;
  60421. }
  60422. if (!doNotCloneChildren) {
  60423. // Children
  60424. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60425. var mesh = this.getScene().meshes[index];
  60426. if (mesh.parent === this) {
  60427. mesh.clone(mesh.name, result);
  60428. }
  60429. }
  60430. }
  60431. result.computeWorldMatrix(true);
  60432. return result;
  60433. };
  60434. /**
  60435. * Disposes the InstancedMesh.
  60436. * Returns nothing.
  60437. */
  60438. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60439. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60440. // Remove from mesh
  60441. var index = this._sourceMesh.instances.indexOf(this);
  60442. this._sourceMesh.instances.splice(index, 1);
  60443. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60444. };
  60445. return InstancedMesh;
  60446. }(BABYLON.AbstractMesh));
  60447. BABYLON.InstancedMesh = InstancedMesh;
  60448. })(BABYLON || (BABYLON = {}));
  60449. //# sourceMappingURL=babylon.instancedMesh.js.map
  60450. var BABYLON;
  60451. (function (BABYLON) {
  60452. var LinesMesh = /** @class */ (function (_super) {
  60453. __extends(LinesMesh, _super);
  60454. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60455. if (scene === void 0) { scene = null; }
  60456. if (parent === void 0) { parent = null; }
  60457. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60458. _this.useVertexColor = useVertexColor;
  60459. _this.useVertexAlpha = useVertexAlpha;
  60460. _this.color = new BABYLON.Color3(1, 1, 1);
  60461. _this.alpha = 1;
  60462. if (source) {
  60463. _this.color = source.color.clone();
  60464. _this.alpha = source.alpha;
  60465. _this.useVertexColor = source.useVertexColor;
  60466. _this.useVertexAlpha = source.useVertexAlpha;
  60467. }
  60468. _this._intersectionThreshold = 0.1;
  60469. var defines = [];
  60470. var options = {
  60471. attributes: [BABYLON.VertexBuffer.PositionKind],
  60472. uniforms: ["world", "viewProjection"],
  60473. needAlphaBlending: true,
  60474. defines: defines
  60475. };
  60476. if (useVertexAlpha === false) {
  60477. options.needAlphaBlending = false;
  60478. }
  60479. if (!useVertexColor) {
  60480. options.uniforms.push("color");
  60481. }
  60482. else {
  60483. options.defines.push("#define VERTEXCOLOR");
  60484. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60485. }
  60486. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60487. return _this;
  60488. }
  60489. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60490. /**
  60491. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60492. * This margin is expressed in world space coordinates, so its value may vary.
  60493. * Default value is 0.1
  60494. * @returns the intersection Threshold value.
  60495. */
  60496. get: function () {
  60497. return this._intersectionThreshold;
  60498. },
  60499. /**
  60500. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60501. * This margin is expressed in world space coordinates, so its value may vary.
  60502. * @param value the new threshold to apply
  60503. */
  60504. set: function (value) {
  60505. if (this._intersectionThreshold === value) {
  60506. return;
  60507. }
  60508. this._intersectionThreshold = value;
  60509. if (this.geometry) {
  60510. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60511. }
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. /**
  60517. * Returns the string "LineMesh"
  60518. */
  60519. LinesMesh.prototype.getClassName = function () {
  60520. return "LinesMesh";
  60521. };
  60522. Object.defineProperty(LinesMesh.prototype, "material", {
  60523. /**
  60524. * @hidden
  60525. */
  60526. get: function () {
  60527. return this._colorShader;
  60528. },
  60529. /**
  60530. * @hidden
  60531. */
  60532. set: function (value) {
  60533. // Do nothing
  60534. },
  60535. enumerable: true,
  60536. configurable: true
  60537. });
  60538. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60539. /**
  60540. * @hidden
  60541. */
  60542. get: function () {
  60543. return false;
  60544. },
  60545. enumerable: true,
  60546. configurable: true
  60547. });
  60548. LinesMesh.prototype.createInstance = function (name) {
  60549. throw new Error("LinesMeshes do not support createInstance.");
  60550. };
  60551. /** @hidden */
  60552. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60553. if (!this._geometry) {
  60554. return this;
  60555. }
  60556. // VBOs
  60557. this._geometry._bind(this._colorShader.getEffect());
  60558. // Color
  60559. if (!this.useVertexColor) {
  60560. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60561. }
  60562. return this;
  60563. };
  60564. /** @hidden */
  60565. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60566. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60567. return this;
  60568. }
  60569. var engine = this.getScene().getEngine();
  60570. // Draw order
  60571. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60572. return this;
  60573. };
  60574. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60575. this._colorShader.dispose();
  60576. _super.prototype.dispose.call(this, doNotRecurse);
  60577. };
  60578. /**
  60579. * Returns a new LineMesh object cloned from the current one.
  60580. */
  60581. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60582. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60583. };
  60584. return LinesMesh;
  60585. }(BABYLON.Mesh));
  60586. BABYLON.LinesMesh = LinesMesh;
  60587. })(BABYLON || (BABYLON = {}));
  60588. //# sourceMappingURL=babylon.linesMesh.js.map
  60589. var BABYLON;
  60590. (function (BABYLON) {
  60591. /**
  60592. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60593. * The underlying implementation relies on an associative array to ensure the best performances.
  60594. * The value can be anything including 'null' but except 'undefined'
  60595. */
  60596. var StringDictionary = /** @class */ (function () {
  60597. function StringDictionary() {
  60598. this._count = 0;
  60599. this._data = {};
  60600. }
  60601. /**
  60602. * This will clear this dictionary and copy the content from the 'source' one.
  60603. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60604. * @param source the dictionary to take the content from and copy to this dictionary
  60605. */
  60606. StringDictionary.prototype.copyFrom = function (source) {
  60607. var _this = this;
  60608. this.clear();
  60609. source.forEach(function (t, v) { return _this.add(t, v); });
  60610. };
  60611. /**
  60612. * Get a value based from its key
  60613. * @param key the given key to get the matching value from
  60614. * @return the value if found, otherwise undefined is returned
  60615. */
  60616. StringDictionary.prototype.get = function (key) {
  60617. var val = this._data[key];
  60618. if (val !== undefined) {
  60619. return val;
  60620. }
  60621. return undefined;
  60622. };
  60623. /**
  60624. * Get a value from its key or add it if it doesn't exist.
  60625. * This method will ensure you that a given key/data will be present in the dictionary.
  60626. * @param key the given key to get the matching value from
  60627. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60628. * The factory will only be invoked if there's no data for the given key.
  60629. * @return the value corresponding to the key.
  60630. */
  60631. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60632. var val = this.get(key);
  60633. if (val !== undefined) {
  60634. return val;
  60635. }
  60636. val = factory(key);
  60637. if (val) {
  60638. this.add(key, val);
  60639. }
  60640. return val;
  60641. };
  60642. /**
  60643. * Get a value from its key if present in the dictionary otherwise add it
  60644. * @param key the key to get the value from
  60645. * @param val if there's no such key/value pair in the dictionary add it with this value
  60646. * @return the value corresponding to the key
  60647. */
  60648. StringDictionary.prototype.getOrAdd = function (key, val) {
  60649. var curVal = this.get(key);
  60650. if (curVal !== undefined) {
  60651. return curVal;
  60652. }
  60653. this.add(key, val);
  60654. return val;
  60655. };
  60656. /**
  60657. * Check if there's a given key in the dictionary
  60658. * @param key the key to check for
  60659. * @return true if the key is present, false otherwise
  60660. */
  60661. StringDictionary.prototype.contains = function (key) {
  60662. return this._data[key] !== undefined;
  60663. };
  60664. /**
  60665. * Add a new key and its corresponding value
  60666. * @param key the key to add
  60667. * @param value the value corresponding to the key
  60668. * @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
  60669. */
  60670. StringDictionary.prototype.add = function (key, value) {
  60671. if (this._data[key] !== undefined) {
  60672. return false;
  60673. }
  60674. this._data[key] = value;
  60675. ++this._count;
  60676. return true;
  60677. };
  60678. StringDictionary.prototype.set = function (key, value) {
  60679. if (this._data[key] === undefined) {
  60680. return false;
  60681. }
  60682. this._data[key] = value;
  60683. return true;
  60684. };
  60685. /**
  60686. * Get the element of the given key and remove it from the dictionary
  60687. * @param key
  60688. */
  60689. StringDictionary.prototype.getAndRemove = function (key) {
  60690. var val = this.get(key);
  60691. if (val !== undefined) {
  60692. delete this._data[key];
  60693. --this._count;
  60694. return val;
  60695. }
  60696. return null;
  60697. };
  60698. /**
  60699. * Remove a key/value from the dictionary.
  60700. * @param key the key to remove
  60701. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60702. */
  60703. StringDictionary.prototype.remove = function (key) {
  60704. if (this.contains(key)) {
  60705. delete this._data[key];
  60706. --this._count;
  60707. return true;
  60708. }
  60709. return false;
  60710. };
  60711. /**
  60712. * Clear the whole content of the dictionary
  60713. */
  60714. StringDictionary.prototype.clear = function () {
  60715. this._data = {};
  60716. this._count = 0;
  60717. };
  60718. Object.defineProperty(StringDictionary.prototype, "count", {
  60719. get: function () {
  60720. return this._count;
  60721. },
  60722. enumerable: true,
  60723. configurable: true
  60724. });
  60725. /**
  60726. * Execute a callback on each key/val of the dictionary.
  60727. * Note that you can remove any element in this dictionary in the callback implementation
  60728. * @param callback the callback to execute on a given key/value pair
  60729. */
  60730. StringDictionary.prototype.forEach = function (callback) {
  60731. for (var cur in this._data) {
  60732. var val = this._data[cur];
  60733. callback(cur, val);
  60734. }
  60735. };
  60736. /**
  60737. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60738. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60739. * Note that you can remove any element in this dictionary in the callback implementation
  60740. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60741. */
  60742. StringDictionary.prototype.first = function (callback) {
  60743. for (var cur in this._data) {
  60744. var val = this._data[cur];
  60745. var res = callback(cur, val);
  60746. if (res) {
  60747. return res;
  60748. }
  60749. }
  60750. return null;
  60751. };
  60752. return StringDictionary;
  60753. }());
  60754. BABYLON.StringDictionary = StringDictionary;
  60755. })(BABYLON || (BABYLON = {}));
  60756. //# sourceMappingURL=babylon.stringDictionary.js.map
  60757. var BABYLON;
  60758. (function (BABYLON) {
  60759. var Debug;
  60760. (function (Debug) {
  60761. /**
  60762. * Class used to render a debug view of a given skeleton
  60763. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60764. */
  60765. var SkeletonViewer = /** @class */ (function () {
  60766. /**
  60767. * Creates a new SkeletonViewer
  60768. * @param skeleton defines the skeleton to render
  60769. * @param mesh defines the mesh attached to the skeleton
  60770. * @param scene defines the hosting scene
  60771. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60772. * @param renderingGroupId defines the rendering group id to use with the viewer
  60773. */
  60774. function SkeletonViewer(
  60775. /** defines the skeleton to render */
  60776. skeleton,
  60777. /** defines the mesh attached to the skeleton */
  60778. mesh, scene,
  60779. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60780. autoUpdateBonesMatrices,
  60781. /** defines the rendering group id to use with the viewer */
  60782. renderingGroupId) {
  60783. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60784. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60785. this.skeleton = skeleton;
  60786. this.mesh = mesh;
  60787. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60788. this.renderingGroupId = renderingGroupId;
  60789. /** Gets or sets the color used to render the skeleton */
  60790. this.color = BABYLON.Color3.White();
  60791. this._debugLines = new Array();
  60792. this._isEnabled = false;
  60793. this._scene = scene;
  60794. this.update();
  60795. this._renderFunction = this.update.bind(this);
  60796. }
  60797. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60798. get: function () {
  60799. return this._isEnabled;
  60800. },
  60801. /** Gets or sets a boolean indicating if the viewer is enabled */
  60802. set: function (value) {
  60803. if (this._isEnabled === value) {
  60804. return;
  60805. }
  60806. this._isEnabled = value;
  60807. if (value) {
  60808. this._scene.registerBeforeRender(this._renderFunction);
  60809. }
  60810. else {
  60811. this._scene.unregisterBeforeRender(this._renderFunction);
  60812. }
  60813. },
  60814. enumerable: true,
  60815. configurable: true
  60816. });
  60817. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60818. if (x === void 0) { x = 0; }
  60819. if (y === void 0) { y = 0; }
  60820. if (z === void 0) { z = 0; }
  60821. var tmat = BABYLON.Tmp.Matrix[0];
  60822. var parentBone = bone.getParent();
  60823. tmat.copyFrom(bone.getLocalMatrix());
  60824. if (x !== 0 || y !== 0 || z !== 0) {
  60825. var tmat2 = BABYLON.Tmp.Matrix[1];
  60826. BABYLON.Matrix.IdentityToRef(tmat2);
  60827. tmat2.m[12] = x;
  60828. tmat2.m[13] = y;
  60829. tmat2.m[14] = z;
  60830. tmat2.multiplyToRef(tmat, tmat);
  60831. }
  60832. if (parentBone) {
  60833. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60834. }
  60835. tmat.multiplyToRef(meshMat, tmat);
  60836. position.x = tmat.m[12];
  60837. position.y = tmat.m[13];
  60838. position.z = tmat.m[14];
  60839. };
  60840. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60841. var len = bones.length;
  60842. var meshPos = this.mesh.position;
  60843. for (var i = 0; i < len; i++) {
  60844. var bone = bones[i];
  60845. var points = this._debugLines[i];
  60846. if (!points) {
  60847. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60848. this._debugLines[i] = points;
  60849. }
  60850. this._getBonePosition(points[0], bone, meshMat);
  60851. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60852. points[0].subtractInPlace(meshPos);
  60853. points[1].subtractInPlace(meshPos);
  60854. }
  60855. };
  60856. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60857. var len = bones.length;
  60858. var boneNum = 0;
  60859. var meshPos = this.mesh.position;
  60860. for (var i = len - 1; i >= 0; i--) {
  60861. var childBone = bones[i];
  60862. var parentBone = childBone.getParent();
  60863. if (!parentBone) {
  60864. continue;
  60865. }
  60866. var points = this._debugLines[boneNum];
  60867. if (!points) {
  60868. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60869. this._debugLines[boneNum] = points;
  60870. }
  60871. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60872. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60873. points[0].subtractInPlace(meshPos);
  60874. points[1].subtractInPlace(meshPos);
  60875. boneNum++;
  60876. }
  60877. };
  60878. /** Update the viewer to sync with current skeleton state */
  60879. SkeletonViewer.prototype.update = function () {
  60880. if (this.autoUpdateBonesMatrices) {
  60881. this.skeleton.computeAbsoluteTransforms();
  60882. }
  60883. if (this.skeleton.bones[0].length === undefined) {
  60884. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60885. }
  60886. else {
  60887. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60888. }
  60889. if (!this._debugMesh) {
  60890. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60891. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60892. }
  60893. else {
  60894. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60895. }
  60896. this._debugMesh.position.copyFrom(this.mesh.position);
  60897. this._debugMesh.color = this.color;
  60898. };
  60899. /** Release associated resources */
  60900. SkeletonViewer.prototype.dispose = function () {
  60901. if (this._debugMesh) {
  60902. this.isEnabled = false;
  60903. this._debugMesh.dispose();
  60904. this._debugMesh = null;
  60905. }
  60906. };
  60907. return SkeletonViewer;
  60908. }());
  60909. Debug.SkeletonViewer = SkeletonViewer;
  60910. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60911. })(BABYLON || (BABYLON = {}));
  60912. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60913. /**
  60914. * Module Debug contains the (visual) components to debug a scene correctly
  60915. */
  60916. var BABYLON;
  60917. (function (BABYLON) {
  60918. var Debug;
  60919. (function (Debug) {
  60920. /**
  60921. * The Axes viewer will show 3 axes in a specific point in space
  60922. */
  60923. var AxesViewer = /** @class */ (function () {
  60924. /**
  60925. * Creates a new AxesViewer
  60926. * @param scene defines the hosting scene
  60927. * @param scaleLines defines a number used to scale line length (1 by default)
  60928. */
  60929. function AxesViewer(scene, scaleLines) {
  60930. if (scaleLines === void 0) { scaleLines = 1; }
  60931. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60932. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60933. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60934. /**
  60935. * Gets or sets a number used to scale line length
  60936. */
  60937. this.scaleLines = 1;
  60938. this.scaleLines = scaleLines;
  60939. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60940. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60941. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60942. this._xmesh.renderingGroupId = 2;
  60943. this._ymesh.renderingGroupId = 2;
  60944. this._zmesh.renderingGroupId = 2;
  60945. this._xmesh.material.checkReadyOnlyOnce = true;
  60946. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60947. this._ymesh.material.checkReadyOnlyOnce = true;
  60948. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60949. this._zmesh.material.checkReadyOnlyOnce = true;
  60950. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60951. this.scene = scene;
  60952. }
  60953. /**
  60954. * Force the viewer to update
  60955. * @param position defines the position of the viewer
  60956. * @param xaxis defines the x axis of the viewer
  60957. * @param yaxis defines the y axis of the viewer
  60958. * @param zaxis defines the z axis of the viewer
  60959. */
  60960. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60961. var scaleLines = this.scaleLines;
  60962. if (this._xmesh) {
  60963. this._xmesh.position.copyFrom(position);
  60964. }
  60965. if (this._ymesh) {
  60966. this._ymesh.position.copyFrom(position);
  60967. }
  60968. if (this._zmesh) {
  60969. this._zmesh.position.copyFrom(position);
  60970. }
  60971. var point2 = this._xline[1];
  60972. point2.x = xaxis.x * scaleLines;
  60973. point2.y = xaxis.y * scaleLines;
  60974. point2.z = xaxis.z * scaleLines;
  60975. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60976. point2 = this._yline[1];
  60977. point2.x = yaxis.x * scaleLines;
  60978. point2.y = yaxis.y * scaleLines;
  60979. point2.z = yaxis.z * scaleLines;
  60980. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60981. point2 = this._zline[1];
  60982. point2.x = zaxis.x * scaleLines;
  60983. point2.y = zaxis.y * scaleLines;
  60984. point2.z = zaxis.z * scaleLines;
  60985. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60986. };
  60987. /** Releases resources */
  60988. AxesViewer.prototype.dispose = function () {
  60989. if (this._xmesh) {
  60990. this._xmesh.dispose();
  60991. }
  60992. if (this._ymesh) {
  60993. this._ymesh.dispose();
  60994. }
  60995. if (this._zmesh) {
  60996. this._zmesh.dispose();
  60997. }
  60998. this._xmesh = null;
  60999. this._ymesh = null;
  61000. this._zmesh = null;
  61001. this.scene = null;
  61002. };
  61003. return AxesViewer;
  61004. }());
  61005. Debug.AxesViewer = AxesViewer;
  61006. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61007. })(BABYLON || (BABYLON = {}));
  61008. //# sourceMappingURL=babylon.axesViewer.js.map
  61009. var BABYLON;
  61010. (function (BABYLON) {
  61011. var Debug;
  61012. (function (Debug) {
  61013. /**
  61014. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  61015. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  61016. */
  61017. var BoneAxesViewer = /** @class */ (function (_super) {
  61018. __extends(BoneAxesViewer, _super);
  61019. /**
  61020. * Creates a new BoneAxesViewer
  61021. * @param scene defines the hosting scene
  61022. * @param bone defines the target bone
  61023. * @param mesh defines the target mesh
  61024. * @param scaleLines defines a scaling factor for line length (1 by default)
  61025. */
  61026. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61027. if (scaleLines === void 0) { scaleLines = 1; }
  61028. var _this = _super.call(this, scene, scaleLines) || this;
  61029. /** Gets current position */
  61030. _this.pos = BABYLON.Vector3.Zero();
  61031. /** Gets direction of X axis */
  61032. _this.xaxis = BABYLON.Vector3.Zero();
  61033. /** Gets direction of Y axis */
  61034. _this.yaxis = BABYLON.Vector3.Zero();
  61035. /** Gets direction of Z axis */
  61036. _this.zaxis = BABYLON.Vector3.Zero();
  61037. _this.mesh = mesh;
  61038. _this.bone = bone;
  61039. return _this;
  61040. }
  61041. /**
  61042. * Force the viewer to update
  61043. */
  61044. BoneAxesViewer.prototype.update = function () {
  61045. if (!this.mesh || !this.bone) {
  61046. return;
  61047. }
  61048. var bone = this.bone;
  61049. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61050. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61051. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61052. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61053. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61054. };
  61055. /** Releases resources */
  61056. BoneAxesViewer.prototype.dispose = function () {
  61057. if (this.mesh) {
  61058. this.mesh = null;
  61059. this.bone = null;
  61060. _super.prototype.dispose.call(this);
  61061. }
  61062. };
  61063. return BoneAxesViewer;
  61064. }(Debug.AxesViewer));
  61065. Debug.BoneAxesViewer = BoneAxesViewer;
  61066. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61067. })(BABYLON || (BABYLON = {}));
  61068. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  61069. var BABYLON;
  61070. (function (BABYLON) {
  61071. var RayHelper = /** @class */ (function () {
  61072. function RayHelper(ray) {
  61073. this.ray = ray;
  61074. }
  61075. RayHelper.CreateAndShow = function (ray, scene, color) {
  61076. var helper = new RayHelper(ray);
  61077. helper.show(scene, color);
  61078. return helper;
  61079. };
  61080. RayHelper.prototype.show = function (scene, color) {
  61081. if (!this._renderFunction && this.ray) {
  61082. var ray = this.ray;
  61083. this._renderFunction = this._render.bind(this);
  61084. this._scene = scene;
  61085. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  61086. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  61087. if (this._renderFunction) {
  61088. this._scene.registerBeforeRender(this._renderFunction);
  61089. }
  61090. }
  61091. if (color && this._renderLine) {
  61092. this._renderLine.color.copyFrom(color);
  61093. }
  61094. };
  61095. RayHelper.prototype.hide = function () {
  61096. if (this._renderFunction && this._scene) {
  61097. this._scene.unregisterBeforeRender(this._renderFunction);
  61098. this._scene = null;
  61099. this._renderFunction = null;
  61100. if (this._renderLine) {
  61101. this._renderLine.dispose();
  61102. this._renderLine = null;
  61103. }
  61104. this._renderPoints = [];
  61105. }
  61106. };
  61107. RayHelper.prototype._render = function () {
  61108. var ray = this.ray;
  61109. if (!ray) {
  61110. return;
  61111. }
  61112. var point = this._renderPoints[1];
  61113. var len = Math.min(ray.length, 1000000);
  61114. point.copyFrom(ray.direction);
  61115. point.scaleInPlace(len);
  61116. point.addInPlace(ray.origin);
  61117. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61118. };
  61119. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61120. this._attachedToMesh = mesh;
  61121. var ray = this.ray;
  61122. if (!ray) {
  61123. return;
  61124. }
  61125. if (!ray.direction) {
  61126. ray.direction = BABYLON.Vector3.Zero();
  61127. }
  61128. if (!ray.origin) {
  61129. ray.origin = BABYLON.Vector3.Zero();
  61130. }
  61131. if (length) {
  61132. ray.length = length;
  61133. }
  61134. if (!meshSpaceOrigin) {
  61135. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61136. }
  61137. if (!meshSpaceDirection) {
  61138. // -1 so that this will work with Mesh.lookAt
  61139. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61140. }
  61141. if (!this._meshSpaceDirection) {
  61142. this._meshSpaceDirection = meshSpaceDirection.clone();
  61143. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61144. }
  61145. else {
  61146. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61147. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61148. }
  61149. if (!this._updateToMeshFunction) {
  61150. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61151. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61152. }
  61153. this._updateToMesh();
  61154. };
  61155. RayHelper.prototype.detachFromMesh = function () {
  61156. if (this._attachedToMesh) {
  61157. if (this._updateToMeshFunction) {
  61158. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61159. }
  61160. this._attachedToMesh = null;
  61161. this._updateToMeshFunction = null;
  61162. }
  61163. };
  61164. RayHelper.prototype._updateToMesh = function () {
  61165. var ray = this.ray;
  61166. if (!this._attachedToMesh || !ray) {
  61167. return;
  61168. }
  61169. if (this._attachedToMesh._isDisposed) {
  61170. this.detachFromMesh();
  61171. return;
  61172. }
  61173. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61174. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61175. };
  61176. RayHelper.prototype.dispose = function () {
  61177. this.hide();
  61178. this.detachFromMesh();
  61179. this.ray = null;
  61180. };
  61181. return RayHelper;
  61182. }());
  61183. BABYLON.RayHelper = RayHelper;
  61184. })(BABYLON || (BABYLON = {}));
  61185. //# sourceMappingURL=babylon.rayHelper.js.map
  61186. var BABYLON;
  61187. (function (BABYLON) {
  61188. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61189. get: function () {
  61190. if (!this._debugLayer) {
  61191. this._debugLayer = new DebugLayer(this);
  61192. }
  61193. return this._debugLayer;
  61194. },
  61195. enumerable: true,
  61196. configurable: true
  61197. });
  61198. var DebugLayer = /** @class */ (function () {
  61199. function DebugLayer(scene) {
  61200. var _this = this;
  61201. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61202. this.onPropertyChangedObservable = new BABYLON.Observable();
  61203. this._scene = scene;
  61204. this._scene.onDisposeObservable.add(function () {
  61205. // Debug layer
  61206. if (_this._scene._debugLayer) {
  61207. _this._scene._debugLayer.hide();
  61208. }
  61209. });
  61210. }
  61211. /** Creates the inspector window. */
  61212. DebugLayer.prototype._createInspector = function (config) {
  61213. if (config === void 0) { config = {}; }
  61214. var popup = config.popup || false;
  61215. var initialTab = config.initialTab || 0;
  61216. var parentElement = config.parentElement || null;
  61217. if (!this._inspector) {
  61218. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61219. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61220. } // else nothing to do as instance is already created
  61221. };
  61222. DebugLayer.prototype.isVisible = function () {
  61223. if (!this._inspector) {
  61224. return false;
  61225. }
  61226. return true;
  61227. };
  61228. DebugLayer.prototype.hide = function () {
  61229. if (this._inspector) {
  61230. try {
  61231. this._inspector.dispose();
  61232. }
  61233. catch (e) {
  61234. // If the inspector has been removed directly from the inspector tool
  61235. }
  61236. this.onPropertyChangedObservable.clear();
  61237. this._inspector = null;
  61238. }
  61239. };
  61240. /**
  61241. *
  61242. * Launch the debugLayer.
  61243. *
  61244. * initialTab:
  61245. * | Value | Tab Name |
  61246. * | --- | --- |
  61247. * | 0 | Scene |
  61248. * | 1 | Console |
  61249. * | 2 | Stats |
  61250. * | 3 | Textures |
  61251. * | 4 | Mesh |
  61252. * | 5 | Light |
  61253. * | 6 | Material |
  61254. * | 7 | GLTF |
  61255. * | 8 | GUI |
  61256. * | 9 | Physics |
  61257. * | 10 | Camera |
  61258. * | 11 | Audio |
  61259. *
  61260. */
  61261. DebugLayer.prototype.show = function (config) {
  61262. if (config === void 0) { config = {}; }
  61263. if (typeof this.BJSINSPECTOR == 'undefined') {
  61264. // Load inspector and add it to the DOM
  61265. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61266. }
  61267. else {
  61268. // Otherwise creates the inspector
  61269. this._createInspector(config);
  61270. }
  61271. };
  61272. /**
  61273. * Gets the active tab
  61274. * @return the index of the active tab or -1 if the inspector is hidden
  61275. */
  61276. DebugLayer.prototype.getActiveTab = function () {
  61277. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61278. };
  61279. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61280. return DebugLayer;
  61281. }());
  61282. BABYLON.DebugLayer = DebugLayer;
  61283. })(BABYLON || (BABYLON = {}));
  61284. //# sourceMappingURL=babylon.debugLayer.js.map
  61285. var BABYLON;
  61286. (function (BABYLON) {
  61287. var Debug;
  61288. (function (Debug) {
  61289. /**
  61290. * Used to show the physics impostor around the specific mesh
  61291. */
  61292. var PhysicsViewer = /** @class */ (function () {
  61293. /**
  61294. * Creates a new PhysicsViewer
  61295. * @param scene defines the hosting scene
  61296. */
  61297. function PhysicsViewer(scene) {
  61298. /** @hidden */
  61299. this._impostors = [];
  61300. /** @hidden */
  61301. this._meshes = [];
  61302. /** @hidden */
  61303. this._numMeshes = 0;
  61304. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61305. var physicEngine = this._scene.getPhysicsEngine();
  61306. if (physicEngine) {
  61307. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61308. }
  61309. }
  61310. /** @hidden */
  61311. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61312. var plugin = this._physicsEnginePlugin;
  61313. for (var i = 0; i < this._numMeshes; i++) {
  61314. var impostor = this._impostors[i];
  61315. if (!impostor) {
  61316. continue;
  61317. }
  61318. if (impostor.isDisposed) {
  61319. this.hideImpostor(this._impostors[i--]);
  61320. }
  61321. else {
  61322. var mesh = this._meshes[i];
  61323. if (mesh && plugin) {
  61324. plugin.syncMeshWithImpostor(mesh, impostor);
  61325. }
  61326. }
  61327. }
  61328. };
  61329. /**
  61330. * Renders a specified physic impostor
  61331. * @param impostor defines the impostor to render
  61332. */
  61333. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61334. if (!this._scene) {
  61335. return;
  61336. }
  61337. for (var i = 0; i < this._numMeshes; i++) {
  61338. if (this._impostors[i] == impostor) {
  61339. return;
  61340. }
  61341. }
  61342. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61343. if (debugMesh) {
  61344. this._impostors[this._numMeshes] = impostor;
  61345. this._meshes[this._numMeshes] = debugMesh;
  61346. if (this._numMeshes === 0) {
  61347. this._renderFunction = this._updateDebugMeshes.bind(this);
  61348. this._scene.registerBeforeRender(this._renderFunction);
  61349. }
  61350. this._numMeshes++;
  61351. }
  61352. };
  61353. /**
  61354. * Hides a specified physic impostor
  61355. * @param impostor defines the impostor to hide
  61356. */
  61357. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61358. if (!impostor || !this._scene) {
  61359. return;
  61360. }
  61361. var removed = false;
  61362. for (var i = 0; i < this._numMeshes; i++) {
  61363. if (this._impostors[i] == impostor) {
  61364. var mesh = this._meshes[i];
  61365. if (!mesh) {
  61366. continue;
  61367. }
  61368. this._scene.removeMesh(mesh);
  61369. mesh.dispose();
  61370. this._numMeshes--;
  61371. if (this._numMeshes > 0) {
  61372. this._meshes[i] = this._meshes[this._numMeshes];
  61373. this._impostors[i] = this._impostors[this._numMeshes];
  61374. this._meshes[this._numMeshes] = null;
  61375. this._impostors[this._numMeshes] = null;
  61376. }
  61377. else {
  61378. this._meshes[0] = null;
  61379. this._impostors[0] = null;
  61380. }
  61381. removed = true;
  61382. break;
  61383. }
  61384. }
  61385. if (removed && this._numMeshes === 0) {
  61386. this._scene.unregisterBeforeRender(this._renderFunction);
  61387. }
  61388. };
  61389. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61390. if (!this._debugMaterial) {
  61391. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61392. this._debugMaterial.wireframe = true;
  61393. }
  61394. return this._debugMaterial;
  61395. };
  61396. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61397. if (!this._debugBoxMesh) {
  61398. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61399. this._debugBoxMesh.renderingGroupId = 1;
  61400. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61401. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61402. scene.removeMesh(this._debugBoxMesh);
  61403. }
  61404. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61405. };
  61406. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61407. if (!this._debugSphereMesh) {
  61408. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61409. this._debugSphereMesh.renderingGroupId = 1;
  61410. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61411. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61412. scene.removeMesh(this._debugSphereMesh);
  61413. }
  61414. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61415. };
  61416. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61417. var mesh = null;
  61418. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61419. mesh = this._getDebugBoxMesh(scene);
  61420. impostor.getBoxSizeToRef(mesh.scaling);
  61421. }
  61422. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61423. mesh = this._getDebugSphereMesh(scene);
  61424. var radius = impostor.getRadius();
  61425. mesh.scaling.x = radius * 2;
  61426. mesh.scaling.y = radius * 2;
  61427. mesh.scaling.z = radius * 2;
  61428. }
  61429. return mesh;
  61430. };
  61431. /** Releases all resources */
  61432. PhysicsViewer.prototype.dispose = function () {
  61433. for (var i = 0; i < this._numMeshes; i++) {
  61434. this.hideImpostor(this._impostors[i]);
  61435. }
  61436. if (this._debugBoxMesh) {
  61437. this._debugBoxMesh.dispose();
  61438. }
  61439. if (this._debugSphereMesh) {
  61440. this._debugSphereMesh.dispose();
  61441. }
  61442. if (this._debugMaterial) {
  61443. this._debugMaterial.dispose();
  61444. }
  61445. this._impostors.length = 0;
  61446. this._scene = null;
  61447. this._physicsEnginePlugin = null;
  61448. };
  61449. return PhysicsViewer;
  61450. }());
  61451. Debug.PhysicsViewer = PhysicsViewer;
  61452. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61453. })(BABYLON || (BABYLON = {}));
  61454. //# sourceMappingURL=babylon.physicsViewer.js.map
  61455. var BABYLON;
  61456. (function (BABYLON) {
  61457. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61458. get: function () {
  61459. return this._forceShowBoundingBoxes || false;
  61460. },
  61461. set: function (value) {
  61462. this._forceShowBoundingBoxes = value;
  61463. // Lazyly creates a BB renderer if needed.
  61464. if (value) {
  61465. this.getBoundingBoxRenderer();
  61466. }
  61467. },
  61468. enumerable: true,
  61469. configurable: true
  61470. });
  61471. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61472. if (!this._boundingBoxRenderer) {
  61473. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61474. }
  61475. return this._boundingBoxRenderer;
  61476. };
  61477. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61478. get: function () {
  61479. return this._showBoundingBox || false;
  61480. },
  61481. set: function (value) {
  61482. this._showBoundingBox = value;
  61483. // Lazyly creates a BB renderer if needed.
  61484. if (value) {
  61485. this.getScene().getBoundingBoxRenderer();
  61486. }
  61487. },
  61488. enumerable: true,
  61489. configurable: true
  61490. });
  61491. var BoundingBoxRenderer = /** @class */ (function () {
  61492. function BoundingBoxRenderer(scene) {
  61493. /**
  61494. * The component name helpfull to identify the component in the list of scene components.
  61495. */
  61496. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61497. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61498. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61499. this.showBackLines = true;
  61500. this.renderList = new BABYLON.SmartArray(32);
  61501. this._vertexBuffers = {};
  61502. this.scene = scene;
  61503. scene._addComponent(this);
  61504. }
  61505. /**
  61506. * Registers the component in a given scene
  61507. */
  61508. BoundingBoxRenderer.prototype.register = function () {
  61509. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61510. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61511. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61512. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  61513. };
  61514. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61515. if (mesh.showSubMeshesBoundingBox) {
  61516. var boundingInfo = subMesh.getBoundingInfo();
  61517. if (boundingInfo !== null && boundingInfo !== undefined) {
  61518. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61519. this.renderList.push(boundingInfo.boundingBox);
  61520. }
  61521. }
  61522. };
  61523. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61524. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61525. var boundingInfo = sourceMesh.getBoundingInfo();
  61526. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61527. this.renderList.push(boundingInfo.boundingBox);
  61528. }
  61529. };
  61530. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61531. if (this._colorShader) {
  61532. return;
  61533. }
  61534. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61535. attributes: [BABYLON.VertexBuffer.PositionKind],
  61536. uniforms: ["world", "viewProjection", "color"]
  61537. });
  61538. var engine = this.scene.getEngine();
  61539. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61540. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61541. this._createIndexBuffer();
  61542. };
  61543. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61544. var engine = this.scene.getEngine();
  61545. 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]);
  61546. };
  61547. /**
  61548. * Rebuilds the elements related to this component in case of
  61549. * context lost for instance.
  61550. */
  61551. BoundingBoxRenderer.prototype.rebuild = function () {
  61552. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61553. if (vb) {
  61554. vb._rebuild();
  61555. }
  61556. this._createIndexBuffer();
  61557. };
  61558. BoundingBoxRenderer.prototype.reset = function () {
  61559. this.renderList.reset();
  61560. };
  61561. /**
  61562. * Render the bounding boxes of a specific rendering group
  61563. * @param renderingGroupId defines the rendering group to render
  61564. */
  61565. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  61566. if (this.renderList.length === 0) {
  61567. return;
  61568. }
  61569. this._prepareRessources();
  61570. if (!this._colorShader.isReady()) {
  61571. return;
  61572. }
  61573. var engine = this.scene.getEngine();
  61574. engine.setDepthWrite(false);
  61575. this._colorShader._preBind();
  61576. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61577. var boundingBox = this.renderList.data[boundingBoxIndex];
  61578. if (boundingBox._tag !== renderingGroupId) {
  61579. continue;
  61580. }
  61581. var min = boundingBox.minimum;
  61582. var max = boundingBox.maximum;
  61583. var diff = max.subtract(min);
  61584. var median = min.add(diff.scale(0.5));
  61585. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61586. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61587. .multiply(boundingBox.getWorldMatrix());
  61588. // VBOs
  61589. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61590. if (this.showBackLines) {
  61591. // Back
  61592. engine.setDepthFunctionToGreaterOrEqual();
  61593. this.scene.resetCachedMaterial();
  61594. this._colorShader.setColor4("color", this.backColor.toColor4());
  61595. this._colorShader.bind(worldMatrix);
  61596. // Draw order
  61597. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61598. }
  61599. // Front
  61600. engine.setDepthFunctionToLess();
  61601. this.scene.resetCachedMaterial();
  61602. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61603. this._colorShader.bind(worldMatrix);
  61604. // Draw order
  61605. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61606. }
  61607. this._colorShader.unbind();
  61608. engine.setDepthFunctionToLessOrEqual();
  61609. engine.setDepthWrite(true);
  61610. };
  61611. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61612. this._prepareRessources();
  61613. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61614. return;
  61615. }
  61616. var engine = this.scene.getEngine();
  61617. engine.setDepthWrite(false);
  61618. engine.setColorWrite(false);
  61619. this._colorShader._preBind();
  61620. var boundingBox = mesh._boundingInfo.boundingBox;
  61621. var min = boundingBox.minimum;
  61622. var max = boundingBox.maximum;
  61623. var diff = max.subtract(min);
  61624. var median = min.add(diff.scale(0.5));
  61625. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61626. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61627. .multiply(boundingBox.getWorldMatrix());
  61628. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61629. engine.setDepthFunctionToLess();
  61630. this.scene.resetCachedMaterial();
  61631. this._colorShader.bind(worldMatrix);
  61632. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61633. this._colorShader.unbind();
  61634. engine.setDepthFunctionToLessOrEqual();
  61635. engine.setDepthWrite(true);
  61636. engine.setColorWrite(true);
  61637. };
  61638. BoundingBoxRenderer.prototype.dispose = function () {
  61639. if (!this._colorShader) {
  61640. return;
  61641. }
  61642. this.renderList.dispose();
  61643. this._colorShader.dispose();
  61644. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61645. if (buffer) {
  61646. buffer.dispose();
  61647. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61648. }
  61649. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61650. };
  61651. return BoundingBoxRenderer;
  61652. }());
  61653. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61654. })(BABYLON || (BABYLON = {}));
  61655. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61656. var BABYLON;
  61657. (function (BABYLON) {
  61658. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61659. return this._gl.createTransformFeedback();
  61660. };
  61661. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61662. this._gl.deleteTransformFeedback(value);
  61663. };
  61664. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61665. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61666. };
  61667. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61668. if (usePoints === void 0) { usePoints = true; }
  61669. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61670. };
  61671. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61672. this._gl.endTransformFeedback();
  61673. };
  61674. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61675. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61676. };
  61677. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61678. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61679. };
  61680. })(BABYLON || (BABYLON = {}));
  61681. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61682. var BABYLON;
  61683. (function (BABYLON) {
  61684. /**
  61685. * This represents a GPU particle system in Babylon
  61686. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61687. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61688. */
  61689. var GPUParticleSystem = /** @class */ (function (_super) {
  61690. __extends(GPUParticleSystem, _super);
  61691. /**
  61692. * Instantiates a GPU particle system.
  61693. * 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.
  61694. * @param name The name of the particle system
  61695. * @param options The options used to create the system
  61696. * @param scene The scene the particle system belongs to
  61697. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61698. */
  61699. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61700. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61701. var _this = _super.call(this, name) || this;
  61702. /**
  61703. * The layer mask we are rendering the particles through.
  61704. */
  61705. _this.layerMask = 0x0FFFFFFF;
  61706. _this._accumulatedCount = 0;
  61707. _this._targetIndex = 0;
  61708. _this._currentRenderId = -1;
  61709. _this._started = false;
  61710. _this._stopped = false;
  61711. _this._timeDelta = 0;
  61712. _this._attributesStrideSize = 21;
  61713. _this._actualFrame = 0;
  61714. _this._rawTextureWidth = 256;
  61715. /**
  61716. * An event triggered when the system is disposed.
  61717. */
  61718. _this.onDisposeObservable = new BABYLON.Observable();
  61719. /**
  61720. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61721. * to override the particles.
  61722. */
  61723. _this.forceDepthWrite = false;
  61724. _this._preWarmDone = false;
  61725. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61726. // Setup the default processing configuration to the scene.
  61727. _this._attachImageProcessingConfiguration(null);
  61728. _this._engine = _this._scene.getEngine();
  61729. if (!options.randomTextureSize) {
  61730. delete options.randomTextureSize;
  61731. }
  61732. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61733. var optionsAsNumber = options;
  61734. if (isFinite(optionsAsNumber)) {
  61735. fullOptions.capacity = optionsAsNumber;
  61736. }
  61737. _this._capacity = fullOptions.capacity;
  61738. _this._activeCount = fullOptions.capacity;
  61739. _this._currentActiveCount = 0;
  61740. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61741. _this._scene.particleSystems.push(_this);
  61742. _this._updateEffectOptions = {
  61743. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  61744. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61745. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61746. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61747. uniformBuffersNames: [],
  61748. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61749. defines: "",
  61750. fallbacks: null,
  61751. onCompiled: null,
  61752. onError: null,
  61753. indexParameters: null,
  61754. maxSimultaneousLights: 0,
  61755. transformFeedbackVaryings: []
  61756. };
  61757. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61758. // Random data
  61759. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61760. var d = [];
  61761. for (var i = 0; i < maxTextureSize; ++i) {
  61762. d.push(Math.random());
  61763. d.push(Math.random());
  61764. d.push(Math.random());
  61765. d.push(Math.random());
  61766. }
  61767. _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);
  61768. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61769. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61770. d = [];
  61771. for (var i = 0; i < maxTextureSize; ++i) {
  61772. d.push(Math.random());
  61773. d.push(Math.random());
  61774. d.push(Math.random());
  61775. d.push(Math.random());
  61776. }
  61777. _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);
  61778. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61779. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61780. _this._randomTextureSize = maxTextureSize;
  61781. return _this;
  61782. }
  61783. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61784. /**
  61785. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61786. */
  61787. get: function () {
  61788. if (!BABYLON.Engine.LastCreatedEngine) {
  61789. return false;
  61790. }
  61791. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61792. },
  61793. enumerable: true,
  61794. configurable: true
  61795. });
  61796. /**
  61797. * Gets the maximum number of particles active at the same time.
  61798. * @returns The max number of active particles.
  61799. */
  61800. GPUParticleSystem.prototype.getCapacity = function () {
  61801. return this._capacity;
  61802. };
  61803. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61804. /**
  61805. * Gets or set the number of active particles
  61806. */
  61807. get: function () {
  61808. return this._activeCount;
  61809. },
  61810. set: function (value) {
  61811. this._activeCount = Math.min(value, this._capacity);
  61812. },
  61813. enumerable: true,
  61814. configurable: true
  61815. });
  61816. /**
  61817. * Is this system ready to be used/rendered
  61818. * @return true if the system is ready
  61819. */
  61820. GPUParticleSystem.prototype.isReady = function () {
  61821. if (!this._updateEffect) {
  61822. this._recreateUpdateEffect();
  61823. this._recreateRenderEffect();
  61824. return false;
  61825. }
  61826. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61827. return false;
  61828. }
  61829. return true;
  61830. };
  61831. /**
  61832. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61833. * @returns True if it has been started, otherwise false.
  61834. */
  61835. GPUParticleSystem.prototype.isStarted = function () {
  61836. return this._started;
  61837. };
  61838. /**
  61839. * Starts the particle system and begins to emit
  61840. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61841. */
  61842. GPUParticleSystem.prototype.start = function (delay) {
  61843. var _this = this;
  61844. if (delay === void 0) { delay = this.startDelay; }
  61845. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61846. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61847. }
  61848. if (delay) {
  61849. setTimeout(function () {
  61850. _this.start(0);
  61851. }, delay);
  61852. return;
  61853. }
  61854. this._started = true;
  61855. this._stopped = false;
  61856. this._preWarmDone = false;
  61857. };
  61858. /**
  61859. * Stops the particle system.
  61860. */
  61861. GPUParticleSystem.prototype.stop = function () {
  61862. this._stopped = true;
  61863. };
  61864. /**
  61865. * Remove all active particles
  61866. */
  61867. GPUParticleSystem.prototype.reset = function () {
  61868. this._releaseBuffers();
  61869. this._releaseVAOs();
  61870. this._currentActiveCount = 0;
  61871. this._targetIndex = 0;
  61872. };
  61873. /**
  61874. * Returns the string "GPUParticleSystem"
  61875. * @returns a string containing the class name
  61876. */
  61877. GPUParticleSystem.prototype.getClassName = function () {
  61878. return "GPUParticleSystem";
  61879. };
  61880. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61881. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61882. this._releaseBuffers();
  61883. return this;
  61884. };
  61885. /**
  61886. * Adds a new color gradient
  61887. * @param gradient defines the gradient to use (between 0 and 1)
  61888. * @param color defines the color to affect to the specified gradient
  61889. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61890. * @returns the current particle system
  61891. */
  61892. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61893. if (!this._colorGradients) {
  61894. this._colorGradients = [];
  61895. }
  61896. var colorGradient = new BABYLON.ColorGradient();
  61897. colorGradient.gradient = gradient;
  61898. colorGradient.color1 = color1;
  61899. this._colorGradients.push(colorGradient);
  61900. this._colorGradients.sort(function (a, b) {
  61901. if (a.gradient < b.gradient) {
  61902. return -1;
  61903. }
  61904. else if (a.gradient > b.gradient) {
  61905. return 1;
  61906. }
  61907. return 0;
  61908. });
  61909. if (this._colorGradientsTexture) {
  61910. this._colorGradientsTexture.dispose();
  61911. this._colorGradientsTexture = null;
  61912. }
  61913. this._releaseBuffers();
  61914. return this;
  61915. };
  61916. /**
  61917. * Remove a specific color gradient
  61918. * @param gradient defines the gradient to remove
  61919. * @returns the current particle system
  61920. */
  61921. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61922. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61923. this._colorGradientsTexture = null;
  61924. return this;
  61925. };
  61926. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61927. var valueGradient = new BABYLON.FactorGradient();
  61928. valueGradient.gradient = gradient;
  61929. valueGradient.factor1 = factor;
  61930. factorGradients.push(valueGradient);
  61931. factorGradients.sort(function (a, b) {
  61932. if (a.gradient < b.gradient) {
  61933. return -1;
  61934. }
  61935. else if (a.gradient > b.gradient) {
  61936. return 1;
  61937. }
  61938. return 0;
  61939. });
  61940. this._releaseBuffers();
  61941. };
  61942. /**
  61943. * Adds a new size gradient
  61944. * @param gradient defines the gradient to use (between 0 and 1)
  61945. * @param factor defines the size factor to affect to the specified gradient
  61946. * @returns the current particle system
  61947. */
  61948. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61949. if (!this._sizeGradients) {
  61950. this._sizeGradients = [];
  61951. }
  61952. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61953. if (this._sizeGradientsTexture) {
  61954. this._sizeGradientsTexture.dispose();
  61955. this._sizeGradientsTexture = null;
  61956. }
  61957. this._releaseBuffers();
  61958. return this;
  61959. };
  61960. /**
  61961. * Remove a specific size gradient
  61962. * @param gradient defines the gradient to remove
  61963. * @returns the current particle system
  61964. */
  61965. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61966. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61967. this._sizeGradientsTexture = null;
  61968. return this;
  61969. };
  61970. /**
  61971. * Adds a new angular speed gradient
  61972. * @param gradient defines the gradient to use (between 0 and 1)
  61973. * @param factor defines the angular speed to affect to the specified gradient
  61974. * @returns the current particle system
  61975. */
  61976. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61977. if (!this._angularSpeedGradients) {
  61978. this._angularSpeedGradients = [];
  61979. }
  61980. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61981. if (this._angularSpeedGradientsTexture) {
  61982. this._angularSpeedGradientsTexture.dispose();
  61983. this._angularSpeedGradientsTexture = null;
  61984. }
  61985. this._releaseBuffers();
  61986. return this;
  61987. };
  61988. /**
  61989. * Remove a specific angular speed gradient
  61990. * @param gradient defines the gradient to remove
  61991. * @returns the current particle system
  61992. */
  61993. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61994. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61995. this._angularSpeedGradientsTexture = null;
  61996. return this;
  61997. };
  61998. /**
  61999. * Adds a new velocity gradient
  62000. * @param gradient defines the gradient to use (between 0 and 1)
  62001. * @param factor defines the velocity to affect to the specified gradient
  62002. * @returns the current particle system
  62003. */
  62004. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  62005. if (!this._velocityGradients) {
  62006. this._velocityGradients = [];
  62007. }
  62008. this._addFactorGradient(this._velocityGradients, gradient, factor);
  62009. if (this._velocityGradientsTexture) {
  62010. this._velocityGradientsTexture.dispose();
  62011. this._velocityGradientsTexture = null;
  62012. }
  62013. this._releaseBuffers();
  62014. return this;
  62015. };
  62016. /**
  62017. * Remove a specific velocity gradient
  62018. * @param gradient defines the gradient to remove
  62019. * @returns the current particle system
  62020. */
  62021. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  62022. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  62023. this._velocityGradientsTexture = null;
  62024. return this;
  62025. };
  62026. /**
  62027. * Adds a new limit velocity gradient
  62028. * @param gradient defines the gradient to use (between 0 and 1)
  62029. * @param factor defines the limit velocity value to affect to the specified gradient
  62030. * @returns the current particle system
  62031. */
  62032. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  62033. if (!this._limitVelocityGradients) {
  62034. this._limitVelocityGradients = [];
  62035. }
  62036. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  62037. if (this._limitVelocityGradientsTexture) {
  62038. this._limitVelocityGradientsTexture.dispose();
  62039. this._limitVelocityGradientsTexture = null;
  62040. }
  62041. this._releaseBuffers();
  62042. return this;
  62043. };
  62044. /**
  62045. * Remove a specific limit velocity gradient
  62046. * @param gradient defines the gradient to remove
  62047. * @returns the current particle system
  62048. */
  62049. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  62050. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  62051. this._limitVelocityGradientsTexture = null;
  62052. return this;
  62053. };
  62054. /**
  62055. * Adds a new drag gradient
  62056. * @param gradient defines the gradient to use (between 0 and 1)
  62057. * @param factor defines the drag value to affect to the specified gradient
  62058. * @returns the current particle system
  62059. */
  62060. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  62061. if (!this._dragGradients) {
  62062. this._dragGradients = [];
  62063. }
  62064. this._addFactorGradient(this._dragGradients, gradient, factor);
  62065. if (this._dragGradientsTexture) {
  62066. this._dragGradientsTexture.dispose();
  62067. this._dragGradientsTexture = null;
  62068. }
  62069. this._releaseBuffers();
  62070. return this;
  62071. };
  62072. /**
  62073. * Remove a specific drag gradient
  62074. * @param gradient defines the gradient to remove
  62075. * @returns the current particle system
  62076. */
  62077. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  62078. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  62079. this._dragGradientsTexture = null;
  62080. return this;
  62081. };
  62082. /**
  62083. * Not supported by GPUParticleSystem
  62084. * @param gradient defines the gradient to use (between 0 and 1)
  62085. * @param factor defines the emit rate value to affect to the specified gradient
  62086. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62087. * @returns the current particle system
  62088. */
  62089. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  62090. // Do nothing as emit rate is not supported by GPUParticleSystem
  62091. return this;
  62092. };
  62093. /**
  62094. * Not supported by GPUParticleSystem
  62095. * @param gradient defines the gradient to remove
  62096. * @returns the current particle system
  62097. */
  62098. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  62099. // Do nothing as emit rate is not supported by GPUParticleSystem
  62100. return this;
  62101. };
  62102. /**
  62103. * Not supported by GPUParticleSystem
  62104. * @param gradient defines the gradient to use (between 0 and 1)
  62105. * @param factor defines the start size value to affect to the specified gradient
  62106. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  62107. * @returns the current particle system
  62108. */
  62109. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  62110. // Do nothing as start size is not supported by GPUParticleSystem
  62111. return this;
  62112. };
  62113. /**
  62114. * Not supported by GPUParticleSystem
  62115. * @param gradient defines the gradient to remove
  62116. * @returns the current particle system
  62117. */
  62118. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  62119. // Do nothing as start size is not supported by GPUParticleSystem
  62120. return this;
  62121. };
  62122. /**
  62123. * Not supported by GPUParticleSystem
  62124. * @param gradient defines the gradient to use (between 0 and 1)
  62125. * @param min defines the color remap minimal range
  62126. * @param max defines the color remap maximal range
  62127. * @returns the current particle system
  62128. */
  62129. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  62130. // Do nothing as start size is not supported by GPUParticleSystem
  62131. return this;
  62132. };
  62133. /**
  62134. * Not supported by GPUParticleSystem
  62135. * @param gradient defines the gradient to remove
  62136. * @returns the current particle system
  62137. */
  62138. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  62139. // Do nothing as start size is not supported by GPUParticleSystem
  62140. return this;
  62141. };
  62142. /**
  62143. * Not supported by GPUParticleSystem
  62144. * @param gradient defines the gradient to use (between 0 and 1)
  62145. * @param min defines the alpha remap minimal range
  62146. * @param max defines the alpha remap maximal range
  62147. * @returns the current particle system
  62148. */
  62149. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  62150. // Do nothing as start size is not supported by GPUParticleSystem
  62151. return this;
  62152. };
  62153. /**
  62154. * Not supported by GPUParticleSystem
  62155. * @param gradient defines the gradient to remove
  62156. * @returns the current particle system
  62157. */
  62158. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  62159. // Do nothing as start size is not supported by GPUParticleSystem
  62160. return this;
  62161. };
  62162. /**
  62163. * Not supported by GPUParticleSystem
  62164. * @param gradient defines the gradient to use (between 0 and 1)
  62165. * @param color defines the color to affect to the specified gradient
  62166. * @returns the current particle system
  62167. */
  62168. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  62169. //Not supported by GPUParticleSystem
  62170. return this;
  62171. };
  62172. /**
  62173. * Not supported by GPUParticleSystem
  62174. * @param gradient defines the gradient to remove
  62175. * @returns the current particle system
  62176. */
  62177. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62178. //Not supported by GPUParticleSystem
  62179. return this;
  62180. };
  62181. /**
  62182. * Not supported by GPUParticleSystem
  62183. * @returns the list of ramp gradients
  62184. */
  62185. GPUParticleSystem.prototype.getRampGradients = function () {
  62186. return null;
  62187. };
  62188. GPUParticleSystem.prototype._reset = function () {
  62189. this._releaseBuffers();
  62190. };
  62191. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62192. var updateVertexBuffers = {};
  62193. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62194. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62195. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62196. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62197. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62198. var offset = 12;
  62199. if (!this._colorGradientsTexture) {
  62200. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62201. offset += 4;
  62202. }
  62203. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62204. offset += 3;
  62205. if (!this._isBillboardBased) {
  62206. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62207. offset += 3;
  62208. }
  62209. if (this._angularSpeedGradientsTexture) {
  62210. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62211. offset += 1;
  62212. }
  62213. else {
  62214. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62215. offset += 2;
  62216. }
  62217. if (this._isAnimationSheetEnabled) {
  62218. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62219. offset += 1;
  62220. if (this.spriteRandomStartCell) {
  62221. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62222. offset += 1;
  62223. }
  62224. }
  62225. if (this.noiseTexture) {
  62226. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  62227. offset += 3;
  62228. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  62229. offset += 3;
  62230. }
  62231. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62232. this._engine.bindArrayBuffer(null);
  62233. return vao;
  62234. };
  62235. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62236. var renderVertexBuffers = {};
  62237. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62238. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62239. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62240. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62241. var offset = 12;
  62242. if (!this._colorGradientsTexture) {
  62243. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62244. offset += 4;
  62245. }
  62246. offset += 3; // Direction
  62247. if (!this._isBillboardBased) {
  62248. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62249. offset += 3;
  62250. }
  62251. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62252. if (this._angularSpeedGradientsTexture) {
  62253. offset++;
  62254. }
  62255. else {
  62256. offset += 2;
  62257. }
  62258. if (this._isAnimationSheetEnabled) {
  62259. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62260. offset += 1;
  62261. if (this.spriteRandomStartCell) {
  62262. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62263. offset += 1;
  62264. }
  62265. }
  62266. if (this.noiseTexture) {
  62267. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  62268. offset += 3;
  62269. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  62270. offset += 3;
  62271. }
  62272. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62273. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62274. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62275. this._engine.bindArrayBuffer(null);
  62276. return vao;
  62277. };
  62278. GPUParticleSystem.prototype._initialize = function (force) {
  62279. if (force === void 0) { force = false; }
  62280. if (this._buffer0 && !force) {
  62281. return;
  62282. }
  62283. var engine = this._scene.getEngine();
  62284. var data = new Array();
  62285. if (!this.isBillboardBased) {
  62286. this._attributesStrideSize += 3;
  62287. }
  62288. if (this._colorGradientsTexture) {
  62289. this._attributesStrideSize -= 4;
  62290. }
  62291. if (this._angularSpeedGradientsTexture) {
  62292. this._attributesStrideSize -= 1;
  62293. }
  62294. if (this._isAnimationSheetEnabled) {
  62295. this._attributesStrideSize += 1;
  62296. if (this.spriteRandomStartCell) {
  62297. this._attributesStrideSize += 1;
  62298. }
  62299. }
  62300. if (this.noiseTexture) {
  62301. this._attributesStrideSize += 6;
  62302. }
  62303. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62304. // position
  62305. data.push(0.0);
  62306. data.push(0.0);
  62307. data.push(0.0);
  62308. // Age and life
  62309. data.push(0.0); // create the particle as a dead one to create a new one at start
  62310. data.push(0.0);
  62311. // Seed
  62312. data.push(Math.random());
  62313. data.push(Math.random());
  62314. data.push(Math.random());
  62315. data.push(Math.random());
  62316. // Size
  62317. data.push(0.0);
  62318. data.push(0.0);
  62319. data.push(0.0);
  62320. if (!this._colorGradientsTexture) {
  62321. // color
  62322. data.push(0.0);
  62323. data.push(0.0);
  62324. data.push(0.0);
  62325. data.push(0.0);
  62326. }
  62327. // direction
  62328. data.push(0.0);
  62329. data.push(0.0);
  62330. data.push(0.0);
  62331. if (!this.isBillboardBased) {
  62332. // initialDirection
  62333. data.push(0.0);
  62334. data.push(0.0);
  62335. data.push(0.0);
  62336. }
  62337. // angle
  62338. data.push(0.0);
  62339. if (!this._angularSpeedGradientsTexture) {
  62340. data.push(0.0);
  62341. }
  62342. if (this._isAnimationSheetEnabled) {
  62343. data.push(0.0);
  62344. if (this.spriteRandomStartCell) {
  62345. data.push(0.0);
  62346. }
  62347. }
  62348. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  62349. data.push(Math.random());
  62350. data.push(Math.random());
  62351. data.push(Math.random());
  62352. data.push(Math.random());
  62353. data.push(Math.random());
  62354. data.push(Math.random());
  62355. }
  62356. }
  62357. // Sprite data
  62358. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62359. -0.5, 0.5, 0, 1,
  62360. -0.5, -0.5, 0, 0,
  62361. 0.5, -0.5, 1, 0]);
  62362. // Buffers
  62363. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62364. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62365. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62366. // Update VAO
  62367. this._updateVAO = [];
  62368. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62369. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62370. // Render VAO
  62371. this._renderVAO = [];
  62372. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62373. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62374. // Links
  62375. this._sourceBuffer = this._buffer0;
  62376. this._targetBuffer = this._buffer1;
  62377. };
  62378. /** @hidden */
  62379. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62380. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62381. if (this._isBillboardBased) {
  62382. defines += "\n#define BILLBOARD";
  62383. }
  62384. if (this._colorGradientsTexture) {
  62385. defines += "\n#define COLORGRADIENTS";
  62386. }
  62387. if (this._sizeGradientsTexture) {
  62388. defines += "\n#define SIZEGRADIENTS";
  62389. }
  62390. if (this._angularSpeedGradientsTexture) {
  62391. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62392. }
  62393. if (this._velocityGradientsTexture) {
  62394. defines += "\n#define VELOCITYGRADIENTS";
  62395. }
  62396. if (this._limitVelocityGradientsTexture) {
  62397. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62398. }
  62399. if (this._dragGradientsTexture) {
  62400. defines += "\n#define DRAGGRADIENTS";
  62401. }
  62402. if (this.isAnimationSheetEnabled) {
  62403. defines += "\n#define ANIMATESHEET";
  62404. if (this.spriteRandomStartCell) {
  62405. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62406. }
  62407. }
  62408. if (this.noiseTexture) {
  62409. defines += "\n#define NOISE";
  62410. }
  62411. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62412. return;
  62413. }
  62414. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62415. if (!this._colorGradientsTexture) {
  62416. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62417. }
  62418. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62419. if (!this._isBillboardBased) {
  62420. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62421. }
  62422. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62423. if (this.isAnimationSheetEnabled) {
  62424. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62425. if (this.spriteRandomStartCell) {
  62426. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62427. }
  62428. }
  62429. if (this.noiseTexture) {
  62430. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  62431. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  62432. }
  62433. this._updateEffectOptions.defines = defines;
  62434. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62435. };
  62436. /** @hidden */
  62437. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62438. var defines = "";
  62439. if (this._scene.clipPlane) {
  62440. defines = "\n#define CLIPPLANE";
  62441. }
  62442. if (this._scene.clipPlane2) {
  62443. defines = "\n#define CLIPPLANE2";
  62444. }
  62445. if (this._scene.clipPlane3) {
  62446. defines = "\n#define CLIPPLANE3";
  62447. }
  62448. if (this._scene.clipPlane4) {
  62449. defines = "\n#define CLIPPLANE4";
  62450. }
  62451. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62452. defines = "\n#define BLENDMULTIPLYMODE";
  62453. }
  62454. if (this._isBillboardBased) {
  62455. defines += "\n#define BILLBOARD";
  62456. switch (this.billboardMode) {
  62457. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62458. defines += "\n#define BILLBOARDY";
  62459. break;
  62460. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62461. default:
  62462. break;
  62463. }
  62464. }
  62465. if (this._colorGradientsTexture) {
  62466. defines += "\n#define COLORGRADIENTS";
  62467. }
  62468. if (this.isAnimationSheetEnabled) {
  62469. defines += "\n#define ANIMATESHEET";
  62470. }
  62471. if (this._imageProcessingConfiguration) {
  62472. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62473. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62474. }
  62475. if (this._renderEffect && this._renderEffect.defines === defines) {
  62476. return;
  62477. }
  62478. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62479. var samplers = ["textureSampler", "colorGradientSampler"];
  62480. if (BABYLON.ImageProcessingConfiguration) {
  62481. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62482. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62483. }
  62484. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62485. };
  62486. /**
  62487. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62488. * @param preWarm defines if we are in the pre-warmimg phase
  62489. */
  62490. GPUParticleSystem.prototype.animate = function (preWarm) {
  62491. if (preWarm === void 0) { preWarm = false; }
  62492. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62493. this._actualFrame += this._timeDelta;
  62494. if (!this._stopped) {
  62495. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62496. this.stop();
  62497. }
  62498. }
  62499. };
  62500. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62501. var texture = this[textureName];
  62502. if (!factorGradients || !factorGradients.length || texture) {
  62503. return;
  62504. }
  62505. var data = new Float32Array(this._rawTextureWidth);
  62506. for (var x = 0; x < this._rawTextureWidth; x++) {
  62507. var ratio = x / this._rawTextureWidth;
  62508. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62509. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62510. });
  62511. }
  62512. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62513. };
  62514. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62515. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62516. };
  62517. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62518. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62519. };
  62520. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62521. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62522. };
  62523. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62524. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62525. };
  62526. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62527. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62528. };
  62529. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62530. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62531. return;
  62532. }
  62533. var data = new Uint8Array(this._rawTextureWidth * 4);
  62534. var tmpColor = BABYLON.Tmp.Color4[0];
  62535. for (var x = 0; x < this._rawTextureWidth; x++) {
  62536. var ratio = x / this._rawTextureWidth;
  62537. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62538. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62539. data[x * 4] = tmpColor.r * 255;
  62540. data[x * 4 + 1] = tmpColor.g * 255;
  62541. data[x * 4 + 2] = tmpColor.b * 255;
  62542. data[x * 4 + 3] = tmpColor.a * 255;
  62543. });
  62544. }
  62545. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62546. };
  62547. /**
  62548. * Renders the particle system in its current state
  62549. * @param preWarm defines if the system should only update the particles but not render them
  62550. * @returns the current number of particles
  62551. */
  62552. GPUParticleSystem.prototype.render = function (preWarm) {
  62553. if (preWarm === void 0) { preWarm = false; }
  62554. if (!this._started) {
  62555. return 0;
  62556. }
  62557. this._createColorGradientTexture();
  62558. this._createSizeGradientTexture();
  62559. this._createAngularSpeedGradientTexture();
  62560. this._createVelocityGradientTexture();
  62561. this._createLimitVelocityGradientTexture();
  62562. this._createDragGradientTexture();
  62563. this._recreateUpdateEffect();
  62564. this._recreateRenderEffect();
  62565. if (!this.isReady()) {
  62566. return 0;
  62567. }
  62568. if (!preWarm) {
  62569. if (!this._preWarmDone && this.preWarmCycles) {
  62570. for (var index = 0; index < this.preWarmCycles; index++) {
  62571. this.animate(true);
  62572. this.render(true);
  62573. }
  62574. this._preWarmDone = true;
  62575. }
  62576. if (this._currentRenderId === this._scene.getRenderId()) {
  62577. return 0;
  62578. }
  62579. this._currentRenderId = this._scene.getRenderId();
  62580. }
  62581. // Get everything ready to render
  62582. this._initialize();
  62583. this._accumulatedCount += this.emitRate * this._timeDelta;
  62584. if (this._accumulatedCount > 1) {
  62585. var intPart = this._accumulatedCount | 0;
  62586. this._accumulatedCount -= intPart;
  62587. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62588. }
  62589. if (!this._currentActiveCount) {
  62590. return 0;
  62591. }
  62592. // Enable update effect
  62593. this._engine.enableEffect(this._updateEffect);
  62594. this._engine.setState(false);
  62595. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62596. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62597. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62598. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62599. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62600. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62601. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62602. if (!this._colorGradientsTexture) {
  62603. this._updateEffect.setDirectColor4("color1", this.color1);
  62604. this._updateEffect.setDirectColor4("color2", this.color2);
  62605. }
  62606. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62607. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62608. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62609. this._updateEffect.setVector3("gravity", this.gravity);
  62610. if (this._sizeGradientsTexture) {
  62611. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62612. }
  62613. if (this._angularSpeedGradientsTexture) {
  62614. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62615. }
  62616. if (this._velocityGradientsTexture) {
  62617. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62618. }
  62619. if (this._limitVelocityGradientsTexture) {
  62620. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62621. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62622. }
  62623. if (this._dragGradientsTexture) {
  62624. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62625. }
  62626. if (this.particleEmitterType) {
  62627. this.particleEmitterType.applyToShader(this._updateEffect);
  62628. }
  62629. if (this._isAnimationSheetEnabled) {
  62630. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62631. }
  62632. if (this.noiseTexture) {
  62633. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62634. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62635. }
  62636. var emitterWM;
  62637. if (this.emitter.position) {
  62638. var emitterMesh = this.emitter;
  62639. emitterWM = emitterMesh.getWorldMatrix();
  62640. }
  62641. else {
  62642. var emitterPosition = this.emitter;
  62643. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62644. }
  62645. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62646. // Bind source VAO
  62647. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62648. // Update
  62649. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62650. this._engine.setRasterizerState(false);
  62651. this._engine.beginTransformFeedback(true);
  62652. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62653. this._engine.endTransformFeedback();
  62654. this._engine.setRasterizerState(true);
  62655. this._engine.bindTransformFeedbackBuffer(null);
  62656. if (!preWarm) {
  62657. // Enable render effect
  62658. this._engine.enableEffect(this._renderEffect);
  62659. var viewMatrix = this._scene.getViewMatrix();
  62660. this._renderEffect.setMatrix("view", viewMatrix);
  62661. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62662. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62663. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62664. if (this._colorGradientsTexture) {
  62665. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62666. }
  62667. else {
  62668. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62669. }
  62670. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62671. var baseSize = this.particleTexture.getBaseSize();
  62672. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62673. }
  62674. if (this._isBillboardBased) {
  62675. var camera = this._scene.activeCamera;
  62676. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62677. }
  62678. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62679. var invView = viewMatrix.clone();
  62680. invView.invert();
  62681. this._renderEffect.setMatrix("invView", invView);
  62682. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62683. }
  62684. // image processing
  62685. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62686. this._imageProcessingConfiguration.bind(this._renderEffect);
  62687. }
  62688. // Draw order
  62689. switch (this.blendMode) {
  62690. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62691. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62692. break;
  62693. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62694. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62695. break;
  62696. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62697. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62698. break;
  62699. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62700. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62701. break;
  62702. }
  62703. if (this.forceDepthWrite) {
  62704. this._engine.setDepthWrite(true);
  62705. }
  62706. // Bind source VAO
  62707. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62708. // Render
  62709. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62710. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62711. }
  62712. // Switch VAOs
  62713. this._targetIndex++;
  62714. if (this._targetIndex === 2) {
  62715. this._targetIndex = 0;
  62716. }
  62717. // Switch buffers
  62718. var tmpBuffer = this._sourceBuffer;
  62719. this._sourceBuffer = this._targetBuffer;
  62720. this._targetBuffer = tmpBuffer;
  62721. return this._currentActiveCount;
  62722. };
  62723. /**
  62724. * Rebuilds the particle system
  62725. */
  62726. GPUParticleSystem.prototype.rebuild = function () {
  62727. this._initialize(true);
  62728. };
  62729. GPUParticleSystem.prototype._releaseBuffers = function () {
  62730. if (this._buffer0) {
  62731. this._buffer0.dispose();
  62732. this._buffer0 = null;
  62733. }
  62734. if (this._buffer1) {
  62735. this._buffer1.dispose();
  62736. this._buffer1 = null;
  62737. }
  62738. if (this._spriteBuffer) {
  62739. this._spriteBuffer.dispose();
  62740. this._spriteBuffer = null;
  62741. }
  62742. };
  62743. GPUParticleSystem.prototype._releaseVAOs = function () {
  62744. if (!this._updateVAO) {
  62745. return;
  62746. }
  62747. for (var index = 0; index < this._updateVAO.length; index++) {
  62748. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62749. }
  62750. this._updateVAO = [];
  62751. for (var index = 0; index < this._renderVAO.length; index++) {
  62752. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62753. }
  62754. this._renderVAO = [];
  62755. };
  62756. /**
  62757. * Disposes the particle system and free the associated resources
  62758. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62759. */
  62760. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62761. if (disposeTexture === void 0) { disposeTexture = true; }
  62762. var index = this._scene.particleSystems.indexOf(this);
  62763. if (index > -1) {
  62764. this._scene.particleSystems.splice(index, 1);
  62765. }
  62766. this._releaseBuffers();
  62767. this._releaseVAOs();
  62768. if (this._colorGradientsTexture) {
  62769. this._colorGradientsTexture.dispose();
  62770. this._colorGradientsTexture = null;
  62771. }
  62772. if (this._sizeGradientsTexture) {
  62773. this._sizeGradientsTexture.dispose();
  62774. this._sizeGradientsTexture = null;
  62775. }
  62776. if (this._angularSpeedGradientsTexture) {
  62777. this._angularSpeedGradientsTexture.dispose();
  62778. this._angularSpeedGradientsTexture = null;
  62779. }
  62780. if (this._velocityGradientsTexture) {
  62781. this._velocityGradientsTexture.dispose();
  62782. this._velocityGradientsTexture = null;
  62783. }
  62784. if (this._limitVelocityGradientsTexture) {
  62785. this._limitVelocityGradientsTexture.dispose();
  62786. this._limitVelocityGradientsTexture = null;
  62787. }
  62788. if (this._dragGradientsTexture) {
  62789. this._dragGradientsTexture.dispose();
  62790. this._dragGradientsTexture = null;
  62791. }
  62792. if (this._randomTexture) {
  62793. this._randomTexture.dispose();
  62794. this._randomTexture = null;
  62795. }
  62796. if (this._randomTexture2) {
  62797. this._randomTexture2.dispose();
  62798. this._randomTexture2 = null;
  62799. }
  62800. if (disposeTexture && this.particleTexture) {
  62801. this.particleTexture.dispose();
  62802. this.particleTexture = null;
  62803. }
  62804. if (disposeTexture && this.noiseTexture) {
  62805. this.noiseTexture.dispose();
  62806. this.noiseTexture = null;
  62807. }
  62808. // Callback
  62809. this.onDisposeObservable.notifyObservers(this);
  62810. this.onDisposeObservable.clear();
  62811. };
  62812. /**
  62813. * Clones the particle system.
  62814. * @param name The name of the cloned object
  62815. * @param newEmitter The new emitter to use
  62816. * @returns the cloned particle system
  62817. */
  62818. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62819. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62820. BABYLON.Tools.DeepCopy(this, result);
  62821. if (newEmitter === undefined) {
  62822. newEmitter = this.emitter;
  62823. }
  62824. result.emitter = newEmitter;
  62825. if (this.particleTexture) {
  62826. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62827. }
  62828. return result;
  62829. };
  62830. /**
  62831. * Serializes the particle system to a JSON object.
  62832. * @returns the JSON object
  62833. */
  62834. GPUParticleSystem.prototype.serialize = function () {
  62835. var serializationObject = {};
  62836. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62837. serializationObject.activeParticleCount = this.activeParticleCount;
  62838. return serializationObject;
  62839. };
  62840. /**
  62841. * Parses a JSON object to create a GPU particle system.
  62842. * @param parsedParticleSystem The JSON object to parse
  62843. * @param scene The scene to create the particle system in
  62844. * @param rootUrl The root url to use to load external dependencies like texture
  62845. * @returns the parsed GPU particle system
  62846. */
  62847. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62848. var name = parsedParticleSystem.name;
  62849. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62850. if (parsedParticleSystem.activeParticleCount) {
  62851. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62852. }
  62853. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62854. return particleSystem;
  62855. };
  62856. return GPUParticleSystem;
  62857. }(BABYLON.BaseParticleSystem));
  62858. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62859. })(BABYLON || (BABYLON = {}));
  62860. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62861. var BABYLON;
  62862. (function (BABYLON) {
  62863. /**
  62864. * Represents one particle of a solid particle system.
  62865. */
  62866. var SolidParticle = /** @class */ (function () {
  62867. /**
  62868. * Creates a Solid Particle object.
  62869. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62870. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62871. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62872. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62873. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62874. * @param shapeId (integer) is the model shape identifier in the SPS.
  62875. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62876. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62877. */
  62878. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62879. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62880. /**
  62881. * particle global index
  62882. */
  62883. this.idx = 0;
  62884. /**
  62885. * The color of the particle
  62886. */
  62887. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62888. /**
  62889. * The world space position of the particle.
  62890. */
  62891. this.position = BABYLON.Vector3.Zero();
  62892. /**
  62893. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62894. */
  62895. this.rotation = BABYLON.Vector3.Zero();
  62896. /**
  62897. * The scaling of the particle.
  62898. */
  62899. this.scaling = BABYLON.Vector3.One();
  62900. /**
  62901. * The uvs of the particle.
  62902. */
  62903. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62904. /**
  62905. * The current speed of the particle.
  62906. */
  62907. this.velocity = BABYLON.Vector3.Zero();
  62908. /**
  62909. * The pivot point in the particle local space.
  62910. */
  62911. this.pivot = BABYLON.Vector3.Zero();
  62912. /**
  62913. * Must the particle be translated from its pivot point in its local space ?
  62914. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62915. * Default : false
  62916. */
  62917. this.translateFromPivot = false;
  62918. /**
  62919. * Is the particle active or not ?
  62920. */
  62921. this.alive = true;
  62922. /**
  62923. * Is the particle visible or not ?
  62924. */
  62925. this.isVisible = true;
  62926. /**
  62927. * Index of this particle in the global "positions" array (Internal use)
  62928. * @hidden
  62929. */
  62930. this._pos = 0;
  62931. /**
  62932. * @hidden Index of this particle in the global "indices" array (Internal use)
  62933. */
  62934. this._ind = 0;
  62935. /**
  62936. * ModelShape id of this particle
  62937. */
  62938. this.shapeId = 0;
  62939. /**
  62940. * Index of the particle in its shape id (Internal use)
  62941. */
  62942. this.idxInShape = 0;
  62943. /**
  62944. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62945. */
  62946. this._stillInvisible = false;
  62947. /**
  62948. * @hidden Last computed particle rotation matrix
  62949. */
  62950. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62951. /**
  62952. * Parent particle Id, if any.
  62953. * Default null.
  62954. */
  62955. this.parentId = null;
  62956. /**
  62957. * @hidden Internal global position in the SPS.
  62958. */
  62959. this._globalPosition = BABYLON.Vector3.Zero();
  62960. this.idx = particleIndex;
  62961. this._pos = positionIndex;
  62962. this._ind = indiceIndex;
  62963. this._model = model;
  62964. this.shapeId = shapeId;
  62965. this.idxInShape = idxInShape;
  62966. this._sps = sps;
  62967. if (modelBoundingInfo) {
  62968. this._modelBoundingInfo = modelBoundingInfo;
  62969. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62970. }
  62971. }
  62972. Object.defineProperty(SolidParticle.prototype, "scale", {
  62973. /**
  62974. * Legacy support, changed scale to scaling
  62975. */
  62976. get: function () {
  62977. return this.scaling;
  62978. },
  62979. /**
  62980. * Legacy support, changed scale to scaling
  62981. */
  62982. set: function (scale) {
  62983. this.scaling = scale;
  62984. },
  62985. enumerable: true,
  62986. configurable: true
  62987. });
  62988. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62989. /**
  62990. * Legacy support, changed quaternion to rotationQuaternion
  62991. */
  62992. get: function () {
  62993. return this.rotationQuaternion;
  62994. },
  62995. /**
  62996. * Legacy support, changed quaternion to rotationQuaternion
  62997. */
  62998. set: function (q) {
  62999. this.rotationQuaternion = q;
  63000. },
  63001. enumerable: true,
  63002. configurable: true
  63003. });
  63004. /**
  63005. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  63006. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  63007. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  63008. * @returns true if it intersects
  63009. */
  63010. SolidParticle.prototype.intersectsMesh = function (target) {
  63011. if (!this._boundingInfo || !target._boundingInfo) {
  63012. return false;
  63013. }
  63014. if (this._sps._bSphereOnly) {
  63015. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  63016. }
  63017. return this._boundingInfo.intersects(target._boundingInfo, false);
  63018. };
  63019. return SolidParticle;
  63020. }());
  63021. BABYLON.SolidParticle = SolidParticle;
  63022. /**
  63023. * Represents the shape of the model used by one particle of a solid particle system.
  63024. * SPS internal tool, don't use it manually.
  63025. */
  63026. var ModelShape = /** @class */ (function () {
  63027. /**
  63028. * 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.
  63029. * SPS internal tool, don't use it manually.
  63030. * @hidden
  63031. */
  63032. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  63033. /**
  63034. * length of the shape in the model indices array (internal use)
  63035. * @hidden
  63036. */
  63037. this._indicesLength = 0;
  63038. this.shapeID = id;
  63039. this._shape = shape;
  63040. this._indicesLength = indicesLength;
  63041. this._shapeUV = shapeUV;
  63042. this._positionFunction = posFunction;
  63043. this._vertexFunction = vtxFunction;
  63044. }
  63045. return ModelShape;
  63046. }());
  63047. BABYLON.ModelShape = ModelShape;
  63048. /**
  63049. * Represents a Depth Sorted Particle in the solid particle system.
  63050. */
  63051. var DepthSortedParticle = /** @class */ (function () {
  63052. function DepthSortedParticle() {
  63053. /**
  63054. * Index of the particle in the "indices" array
  63055. */
  63056. this.ind = 0;
  63057. /**
  63058. * Length of the particle shape in the "indices" array
  63059. */
  63060. this.indicesLength = 0;
  63061. /**
  63062. * Squared distance from the particle to the camera
  63063. */
  63064. this.sqDistance = 0.0;
  63065. }
  63066. return DepthSortedParticle;
  63067. }());
  63068. BABYLON.DepthSortedParticle = DepthSortedParticle;
  63069. })(BABYLON || (BABYLON = {}));
  63070. //# sourceMappingURL=babylon.solidParticle.js.map
  63071. var BABYLON;
  63072. (function (BABYLON) {
  63073. /**
  63074. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  63075. *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.
  63076. * The SPS is also a particle system. It provides some methods to manage the particles.
  63077. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  63078. *
  63079. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  63080. */
  63081. var SolidParticleSystem = /** @class */ (function () {
  63082. /**
  63083. * Creates a SPS (Solid Particle System) object.
  63084. * @param name (String) is the SPS name, this will be the underlying mesh name.
  63085. * @param scene (Scene) is the scene in which the SPS is added.
  63086. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  63087. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  63088. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  63089. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  63090. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  63091. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  63092. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  63093. */
  63094. function SolidParticleSystem(name, scene, options) {
  63095. /**
  63096. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  63097. * Example : var p = SPS.particles[i];
  63098. */
  63099. this.particles = new Array();
  63100. /**
  63101. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  63102. */
  63103. this.nbParticles = 0;
  63104. /**
  63105. * If the particles must ever face the camera (default false). Useful for planar particles.
  63106. */
  63107. this.billboard = false;
  63108. /**
  63109. * Recompute normals when adding a shape
  63110. */
  63111. this.recomputeNormals = true;
  63112. /**
  63113. * This a counter ofr your own usage. It's not set by any SPS functions.
  63114. */
  63115. this.counter = 0;
  63116. /**
  63117. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  63118. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  63119. */
  63120. this.vars = {};
  63121. /**
  63122. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  63123. * @hidden
  63124. */
  63125. this._bSphereOnly = false;
  63126. /**
  63127. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  63128. * @hidden
  63129. */
  63130. this._bSphereRadiusFactor = 1.0;
  63131. this._positions = new Array();
  63132. this._indices = new Array();
  63133. this._normals = new Array();
  63134. this._colors = new Array();
  63135. this._uvs = new Array();
  63136. this._index = 0; // indices index
  63137. this._updatable = true;
  63138. this._pickable = false;
  63139. this._isVisibilityBoxLocked = false;
  63140. this._alwaysVisible = false;
  63141. this._depthSort = false;
  63142. this._shapeCounter = 0;
  63143. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  63144. this._color = new BABYLON.Color4(0, 0, 0, 0);
  63145. this._computeParticleColor = true;
  63146. this._computeParticleTexture = true;
  63147. this._computeParticleRotation = true;
  63148. this._computeParticleVertex = false;
  63149. this._computeBoundingBox = false;
  63150. this._depthSortParticles = true;
  63151. this._cam_axisZ = BABYLON.Vector3.Zero();
  63152. this._cam_axisY = BABYLON.Vector3.Zero();
  63153. this._cam_axisX = BABYLON.Vector3.Zero();
  63154. this._axisZ = BABYLON.Axis.Z;
  63155. this._camDir = BABYLON.Vector3.Zero();
  63156. this._camInvertedPosition = BABYLON.Vector3.Zero();
  63157. this._rotMatrix = new BABYLON.Matrix();
  63158. this._invertMatrix = new BABYLON.Matrix();
  63159. this._rotated = BABYLON.Vector3.Zero();
  63160. this._quaternion = new BABYLON.Quaternion();
  63161. this._vertex = BABYLON.Vector3.Zero();
  63162. this._normal = BABYLON.Vector3.Zero();
  63163. this._yaw = 0.0;
  63164. this._pitch = 0.0;
  63165. this._roll = 0.0;
  63166. this._halfroll = 0.0;
  63167. this._halfpitch = 0.0;
  63168. this._halfyaw = 0.0;
  63169. this._sinRoll = 0.0;
  63170. this._cosRoll = 0.0;
  63171. this._sinPitch = 0.0;
  63172. this._cosPitch = 0.0;
  63173. this._sinYaw = 0.0;
  63174. this._cosYaw = 0.0;
  63175. this._mustUnrotateFixedNormals = false;
  63176. this._minimum = BABYLON.Vector3.Zero();
  63177. this._maximum = BABYLON.Vector3.Zero();
  63178. this._minBbox = BABYLON.Vector3.Zero();
  63179. this._maxBbox = BABYLON.Vector3.Zero();
  63180. this._particlesIntersect = false;
  63181. this._depthSortFunction = function (p1, p2) {
  63182. return (p2.sqDistance - p1.sqDistance);
  63183. };
  63184. this._needs32Bits = false;
  63185. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  63186. this._scaledPivot = BABYLON.Vector3.Zero();
  63187. this._particleHasParent = false;
  63188. this.name = name;
  63189. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63190. this._camera = scene.activeCamera;
  63191. this._pickable = options ? options.isPickable : false;
  63192. this._depthSort = options ? options.enableDepthSort : false;
  63193. this._particlesIntersect = options ? options.particleIntersection : false;
  63194. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  63195. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  63196. if (options && options.updatable !== undefined) {
  63197. this._updatable = options.updatable;
  63198. }
  63199. else {
  63200. this._updatable = true;
  63201. }
  63202. if (this._pickable) {
  63203. this.pickedParticles = [];
  63204. }
  63205. if (this._depthSort) {
  63206. this.depthSortedParticles = [];
  63207. }
  63208. }
  63209. /**
  63210. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63211. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63212. * @returns the created mesh
  63213. */
  63214. SolidParticleSystem.prototype.buildMesh = function () {
  63215. if (this.nbParticles === 0) {
  63216. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63217. this.addShape(triangle, 1);
  63218. triangle.dispose();
  63219. }
  63220. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63221. this._positions32 = new Float32Array(this._positions);
  63222. this._uvs32 = new Float32Array(this._uvs);
  63223. this._colors32 = new Float32Array(this._colors);
  63224. if (this.recomputeNormals) {
  63225. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63226. }
  63227. this._normals32 = new Float32Array(this._normals);
  63228. this._fixedNormal32 = new Float32Array(this._normals);
  63229. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63230. this._unrotateFixedNormals();
  63231. }
  63232. var vertexData = new BABYLON.VertexData();
  63233. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63234. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63235. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63236. if (this._uvs32.length > 0) {
  63237. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63238. }
  63239. if (this._colors32.length > 0) {
  63240. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63241. }
  63242. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63243. vertexData.applyToMesh(mesh, this._updatable);
  63244. this.mesh = mesh;
  63245. this.mesh.isPickable = this._pickable;
  63246. // free memory
  63247. if (!this._depthSort) {
  63248. this._indices = null;
  63249. }
  63250. this._positions = null;
  63251. this._normals = null;
  63252. this._uvs = null;
  63253. this._colors = null;
  63254. if (!this._updatable) {
  63255. this.particles.length = 0;
  63256. }
  63257. return mesh;
  63258. };
  63259. /**
  63260. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63261. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63262. * Thus the particles generated from `digest()` have their property `position` set yet.
  63263. * @param mesh ( Mesh ) is the mesh to be digested
  63264. * @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
  63265. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63266. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63267. * @returns the current SPS
  63268. */
  63269. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63270. var size = (options && options.facetNb) || 1;
  63271. var number = (options && options.number) || 0;
  63272. var delta = (options && options.delta) || 0;
  63273. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63274. var meshInd = mesh.getIndices();
  63275. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63276. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63277. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63278. var f = 0; // facet counter
  63279. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63280. // compute size from number
  63281. if (number) {
  63282. number = (number > totalFacets) ? totalFacets : number;
  63283. size = Math.round(totalFacets / number);
  63284. delta = 0;
  63285. }
  63286. else {
  63287. size = (size > totalFacets) ? totalFacets : size;
  63288. }
  63289. var facetPos = []; // submesh positions
  63290. var facetInd = []; // submesh indices
  63291. var facetUV = []; // submesh UV
  63292. var facetCol = []; // submesh colors
  63293. var barycenter = BABYLON.Vector3.Zero();
  63294. var sizeO = size;
  63295. while (f < totalFacets) {
  63296. size = sizeO + Math.floor((1 + delta) * Math.random());
  63297. if (f > totalFacets - size) {
  63298. size = totalFacets - f;
  63299. }
  63300. // reset temp arrays
  63301. facetPos.length = 0;
  63302. facetInd.length = 0;
  63303. facetUV.length = 0;
  63304. facetCol.length = 0;
  63305. // iterate over "size" facets
  63306. var fi = 0;
  63307. for (var j = f * 3; j < (f + size) * 3; j++) {
  63308. facetInd.push(fi);
  63309. var i = meshInd[j];
  63310. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63311. if (meshUV) {
  63312. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63313. }
  63314. if (meshCol) {
  63315. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63316. }
  63317. fi++;
  63318. }
  63319. // create a model shape for each single particle
  63320. var idx = this.nbParticles;
  63321. var shape = this._posToShape(facetPos);
  63322. var shapeUV = this._uvsToShapeUV(facetUV);
  63323. // compute the barycenter of the shape
  63324. var v;
  63325. for (v = 0; v < shape.length; v++) {
  63326. barycenter.addInPlace(shape[v]);
  63327. }
  63328. barycenter.scaleInPlace(1 / shape.length);
  63329. // shift the shape from its barycenter to the origin
  63330. for (v = 0; v < shape.length; v++) {
  63331. shape[v].subtractInPlace(barycenter);
  63332. }
  63333. var bInfo;
  63334. if (this._particlesIntersect) {
  63335. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63336. }
  63337. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63338. // add the particle in the SPS
  63339. var currentPos = this._positions.length;
  63340. var currentInd = this._indices.length;
  63341. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63342. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63343. // initialize the particle position
  63344. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63345. this._index += shape.length;
  63346. idx++;
  63347. this.nbParticles++;
  63348. this._shapeCounter++;
  63349. f += size;
  63350. }
  63351. return this;
  63352. };
  63353. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63354. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63355. var index = 0;
  63356. var idx = 0;
  63357. for (var p = 0; p < this.particles.length; p++) {
  63358. this._particle = this.particles[p];
  63359. this._shape = this._particle._model._shape;
  63360. if (this._particle.rotationQuaternion) {
  63361. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63362. }
  63363. else {
  63364. this._yaw = this._particle.rotation.y;
  63365. this._pitch = this._particle.rotation.x;
  63366. this._roll = this._particle.rotation.z;
  63367. this._quaternionRotationYPR();
  63368. }
  63369. this._quaternionToRotationMatrix();
  63370. this._rotMatrix.invertToRef(this._invertMatrix);
  63371. for (var pt = 0; pt < this._shape.length; pt++) {
  63372. idx = index + pt * 3;
  63373. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63374. this._fixedNormal32[idx] = this._normal.x;
  63375. this._fixedNormal32[idx + 1] = this._normal.y;
  63376. this._fixedNormal32[idx + 2] = this._normal.z;
  63377. }
  63378. index = idx + 3;
  63379. }
  63380. };
  63381. //reset copy
  63382. SolidParticleSystem.prototype._resetCopy = function () {
  63383. this._copy.position.x = 0;
  63384. this._copy.position.y = 0;
  63385. this._copy.position.z = 0;
  63386. this._copy.rotation.x = 0;
  63387. this._copy.rotation.y = 0;
  63388. this._copy.rotation.z = 0;
  63389. this._copy.rotationQuaternion = null;
  63390. this._copy.scaling.x = 1.0;
  63391. this._copy.scaling.y = 1.0;
  63392. this._copy.scaling.z = 1.0;
  63393. this._copy.uvs.x = 0;
  63394. this._copy.uvs.y = 0;
  63395. this._copy.uvs.z = 1.0;
  63396. this._copy.uvs.w = 1.0;
  63397. this._copy.color = null;
  63398. this._copy.translateFromPivot = false;
  63399. };
  63400. // _meshBuilder : inserts the shape model in the global SPS mesh
  63401. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63402. var i;
  63403. var u = 0;
  63404. var c = 0;
  63405. var n = 0;
  63406. this._resetCopy();
  63407. if (options && options.positionFunction) { // call to custom positionFunction
  63408. options.positionFunction(this._copy, idx, idxInShape);
  63409. this._mustUnrotateFixedNormals = true;
  63410. }
  63411. if (this._copy.rotationQuaternion) {
  63412. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63413. }
  63414. else {
  63415. this._yaw = this._copy.rotation.y;
  63416. this._pitch = this._copy.rotation.x;
  63417. this._roll = this._copy.rotation.z;
  63418. this._quaternionRotationYPR();
  63419. }
  63420. this._quaternionToRotationMatrix();
  63421. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63422. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63423. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63424. if (this._copy.translateFromPivot) {
  63425. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63426. }
  63427. else {
  63428. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63429. }
  63430. for (i = 0; i < shape.length; i++) {
  63431. this._vertex.x = shape[i].x;
  63432. this._vertex.y = shape[i].y;
  63433. this._vertex.z = shape[i].z;
  63434. if (options && options.vertexFunction) {
  63435. options.vertexFunction(this._copy, this._vertex, i);
  63436. }
  63437. this._vertex.x *= this._copy.scaling.x;
  63438. this._vertex.y *= this._copy.scaling.y;
  63439. this._vertex.z *= this._copy.scaling.z;
  63440. this._vertex.x -= this._scaledPivot.x;
  63441. this._vertex.y -= this._scaledPivot.y;
  63442. this._vertex.z -= this._scaledPivot.z;
  63443. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63444. this._rotated.addInPlace(this._pivotBackTranslation);
  63445. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63446. if (meshUV) {
  63447. 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);
  63448. u += 2;
  63449. }
  63450. if (this._copy.color) {
  63451. this._color = this._copy.color;
  63452. }
  63453. else if (meshCol && meshCol[c] !== undefined) {
  63454. this._color.r = meshCol[c];
  63455. this._color.g = meshCol[c + 1];
  63456. this._color.b = meshCol[c + 2];
  63457. this._color.a = meshCol[c + 3];
  63458. }
  63459. else {
  63460. this._color.r = 1.0;
  63461. this._color.g = 1.0;
  63462. this._color.b = 1.0;
  63463. this._color.a = 1.0;
  63464. }
  63465. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63466. c += 4;
  63467. if (!this.recomputeNormals && meshNor) {
  63468. this._normal.x = meshNor[n];
  63469. this._normal.y = meshNor[n + 1];
  63470. this._normal.z = meshNor[n + 2];
  63471. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63472. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63473. n += 3;
  63474. }
  63475. }
  63476. for (i = 0; i < meshInd.length; i++) {
  63477. var current_ind = p + meshInd[i];
  63478. indices.push(current_ind);
  63479. if (current_ind > 65535) {
  63480. this._needs32Bits = true;
  63481. }
  63482. }
  63483. if (this._pickable) {
  63484. var nbfaces = meshInd.length / 3;
  63485. for (i = 0; i < nbfaces; i++) {
  63486. this.pickedParticles.push({ idx: idx, faceId: i });
  63487. }
  63488. }
  63489. if (this._depthSort) {
  63490. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63491. }
  63492. return this._copy;
  63493. };
  63494. // returns a shape array from positions array
  63495. SolidParticleSystem.prototype._posToShape = function (positions) {
  63496. var shape = [];
  63497. for (var i = 0; i < positions.length; i += 3) {
  63498. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63499. }
  63500. return shape;
  63501. };
  63502. // returns a shapeUV array from a Vector4 uvs
  63503. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63504. var shapeUV = [];
  63505. if (uvs) {
  63506. for (var i = 0; i < uvs.length; i++)
  63507. shapeUV.push(uvs[i]);
  63508. }
  63509. return shapeUV;
  63510. };
  63511. // adds a new particle object in the particles array
  63512. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63513. if (bInfo === void 0) { bInfo = null; }
  63514. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63515. this.particles.push(sp);
  63516. return sp;
  63517. };
  63518. /**
  63519. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63520. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63521. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63522. * @param nb (positive integer) the number of particles to be created from this model
  63523. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63524. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63525. * @returns the number of shapes in the system
  63526. */
  63527. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63528. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63529. var meshInd = mesh.getIndices();
  63530. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63531. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63532. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63533. var bbInfo;
  63534. if (this._particlesIntersect) {
  63535. bbInfo = mesh.getBoundingInfo();
  63536. }
  63537. var shape = this._posToShape(meshPos);
  63538. var shapeUV = this._uvsToShapeUV(meshUV);
  63539. var posfunc = options ? options.positionFunction : null;
  63540. var vtxfunc = options ? options.vertexFunction : null;
  63541. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63542. // particles
  63543. var sp;
  63544. var currentCopy;
  63545. var idx = this.nbParticles;
  63546. for (var i = 0; i < nb; i++) {
  63547. var currentPos = this._positions.length;
  63548. var currentInd = this._indices.length;
  63549. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63550. if (this._updatable) {
  63551. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63552. sp.position.copyFrom(currentCopy.position);
  63553. sp.rotation.copyFrom(currentCopy.rotation);
  63554. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63555. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63556. }
  63557. if (currentCopy.color && sp.color) {
  63558. sp.color.copyFrom(currentCopy.color);
  63559. }
  63560. sp.scaling.copyFrom(currentCopy.scaling);
  63561. sp.uvs.copyFrom(currentCopy.uvs);
  63562. }
  63563. this._index += shape.length;
  63564. idx++;
  63565. }
  63566. this.nbParticles += nb;
  63567. this._shapeCounter++;
  63568. return this._shapeCounter - 1;
  63569. };
  63570. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63571. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63572. this._resetCopy();
  63573. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63574. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63575. }
  63576. if (this._copy.rotationQuaternion) {
  63577. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63578. }
  63579. else {
  63580. this._yaw = this._copy.rotation.y;
  63581. this._pitch = this._copy.rotation.x;
  63582. this._roll = this._copy.rotation.z;
  63583. this._quaternionRotationYPR();
  63584. }
  63585. this._quaternionToRotationMatrix();
  63586. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63587. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63588. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63589. if (this._copy.translateFromPivot) {
  63590. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63591. }
  63592. else {
  63593. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63594. }
  63595. this._shape = particle._model._shape;
  63596. for (var pt = 0; pt < this._shape.length; pt++) {
  63597. this._vertex.x = this._shape[pt].x;
  63598. this._vertex.y = this._shape[pt].y;
  63599. this._vertex.z = this._shape[pt].z;
  63600. if (particle._model._vertexFunction) {
  63601. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63602. }
  63603. this._vertex.x *= this._copy.scaling.x;
  63604. this._vertex.y *= this._copy.scaling.y;
  63605. this._vertex.z *= this._copy.scaling.z;
  63606. this._vertex.x -= this._scaledPivot.x;
  63607. this._vertex.y -= this._scaledPivot.y;
  63608. this._vertex.z -= this._scaledPivot.z;
  63609. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63610. this._rotated.addInPlace(this._pivotBackTranslation);
  63611. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63612. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63613. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63614. }
  63615. particle.position.x = 0.0;
  63616. particle.position.y = 0.0;
  63617. particle.position.z = 0.0;
  63618. particle.rotation.x = 0.0;
  63619. particle.rotation.y = 0.0;
  63620. particle.rotation.z = 0.0;
  63621. particle.rotationQuaternion = null;
  63622. particle.scaling.x = 1.0;
  63623. particle.scaling.y = 1.0;
  63624. particle.scaling.z = 1.0;
  63625. particle.uvs.x = 0.0;
  63626. particle.uvs.y = 0.0;
  63627. particle.uvs.z = 1.0;
  63628. particle.uvs.w = 1.0;
  63629. particle.pivot.x = 0.0;
  63630. particle.pivot.y = 0.0;
  63631. particle.pivot.z = 0.0;
  63632. particle.translateFromPivot = false;
  63633. particle.parentId = null;
  63634. };
  63635. /**
  63636. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63637. * @returns the SPS.
  63638. */
  63639. SolidParticleSystem.prototype.rebuildMesh = function () {
  63640. for (var p = 0; p < this.particles.length; p++) {
  63641. this._rebuildParticle(this.particles[p]);
  63642. }
  63643. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63644. return this;
  63645. };
  63646. /**
  63647. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63648. * This method calls `updateParticle()` for each particle of the SPS.
  63649. * For an animated SPS, it is usually called within the render loop.
  63650. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63651. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63652. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63653. * @returns the SPS.
  63654. */
  63655. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63656. if (start === void 0) { start = 0; }
  63657. if (end === void 0) { end = this.nbParticles - 1; }
  63658. if (update === void 0) { update = true; }
  63659. if (!this._updatable) {
  63660. return this;
  63661. }
  63662. // custom beforeUpdate
  63663. this.beforeUpdateParticles(start, end, update);
  63664. this._cam_axisX.x = 1.0;
  63665. this._cam_axisX.y = 0.0;
  63666. this._cam_axisX.z = 0.0;
  63667. this._cam_axisY.x = 0.0;
  63668. this._cam_axisY.y = 1.0;
  63669. this._cam_axisY.z = 0.0;
  63670. this._cam_axisZ.x = 0.0;
  63671. this._cam_axisZ.y = 0.0;
  63672. this._cam_axisZ.z = 1.0;
  63673. // cases when the World Matrix is to be computed first
  63674. if (this.billboard || this._depthSort) {
  63675. this.mesh.computeWorldMatrix(true);
  63676. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63677. }
  63678. // if the particles will always face the camera
  63679. if (this.billboard) {
  63680. // compute the camera position and un-rotate it by the current mesh rotation
  63681. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63682. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63683. this._cam_axisZ.normalize();
  63684. // same for camera up vector extracted from the cam view matrix
  63685. var view = this._camera.getViewMatrix(true);
  63686. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63687. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63688. this._cam_axisY.normalize();
  63689. this._cam_axisX.normalize();
  63690. }
  63691. // if depthSort, compute the camera global position in the mesh local system
  63692. if (this._depthSort) {
  63693. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63694. }
  63695. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63696. var idx = 0; // current position index in the global array positions32
  63697. var index = 0; // position start index in the global array positions32 of the current particle
  63698. var colidx = 0; // current color index in the global array colors32
  63699. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63700. var uvidx = 0; // current uv index in the global array uvs32
  63701. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63702. var pt = 0; // current index in the particle model shape
  63703. if (this.mesh.isFacetDataEnabled) {
  63704. this._computeBoundingBox = true;
  63705. }
  63706. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63707. if (this._computeBoundingBox) {
  63708. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63709. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63710. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63711. }
  63712. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63713. if (this.mesh._boundingInfo) {
  63714. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63715. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63716. }
  63717. }
  63718. }
  63719. // particle loop
  63720. index = this.particles[start]._pos;
  63721. var vpos = (index / 3) | 0;
  63722. colorIndex = vpos * 4;
  63723. uvIndex = vpos * 2;
  63724. for (var p = start; p <= end; p++) {
  63725. this._particle = this.particles[p];
  63726. this._shape = this._particle._model._shape;
  63727. this._shapeUV = this._particle._model._shapeUV;
  63728. // call to custom user function to update the particle properties
  63729. this.updateParticle(this._particle);
  63730. // camera-particle distance for depth sorting
  63731. if (this._depthSort && this._depthSortParticles) {
  63732. var dsp = this.depthSortedParticles[p];
  63733. dsp.ind = this._particle._ind;
  63734. dsp.indicesLength = this._particle._model._indicesLength;
  63735. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63736. }
  63737. // skip the computations for inactive or already invisible particles
  63738. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63739. // increment indexes for the next particle
  63740. pt = this._shape.length;
  63741. index += pt * 3;
  63742. colorIndex += pt * 4;
  63743. uvIndex += pt * 2;
  63744. continue;
  63745. }
  63746. if (this._particle.isVisible) {
  63747. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63748. this._particleHasParent = (this._particle.parentId !== null);
  63749. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63750. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63751. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63752. // particle rotation matrix
  63753. if (this.billboard) {
  63754. this._particle.rotation.x = 0.0;
  63755. this._particle.rotation.y = 0.0;
  63756. }
  63757. if (this._computeParticleRotation || this.billboard) {
  63758. if (this._particle.rotationQuaternion) {
  63759. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63760. }
  63761. else {
  63762. this._yaw = this._particle.rotation.y;
  63763. this._pitch = this._particle.rotation.x;
  63764. this._roll = this._particle.rotation.z;
  63765. this._quaternionRotationYPR();
  63766. }
  63767. this._quaternionToRotationMatrix();
  63768. }
  63769. if (this._particleHasParent) {
  63770. this._parent = this.particles[this._particle.parentId];
  63771. 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];
  63772. 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];
  63773. 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];
  63774. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63775. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63776. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63777. if (this._computeParticleRotation || this.billboard) {
  63778. 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];
  63779. 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];
  63780. 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];
  63781. 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];
  63782. 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];
  63783. 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];
  63784. 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];
  63785. 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];
  63786. 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];
  63787. }
  63788. }
  63789. else {
  63790. this._particle._globalPosition.x = this._particle.position.x;
  63791. this._particle._globalPosition.y = this._particle.position.y;
  63792. this._particle._globalPosition.z = this._particle.position.z;
  63793. if (this._computeParticleRotation || this.billboard) {
  63794. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63795. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63796. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63797. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63798. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63799. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63800. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63801. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63802. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63803. }
  63804. }
  63805. if (this._particle.translateFromPivot) {
  63806. this._pivotBackTranslation.x = 0.0;
  63807. this._pivotBackTranslation.y = 0.0;
  63808. this._pivotBackTranslation.z = 0.0;
  63809. }
  63810. else {
  63811. this._pivotBackTranslation.x = this._scaledPivot.x;
  63812. this._pivotBackTranslation.y = this._scaledPivot.y;
  63813. this._pivotBackTranslation.z = this._scaledPivot.z;
  63814. }
  63815. // particle vertex loop
  63816. for (pt = 0; pt < this._shape.length; pt++) {
  63817. idx = index + pt * 3;
  63818. colidx = colorIndex + pt * 4;
  63819. uvidx = uvIndex + pt * 2;
  63820. this._vertex.x = this._shape[pt].x;
  63821. this._vertex.y = this._shape[pt].y;
  63822. this._vertex.z = this._shape[pt].z;
  63823. if (this._computeParticleVertex) {
  63824. this.updateParticleVertex(this._particle, this._vertex, pt);
  63825. }
  63826. // positions
  63827. this._vertex.x *= this._particle.scaling.x;
  63828. this._vertex.y *= this._particle.scaling.y;
  63829. this._vertex.z *= this._particle.scaling.z;
  63830. this._vertex.x -= this._scaledPivot.x;
  63831. this._vertex.y -= this._scaledPivot.y;
  63832. this._vertex.z -= this._scaledPivot.z;
  63833. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63834. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63835. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63836. this._rotated.x += this._pivotBackTranslation.x;
  63837. this._rotated.y += this._pivotBackTranslation.y;
  63838. this._rotated.z += this._pivotBackTranslation.z;
  63839. 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;
  63840. 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;
  63841. 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;
  63842. if (this._computeBoundingBox) {
  63843. if (this._positions32[idx] < this._minimum.x) {
  63844. this._minimum.x = this._positions32[idx];
  63845. }
  63846. if (this._positions32[idx] > this._maximum.x) {
  63847. this._maximum.x = this._positions32[idx];
  63848. }
  63849. if (this._positions32[idx + 1] < this._minimum.y) {
  63850. this._minimum.y = this._positions32[idx + 1];
  63851. }
  63852. if (this._positions32[idx + 1] > this._maximum.y) {
  63853. this._maximum.y = this._positions32[idx + 1];
  63854. }
  63855. if (this._positions32[idx + 2] < this._minimum.z) {
  63856. this._minimum.z = this._positions32[idx + 2];
  63857. }
  63858. if (this._positions32[idx + 2] > this._maximum.z) {
  63859. this._maximum.z = this._positions32[idx + 2];
  63860. }
  63861. }
  63862. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63863. if (!this._computeParticleVertex) {
  63864. this._normal.x = this._fixedNormal32[idx];
  63865. this._normal.y = this._fixedNormal32[idx + 1];
  63866. this._normal.z = this._fixedNormal32[idx + 2];
  63867. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63868. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63869. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63870. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63871. 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;
  63872. 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;
  63873. }
  63874. if (this._computeParticleColor && this._particle.color) {
  63875. this._colors32[colidx] = this._particle.color.r;
  63876. this._colors32[colidx + 1] = this._particle.color.g;
  63877. this._colors32[colidx + 2] = this._particle.color.b;
  63878. this._colors32[colidx + 3] = this._particle.color.a;
  63879. }
  63880. if (this._computeParticleTexture) {
  63881. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63882. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63883. }
  63884. }
  63885. }
  63886. // particle just set invisible : scaled to zero and positioned at the origin
  63887. else {
  63888. this._particle._stillInvisible = true; // mark the particle as invisible
  63889. for (pt = 0; pt < this._shape.length; pt++) {
  63890. idx = index + pt * 3;
  63891. colidx = colorIndex + pt * 4;
  63892. uvidx = uvIndex + pt * 2;
  63893. this._positions32[idx] = 0.0;
  63894. this._positions32[idx + 1] = 0.0;
  63895. this._positions32[idx + 2] = 0.0;
  63896. this._normals32[idx] = 0.0;
  63897. this._normals32[idx + 1] = 0.0;
  63898. this._normals32[idx + 2] = 0.0;
  63899. if (this._computeParticleColor && this._particle.color) {
  63900. this._colors32[colidx] = this._particle.color.r;
  63901. this._colors32[colidx + 1] = this._particle.color.g;
  63902. this._colors32[colidx + 2] = this._particle.color.b;
  63903. this._colors32[colidx + 3] = this._particle.color.a;
  63904. }
  63905. if (this._computeParticleTexture) {
  63906. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63907. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63908. }
  63909. }
  63910. }
  63911. // if the particle intersections must be computed : update the bbInfo
  63912. if (this._particlesIntersect) {
  63913. var bInfo = this._particle._boundingInfo;
  63914. var bBox = bInfo.boundingBox;
  63915. var bSphere = bInfo.boundingSphere;
  63916. if (!this._bSphereOnly) {
  63917. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63918. for (var b = 0; b < bBox.vectors.length; b++) {
  63919. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63920. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63921. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63922. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63923. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63924. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63925. 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;
  63926. 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;
  63927. 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;
  63928. }
  63929. bBox._update(this.mesh._worldMatrix);
  63930. }
  63931. // place and scale the particle bouding sphere in the SPS local system, then update it
  63932. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63933. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63934. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63935. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63936. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63937. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63938. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63939. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63940. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63941. 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));
  63942. bSphere._update(this.mesh._worldMatrix);
  63943. }
  63944. // increment indexes for the next particle
  63945. index = idx + 3;
  63946. colorIndex = colidx + 4;
  63947. uvIndex = uvidx + 2;
  63948. }
  63949. // if the VBO must be updated
  63950. if (update) {
  63951. if (this._computeParticleColor) {
  63952. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63953. }
  63954. if (this._computeParticleTexture) {
  63955. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63956. }
  63957. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63958. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63959. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63960. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63961. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63962. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63963. for (var i = 0; i < this._normals32.length; i++) {
  63964. this._fixedNormal32[i] = this._normals32[i];
  63965. }
  63966. }
  63967. if (!this.mesh.areNormalsFrozen) {
  63968. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63969. }
  63970. }
  63971. if (this._depthSort && this._depthSortParticles) {
  63972. this.depthSortedParticles.sort(this._depthSortFunction);
  63973. var dspl = this.depthSortedParticles.length;
  63974. var sorted = 0;
  63975. var lind = 0;
  63976. var sind = 0;
  63977. var sid = 0;
  63978. for (sorted = 0; sorted < dspl; sorted++) {
  63979. lind = this.depthSortedParticles[sorted].indicesLength;
  63980. sind = this.depthSortedParticles[sorted].ind;
  63981. for (var i = 0; i < lind; i++) {
  63982. this._indices32[sid] = this._indices[sind + i];
  63983. sid++;
  63984. }
  63985. }
  63986. this.mesh.updateIndices(this._indices32);
  63987. }
  63988. }
  63989. if (this._computeBoundingBox) {
  63990. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63991. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63992. }
  63993. this.afterUpdateParticles(start, end, update);
  63994. return this;
  63995. };
  63996. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63997. this._halfroll = this._roll * 0.5;
  63998. this._halfpitch = this._pitch * 0.5;
  63999. this._halfyaw = this._yaw * 0.5;
  64000. this._sinRoll = Math.sin(this._halfroll);
  64001. this._cosRoll = Math.cos(this._halfroll);
  64002. this._sinPitch = Math.sin(this._halfpitch);
  64003. this._cosPitch = Math.cos(this._halfpitch);
  64004. this._sinYaw = Math.sin(this._halfyaw);
  64005. this._cosYaw = Math.cos(this._halfyaw);
  64006. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  64007. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  64008. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  64009. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  64010. };
  64011. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  64012. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  64013. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  64014. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  64015. this._rotMatrix.m[3] = 0;
  64016. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  64017. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  64018. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  64019. this._rotMatrix.m[7] = 0;
  64020. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  64021. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  64022. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  64023. this._rotMatrix.m[11] = 0;
  64024. this._rotMatrix.m[12] = 0;
  64025. this._rotMatrix.m[13] = 0;
  64026. this._rotMatrix.m[14] = 0;
  64027. this._rotMatrix.m[15] = 1.0;
  64028. };
  64029. /**
  64030. * Disposes the SPS.
  64031. */
  64032. SolidParticleSystem.prototype.dispose = function () {
  64033. this.mesh.dispose();
  64034. this.vars = null;
  64035. // drop references to internal big arrays for the GC
  64036. this._positions = null;
  64037. this._indices = null;
  64038. this._normals = null;
  64039. this._uvs = null;
  64040. this._colors = null;
  64041. this._indices32 = null;
  64042. this._positions32 = null;
  64043. this._normals32 = null;
  64044. this._fixedNormal32 = null;
  64045. this._uvs32 = null;
  64046. this._colors32 = null;
  64047. this.pickedParticles = null;
  64048. };
  64049. /**
  64050. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  64051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64052. * @returns the SPS.
  64053. */
  64054. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  64055. if (!this._isVisibilityBoxLocked) {
  64056. this.mesh.refreshBoundingInfo();
  64057. }
  64058. return this;
  64059. };
  64060. /**
  64061. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  64062. * @param size the size (float) of the visibility box
  64063. * note : this doesn't lock the SPS mesh bounding box.
  64064. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64065. */
  64066. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  64067. var vis = size / 2;
  64068. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  64069. };
  64070. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  64071. /**
  64072. * Gets whether the SPS as always visible or not
  64073. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64074. */
  64075. get: function () {
  64076. return this._alwaysVisible;
  64077. },
  64078. /**
  64079. * Sets the SPS as always visible or not
  64080. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64081. */
  64082. set: function (val) {
  64083. this._alwaysVisible = val;
  64084. this.mesh.alwaysSelectAsActiveMesh = val;
  64085. },
  64086. enumerable: true,
  64087. configurable: true
  64088. });
  64089. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  64090. /**
  64091. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  64092. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64093. */
  64094. get: function () {
  64095. return this._isVisibilityBoxLocked;
  64096. },
  64097. /**
  64098. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  64099. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64100. */
  64101. set: function (val) {
  64102. this._isVisibilityBoxLocked = val;
  64103. var boundingInfo = this.mesh.getBoundingInfo();
  64104. boundingInfo.isLocked = val;
  64105. },
  64106. enumerable: true,
  64107. configurable: true
  64108. });
  64109. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  64110. /**
  64111. * Gets if `setParticles()` computes the particle rotations or not.
  64112. * Default value : true. The SPS is faster when it's set to false.
  64113. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64114. */
  64115. get: function () {
  64116. return this._computeParticleRotation;
  64117. },
  64118. /**
  64119. * Tells to `setParticles()` to compute the particle rotations or not.
  64120. * Default value : true. The SPS is faster when it's set to false.
  64121. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  64122. */
  64123. set: function (val) {
  64124. this._computeParticleRotation = val;
  64125. },
  64126. enumerable: true,
  64127. configurable: true
  64128. });
  64129. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  64130. /**
  64131. * Gets if `setParticles()` computes the particle colors or not.
  64132. * Default value : true. The SPS is faster when it's set to false.
  64133. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64134. */
  64135. get: function () {
  64136. return this._computeParticleColor;
  64137. },
  64138. /**
  64139. * Tells to `setParticles()` to compute the particle colors or not.
  64140. * Default value : true. The SPS is faster when it's set to false.
  64141. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  64142. */
  64143. set: function (val) {
  64144. this._computeParticleColor = val;
  64145. },
  64146. enumerable: true,
  64147. configurable: true
  64148. });
  64149. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  64150. /**
  64151. * Gets if `setParticles()` computes the particle textures or not.
  64152. * Default value : true. The SPS is faster when it's set to false.
  64153. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  64154. */
  64155. get: function () {
  64156. return this._computeParticleTexture;
  64157. },
  64158. set: function (val) {
  64159. this._computeParticleTexture = val;
  64160. },
  64161. enumerable: true,
  64162. configurable: true
  64163. });
  64164. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  64165. /**
  64166. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  64167. * Default value : false. The SPS is faster when it's set to false.
  64168. * Note : the particle custom vertex positions aren't stored values.
  64169. */
  64170. get: function () {
  64171. return this._computeParticleVertex;
  64172. },
  64173. /**
  64174. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  64175. * Default value : false. The SPS is faster when it's set to false.
  64176. * Note : the particle custom vertex positions aren't stored values.
  64177. */
  64178. set: function (val) {
  64179. this._computeParticleVertex = val;
  64180. },
  64181. enumerable: true,
  64182. configurable: true
  64183. });
  64184. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  64185. /**
  64186. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  64187. */
  64188. get: function () {
  64189. return this._computeBoundingBox;
  64190. },
  64191. /**
  64192. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  64193. */
  64194. set: function (val) {
  64195. this._computeBoundingBox = val;
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  64201. /**
  64202. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  64203. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64204. * Default : `true`
  64205. */
  64206. get: function () {
  64207. return this._depthSortParticles;
  64208. },
  64209. /**
  64210. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64211. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64212. * Default : `true`
  64213. */
  64214. set: function (val) {
  64215. this._depthSortParticles = val;
  64216. },
  64217. enumerable: true,
  64218. configurable: true
  64219. });
  64220. // =======================================================================
  64221. // Particle behavior logic
  64222. // these following methods may be overwritten by the user to fit his needs
  64223. /**
  64224. * This function does nothing. It may be overwritten to set all the particle first values.
  64225. * The SPS doesn't call this function, you may have to call it by your own.
  64226. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64227. */
  64228. SolidParticleSystem.prototype.initParticles = function () {
  64229. };
  64230. /**
  64231. * This function does nothing. It may be overwritten to recycle a particle.
  64232. * The SPS doesn't call this function, you may have to call it by your own.
  64233. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64234. * @param particle The particle to recycle
  64235. * @returns the recycled particle
  64236. */
  64237. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64238. return particle;
  64239. };
  64240. /**
  64241. * Updates a particle : this function should be overwritten by the user.
  64242. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64244. * @example : just set a particle position or velocity and recycle conditions
  64245. * @param particle The particle to update
  64246. * @returns the updated particle
  64247. */
  64248. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64249. return particle;
  64250. };
  64251. /**
  64252. * Updates a vertex of a particle : it can be overwritten by the user.
  64253. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64254. * @param particle the current particle
  64255. * @param vertex the current index of the current particle
  64256. * @param pt the index of the current vertex in the particle shape
  64257. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64258. * @example : just set a vertex particle position
  64259. * @returns the updated vertex
  64260. */
  64261. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64262. return vertex;
  64263. };
  64264. /**
  64265. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64266. * This does nothing and may be overwritten by the user.
  64267. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64268. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64269. * @param update the boolean update value actually passed to setParticles()
  64270. */
  64271. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64272. };
  64273. /**
  64274. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64275. * This will be passed three parameters.
  64276. * This does nothing and may be overwritten by the user.
  64277. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64278. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64279. * @param update the boolean update value actually passed to setParticles()
  64280. */
  64281. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64282. };
  64283. return SolidParticleSystem;
  64284. }());
  64285. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64286. })(BABYLON || (BABYLON = {}));
  64287. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64288. var BABYLON;
  64289. (function (BABYLON) {
  64290. /**
  64291. * Class containing static functions to help procedurally build meshes
  64292. */
  64293. var MeshBuilder = /** @class */ (function () {
  64294. function MeshBuilder() {
  64295. }
  64296. MeshBuilder.updateSideOrientation = function (orientation) {
  64297. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64298. return BABYLON.Mesh.DOUBLESIDE;
  64299. }
  64300. if (orientation === undefined || orientation === null) {
  64301. return BABYLON.Mesh.FRONTSIDE;
  64302. }
  64303. return orientation;
  64304. };
  64305. /**
  64306. * Creates a box mesh
  64307. * * The parameter `size` sets the size (float) of each box side (default 1)
  64308. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64309. * * 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)
  64310. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64311. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64312. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  64313. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64315. * @param name defines the name of the mesh
  64316. * @param options defines the options used to create the mesh
  64317. * @param scene defines the hosting scene
  64318. * @returns the box mesh
  64319. */
  64320. MeshBuilder.CreateBox = function (name, options, scene) {
  64321. if (scene === void 0) { scene = null; }
  64322. var box = new BABYLON.Mesh(name, scene);
  64323. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64324. box._originalBuilderSideOrientation = options.sideOrientation;
  64325. var vertexData = BABYLON.VertexData.CreateBox(options);
  64326. vertexData.applyToMesh(box, options.updatable);
  64327. return box;
  64328. };
  64329. /**
  64330. * Creates a sphere mesh
  64331. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64332. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  64333. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64334. * * 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
  64335. * * 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)
  64336. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64337. * * 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
  64338. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64339. * @param name defines the name of the mesh
  64340. * @param options defines the options used to create the mesh
  64341. * @param scene defines the hosting scene
  64342. * @returns the sphere mesh
  64343. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64344. */
  64345. MeshBuilder.CreateSphere = function (name, options, scene) {
  64346. var sphere = new BABYLON.Mesh(name, scene);
  64347. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64348. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64349. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64350. vertexData.applyToMesh(sphere, options.updatable);
  64351. return sphere;
  64352. };
  64353. /**
  64354. * Creates a plane polygonal mesh. By default, this is a disc
  64355. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64356. * * 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
  64357. * * 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
  64358. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64359. * * 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
  64360. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64361. * @param name defines the name of the mesh
  64362. * @param options defines the options used to create the mesh
  64363. * @param scene defines the hosting scene
  64364. * @returns the plane polygonal mesh
  64365. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64366. */
  64367. MeshBuilder.CreateDisc = function (name, options, scene) {
  64368. if (scene === void 0) { scene = null; }
  64369. var disc = new BABYLON.Mesh(name, scene);
  64370. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64371. disc._originalBuilderSideOrientation = options.sideOrientation;
  64372. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64373. vertexData.applyToMesh(disc, options.updatable);
  64374. return disc;
  64375. };
  64376. /**
  64377. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64378. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64379. * * 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`)
  64380. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64381. * * 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
  64382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64383. * * 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
  64384. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64385. * @param name defines the name of the mesh
  64386. * @param options defines the options used to create the mesh
  64387. * @param scene defines the hosting scene
  64388. * @returns the icosahedron mesh
  64389. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64390. */
  64391. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64392. var sphere = new BABYLON.Mesh(name, scene);
  64393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64394. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64395. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64396. vertexData.applyToMesh(sphere, options.updatable);
  64397. return sphere;
  64398. };
  64399. ;
  64400. /**
  64401. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64402. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64403. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64404. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64405. * * 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
  64406. * * 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
  64407. * * 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
  64408. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64409. * * 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
  64410. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64411. * * 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
  64412. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64413. * * 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
  64414. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64415. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64416. * @param name defines the name of the mesh
  64417. * @param options defines the options used to create the mesh
  64418. * @param scene defines the hosting scene
  64419. * @returns the ribbon mesh
  64420. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64421. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64422. */
  64423. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64424. if (scene === void 0) { scene = null; }
  64425. var pathArray = options.pathArray;
  64426. var closeArray = options.closeArray;
  64427. var closePath = options.closePath;
  64428. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64429. var instance = options.instance;
  64430. var updatable = options.updatable;
  64431. if (instance) { // existing ribbon instance update
  64432. // positionFunction : ribbon case
  64433. // only pathArray and sideOrientation parameters are taken into account for positions update
  64434. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64435. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64436. var positionFunction = function (positions) {
  64437. var minlg = pathArray[0].length;
  64438. var i = 0;
  64439. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64440. for (var si = 1; si <= ns; si++) {
  64441. for (var p = 0; p < pathArray.length; p++) {
  64442. var path = pathArray[p];
  64443. var l = path.length;
  64444. minlg = (minlg < l) ? minlg : l;
  64445. var j = 0;
  64446. while (j < minlg) {
  64447. positions[i] = path[j].x;
  64448. positions[i + 1] = path[j].y;
  64449. positions[i + 2] = path[j].z;
  64450. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64451. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64452. }
  64453. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64454. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64455. }
  64456. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64457. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64458. }
  64459. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64460. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64461. }
  64462. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64463. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64464. }
  64465. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64466. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64467. }
  64468. j++;
  64469. i += 3;
  64470. }
  64471. if (instance._closePath) {
  64472. positions[i] = path[0].x;
  64473. positions[i + 1] = path[0].y;
  64474. positions[i + 2] = path[0].z;
  64475. i += 3;
  64476. }
  64477. }
  64478. }
  64479. };
  64480. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64481. positionFunction(positions);
  64482. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64483. instance._boundingInfo.update(instance._worldMatrix);
  64484. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64485. if (options.colors) {
  64486. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64487. for (var c = 0; c < options.colors.length; c++) {
  64488. colors[c * 4] = options.colors[c].r;
  64489. colors[c * 4 + 1] = options.colors[c].g;
  64490. colors[c * 4 + 2] = options.colors[c].b;
  64491. colors[c * 4 + 3] = options.colors[c].a;
  64492. }
  64493. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64494. }
  64495. if (options.uvs) {
  64496. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64497. for (var i = 0; i < options.uvs.length; i++) {
  64498. uvs[i * 2] = options.uvs[i].x;
  64499. uvs[i * 2 + 1] = options.uvs[i].y;
  64500. }
  64501. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64502. }
  64503. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64504. var indices = instance.getIndices();
  64505. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64506. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64507. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64508. if (instance._closePath) {
  64509. var indexFirst = 0;
  64510. var indexLast = 0;
  64511. for (var p = 0; p < pathArray.length; p++) {
  64512. indexFirst = instance._idx[p] * 3;
  64513. if (p + 1 < pathArray.length) {
  64514. indexLast = (instance._idx[p + 1] - 1) * 3;
  64515. }
  64516. else {
  64517. indexLast = normals.length - 3;
  64518. }
  64519. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64520. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64521. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64522. normals[indexLast] = normals[indexFirst];
  64523. normals[indexLast + 1] = normals[indexFirst + 1];
  64524. normals[indexLast + 2] = normals[indexFirst + 2];
  64525. }
  64526. }
  64527. if (!(instance.areNormalsFrozen)) {
  64528. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64529. }
  64530. }
  64531. return instance;
  64532. }
  64533. else { // new ribbon creation
  64534. var ribbon = new BABYLON.Mesh(name, scene);
  64535. ribbon._originalBuilderSideOrientation = sideOrientation;
  64536. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64537. if (closePath) {
  64538. ribbon._idx = vertexData._idx;
  64539. }
  64540. ribbon._closePath = closePath;
  64541. ribbon._closeArray = closeArray;
  64542. vertexData.applyToMesh(ribbon, updatable);
  64543. return ribbon;
  64544. }
  64545. };
  64546. /**
  64547. * Creates a cylinder or a cone mesh
  64548. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64549. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64550. * * 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.
  64551. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64552. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64553. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64554. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64555. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64556. * * 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).
  64557. * * 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
  64558. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64559. * * 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
  64560. * * 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.
  64561. * * If `enclose` is false, a ring surface is one element.
  64562. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64563. * * 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
  64564. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64565. * * 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
  64566. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64567. * @param name defines the name of the mesh
  64568. * @param options defines the options used to create the mesh
  64569. * @param scene defines the hosting scene
  64570. * @returns the cylinder mesh
  64571. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64572. */
  64573. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64574. var cylinder = new BABYLON.Mesh(name, scene);
  64575. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64576. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64577. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64578. vertexData.applyToMesh(cylinder, options.updatable);
  64579. return cylinder;
  64580. };
  64581. /**
  64582. * Creates a torus mesh
  64583. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64584. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64585. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64586. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64587. * * 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
  64588. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64589. * @param name defines the name of the mesh
  64590. * @param options defines the options used to create the mesh
  64591. * @param scene defines the hosting scene
  64592. * @returns the torus mesh
  64593. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64594. */
  64595. MeshBuilder.CreateTorus = function (name, options, scene) {
  64596. var torus = new BABYLON.Mesh(name, scene);
  64597. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64598. torus._originalBuilderSideOrientation = options.sideOrientation;
  64599. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64600. vertexData.applyToMesh(torus, options.updatable);
  64601. return torus;
  64602. };
  64603. /**
  64604. * Creates a torus knot mesh
  64605. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64606. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64607. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64608. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64609. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64610. * * 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
  64611. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64612. * @param name defines the name of the mesh
  64613. * @param options defines the options used to create the mesh
  64614. * @param scene defines the hosting scene
  64615. * @returns the torus knot mesh
  64616. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64617. */
  64618. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64619. var torusKnot = new BABYLON.Mesh(name, scene);
  64620. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64621. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64622. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64623. vertexData.applyToMesh(torusKnot, options.updatable);
  64624. return torusKnot;
  64625. };
  64626. /**
  64627. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64628. * * 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
  64629. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64630. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64631. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64632. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64633. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64634. * * 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
  64635. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64636. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64637. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64638. * @param name defines the name of the new line system
  64639. * @param options defines the options used to create the line system
  64640. * @param scene defines the hosting scene
  64641. * @returns a new line system mesh
  64642. */
  64643. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64644. var instance = options.instance;
  64645. var lines = options.lines;
  64646. var colors = options.colors;
  64647. if (instance) { // lines update
  64648. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64649. var vertexColor;
  64650. var lineColors;
  64651. if (colors) {
  64652. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64653. }
  64654. var i = 0;
  64655. var c = 0;
  64656. for (var l = 0; l < lines.length; l++) {
  64657. var points = lines[l];
  64658. for (var p = 0; p < points.length; p++) {
  64659. positions[i] = points[p].x;
  64660. positions[i + 1] = points[p].y;
  64661. positions[i + 2] = points[p].z;
  64662. if (colors && vertexColor) {
  64663. lineColors = colors[l];
  64664. vertexColor[c] = lineColors[p].r;
  64665. vertexColor[c + 1] = lineColors[p].g;
  64666. vertexColor[c + 2] = lineColors[p].b;
  64667. vertexColor[c + 3] = lineColors[p].a;
  64668. c += 4;
  64669. }
  64670. i += 3;
  64671. }
  64672. }
  64673. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64674. if (colors && vertexColor) {
  64675. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64676. }
  64677. return instance;
  64678. }
  64679. // line system creation
  64680. var useVertexColor = (colors) ? true : false;
  64681. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64682. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64683. vertexData.applyToMesh(lineSystem, options.updatable);
  64684. return lineSystem;
  64685. };
  64686. /**
  64687. * Creates a line mesh
  64688. * 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
  64689. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64690. * * The parameter `points` is an array successive Vector3
  64691. * * 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
  64692. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64693. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64694. * * When updating an instance, remember that only point positions can change, not the number of points
  64695. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64696. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64697. * @param name defines the name of the new line system
  64698. * @param options defines the options used to create the line system
  64699. * @param scene defines the hosting scene
  64700. * @returns a new line mesh
  64701. */
  64702. MeshBuilder.CreateLines = function (name, options, scene) {
  64703. if (scene === void 0) { scene = null; }
  64704. var colors = (options.colors) ? [options.colors] : null;
  64705. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64706. return lines;
  64707. };
  64708. /**
  64709. * Creates a dashed line mesh
  64710. * * 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
  64711. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64712. * * The parameter `points` is an array successive Vector3
  64713. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64714. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64715. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64716. * * 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
  64717. * * When updating an instance, remember that only point positions can change, not the number of points
  64718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64719. * @param name defines the name of the mesh
  64720. * @param options defines the options used to create the mesh
  64721. * @param scene defines the hosting scene
  64722. * @returns the dashed line mesh
  64723. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64724. */
  64725. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64726. if (scene === void 0) { scene = null; }
  64727. var points = options.points;
  64728. var instance = options.instance;
  64729. var gapSize = options.gapSize || 1;
  64730. var dashSize = options.dashSize || 3;
  64731. if (instance) { // dashed lines update
  64732. var positionFunction = function (positions) {
  64733. var curvect = BABYLON.Vector3.Zero();
  64734. var nbSeg = positions.length / 6;
  64735. var lg = 0;
  64736. var nb = 0;
  64737. var shft = 0;
  64738. var dashshft = 0;
  64739. var curshft = 0;
  64740. var p = 0;
  64741. var i = 0;
  64742. var j = 0;
  64743. for (i = 0; i < points.length - 1; i++) {
  64744. points[i + 1].subtractToRef(points[i], curvect);
  64745. lg += curvect.length();
  64746. }
  64747. shft = lg / nbSeg;
  64748. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64749. for (i = 0; i < points.length - 1; i++) {
  64750. points[i + 1].subtractToRef(points[i], curvect);
  64751. nb = Math.floor(curvect.length() / shft);
  64752. curvect.normalize();
  64753. j = 0;
  64754. while (j < nb && p < positions.length) {
  64755. curshft = shft * j;
  64756. positions[p] = points[i].x + curshft * curvect.x;
  64757. positions[p + 1] = points[i].y + curshft * curvect.y;
  64758. positions[p + 2] = points[i].z + curshft * curvect.z;
  64759. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64760. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64761. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64762. p += 6;
  64763. j++;
  64764. }
  64765. }
  64766. while (p < positions.length) {
  64767. positions[p] = points[i].x;
  64768. positions[p + 1] = points[i].y;
  64769. positions[p + 2] = points[i].z;
  64770. p += 3;
  64771. }
  64772. };
  64773. instance.updateMeshPositions(positionFunction, false);
  64774. return instance;
  64775. }
  64776. // dashed lines creation
  64777. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64778. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64779. vertexData.applyToMesh(dashedLines, options.updatable);
  64780. dashedLines.dashSize = dashSize;
  64781. dashedLines.gapSize = gapSize;
  64782. return dashedLines;
  64783. };
  64784. /**
  64785. * 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.
  64786. * * 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.
  64787. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64788. * * 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.
  64789. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64790. * * 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
  64791. * * 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
  64792. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64793. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64794. * * 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
  64795. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64796. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64797. * @param name defines the name of the mesh
  64798. * @param options defines the options used to create the mesh
  64799. * @param scene defines the hosting scene
  64800. * @returns the extruded shape mesh
  64801. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64802. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64803. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64804. */
  64805. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64806. if (scene === void 0) { scene = null; }
  64807. var path = options.path;
  64808. var shape = options.shape;
  64809. var scale = options.scale || 1;
  64810. var rotation = options.rotation || 0;
  64811. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64812. var updatable = options.updatable;
  64813. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64814. var instance = options.instance || null;
  64815. var invertUV = options.invertUV || false;
  64816. 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);
  64817. };
  64818. /**
  64819. * Creates an custom extruded shape mesh.
  64820. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64821. * * 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.
  64822. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64823. * * 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
  64824. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64825. * * 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
  64826. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64827. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64828. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64829. * * 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
  64830. * * 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
  64831. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64832. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64833. * * 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
  64834. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64835. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64836. * @param name defines the name of the mesh
  64837. * @param options defines the options used to create the mesh
  64838. * @param scene defines the hosting scene
  64839. * @returns the custom extruded shape mesh
  64840. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64841. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64842. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64843. */
  64844. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64845. var path = options.path;
  64846. var shape = options.shape;
  64847. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64848. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64849. var ribbonCloseArray = options.ribbonCloseArray || false;
  64850. var ribbonClosePath = options.ribbonClosePath || false;
  64851. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64852. var updatable = options.updatable;
  64853. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64854. var instance = options.instance;
  64855. var invertUV = options.invertUV || false;
  64856. 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);
  64857. };
  64858. /**
  64859. * Creates lathe mesh.
  64860. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64861. * * 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
  64862. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64863. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64864. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64865. * * 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
  64866. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64867. * * 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
  64868. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64869. * * 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
  64870. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64871. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64872. * @param name defines the name of the mesh
  64873. * @param options defines the options used to create the mesh
  64874. * @param scene defines the hosting scene
  64875. * @returns the lathe mesh
  64876. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64877. */
  64878. MeshBuilder.CreateLathe = function (name, options, scene) {
  64879. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64880. var closed = (options.closed === undefined) ? true : options.closed;
  64881. var shape = options.shape;
  64882. var radius = options.radius || 1;
  64883. var tessellation = options.tessellation || 64;
  64884. var clip = options.clip || 0;
  64885. var updatable = options.updatable;
  64886. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64887. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64888. var pi2 = Math.PI * 2;
  64889. var paths = new Array();
  64890. var invertUV = options.invertUV || false;
  64891. var i = 0;
  64892. var p = 0;
  64893. var step = pi2 / tessellation * arc;
  64894. var rotated;
  64895. var path = new Array();
  64896. for (i = 0; i <= tessellation - clip; i++) {
  64897. var path = [];
  64898. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64899. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64900. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64901. }
  64902. for (p = 0; p < shape.length; p++) {
  64903. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64904. path.push(rotated);
  64905. }
  64906. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64907. 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));
  64908. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64909. }
  64910. paths.push(path);
  64911. }
  64912. // lathe ribbon
  64913. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64914. return lathe;
  64915. };
  64916. /**
  64917. * Creates a plane mesh
  64918. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64919. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64920. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64921. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64922. * * 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
  64923. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64924. * @param name defines the name of the mesh
  64925. * @param options defines the options used to create the mesh
  64926. * @param scene defines the hosting scene
  64927. * @returns the plane mesh
  64928. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64929. */
  64930. MeshBuilder.CreatePlane = function (name, options, scene) {
  64931. var plane = new BABYLON.Mesh(name, scene);
  64932. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64933. plane._originalBuilderSideOrientation = options.sideOrientation;
  64934. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64935. vertexData.applyToMesh(plane, options.updatable);
  64936. if (options.sourcePlane) {
  64937. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64938. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64939. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64940. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64941. plane.rotate(vectorProduct, product);
  64942. }
  64943. }
  64944. return plane;
  64945. };
  64946. /**
  64947. * Creates a ground mesh
  64948. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64949. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64950. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64951. * @param name defines the name of the mesh
  64952. * @param options defines the options used to create the mesh
  64953. * @param scene defines the hosting scene
  64954. * @returns the ground mesh
  64955. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64956. */
  64957. MeshBuilder.CreateGround = function (name, options, scene) {
  64958. var ground = new BABYLON.GroundMesh(name, scene);
  64959. ground._setReady(false);
  64960. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64961. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64962. ground._width = options.width || 1;
  64963. ground._height = options.height || 1;
  64964. ground._maxX = ground._width / 2;
  64965. ground._maxZ = ground._height / 2;
  64966. ground._minX = -ground._maxX;
  64967. ground._minZ = -ground._maxZ;
  64968. var vertexData = BABYLON.VertexData.CreateGround(options);
  64969. vertexData.applyToMesh(ground, options.updatable);
  64970. ground._setReady(true);
  64971. return ground;
  64972. };
  64973. /**
  64974. * Creates a tiled ground mesh
  64975. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64976. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64977. * * 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
  64978. * * 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
  64979. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64980. * @param name defines the name of the mesh
  64981. * @param options defines the options used to create the mesh
  64982. * @param scene defines the hosting scene
  64983. * @returns the tiled ground mesh
  64984. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64985. */
  64986. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64987. var tiledGround = new BABYLON.Mesh(name, scene);
  64988. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64989. vertexData.applyToMesh(tiledGround, options.updatable);
  64990. return tiledGround;
  64991. };
  64992. /**
  64993. * Creates a ground mesh from a height map
  64994. * * The parameter `url` sets the URL of the height map image resource.
  64995. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64996. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64997. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64998. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64999. * * 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.
  65000. * * 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).
  65001. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  65002. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65003. * @param name defines the name of the mesh
  65004. * @param url defines the url to the height map
  65005. * @param options defines the options used to create the mesh
  65006. * @param scene defines the hosting scene
  65007. * @returns the ground mesh
  65008. * @see http://doc.babylonjs.com/babylon101/height_map
  65009. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  65010. */
  65011. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  65012. var width = options.width || 10.0;
  65013. var height = options.height || 10.0;
  65014. var subdivisions = options.subdivisions || 1 | 0;
  65015. var minHeight = options.minHeight || 0.0;
  65016. var maxHeight = options.maxHeight || 1.0;
  65017. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  65018. var alphaFilter = options.alphaFilter || 0.0;
  65019. var updatable = options.updatable;
  65020. var onReady = options.onReady;
  65021. var ground = new BABYLON.GroundMesh(name, scene);
  65022. ground._subdivisionsX = subdivisions;
  65023. ground._subdivisionsY = subdivisions;
  65024. ground._width = width;
  65025. ground._height = height;
  65026. ground._maxX = ground._width / 2.0;
  65027. ground._maxZ = ground._height / 2.0;
  65028. ground._minX = -ground._maxX;
  65029. ground._minZ = -ground._maxZ;
  65030. ground._setReady(false);
  65031. var onload = function (img) {
  65032. // Getting height map data
  65033. var canvas = document.createElement("canvas");
  65034. var context = canvas.getContext("2d");
  65035. if (!context) {
  65036. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  65037. }
  65038. if (scene.isDisposed) {
  65039. return;
  65040. }
  65041. var bufferWidth = img.width;
  65042. var bufferHeight = img.height;
  65043. canvas.width = bufferWidth;
  65044. canvas.height = bufferHeight;
  65045. context.drawImage(img, 0, 0);
  65046. // Create VertexData from map data
  65047. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  65048. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  65049. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  65050. width: width, height: height,
  65051. subdivisions: subdivisions,
  65052. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  65053. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  65054. alphaFilter: alphaFilter
  65055. });
  65056. vertexData.applyToMesh(ground, updatable);
  65057. //execute ready callback, if set
  65058. if (onReady) {
  65059. onReady(ground);
  65060. }
  65061. ground._setReady(true);
  65062. };
  65063. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  65064. return ground;
  65065. };
  65066. /**
  65067. * Creates a polygon mesh
  65068. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  65069. * * 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
  65070. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65071. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65072. * * 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)
  65073. * * Remember you can only change the shape positions, not their number when updating a polygon
  65074. * @param name defines the name of the mesh
  65075. * @param options defines the options used to create the mesh
  65076. * @param scene defines the hosting scene
  65077. * @returns the polygon mesh
  65078. */
  65079. MeshBuilder.CreatePolygon = function (name, options, scene) {
  65080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65081. var shape = options.shape;
  65082. var holes = options.holes || [];
  65083. var depth = options.depth || 0;
  65084. var contours = [];
  65085. var hole = [];
  65086. for (var i = 0; i < shape.length; i++) {
  65087. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  65088. }
  65089. var epsilon = 0.00000001;
  65090. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  65091. contours.pop();
  65092. }
  65093. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  65094. for (var hNb = 0; hNb < holes.length; hNb++) {
  65095. hole = [];
  65096. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  65097. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  65098. }
  65099. polygonTriangulation.addHole(hole);
  65100. }
  65101. var polygon = polygonTriangulation.build(options.updatable, depth);
  65102. polygon._originalBuilderSideOrientation = options.sideOrientation;
  65103. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  65104. vertexData.applyToMesh(polygon, options.updatable);
  65105. return polygon;
  65106. };
  65107. ;
  65108. /**
  65109. * Creates an extruded polygon mesh, with depth in the Y direction.
  65110. * * 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)
  65111. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65112. * @param name defines the name of the mesh
  65113. * @param options defines the options used to create the mesh
  65114. * @param scene defines the hosting scene
  65115. * @returns the polygon mesh
  65116. */
  65117. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  65118. return MeshBuilder.CreatePolygon(name, options, scene);
  65119. };
  65120. ;
  65121. /**
  65122. * Creates a tube mesh.
  65123. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65124. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  65125. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  65126. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  65127. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  65128. * * 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)
  65129. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  65130. * * 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
  65131. * * 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
  65132. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65133. * * 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
  65134. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65135. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65136. * @param name defines the name of the mesh
  65137. * @param options defines the options used to create the mesh
  65138. * @param scene defines the hosting scene
  65139. * @returns the tube mesh
  65140. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65141. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  65142. */
  65143. MeshBuilder.CreateTube = function (name, options, scene) {
  65144. var path = options.path;
  65145. var instance = options.instance;
  65146. var radius = 1.0;
  65147. if (instance) {
  65148. radius = instance.radius;
  65149. }
  65150. if (options.radius !== undefined) {
  65151. radius = options.radius;
  65152. }
  65153. ;
  65154. var tessellation = options.tessellation || 64 | 0;
  65155. var radiusFunction = options.radiusFunction || null;
  65156. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65157. var invertUV = options.invertUV || false;
  65158. var updatable = options.updatable;
  65159. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65160. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  65161. // tube geometry
  65162. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  65163. var tangents = path3D.getTangents();
  65164. var normals = path3D.getNormals();
  65165. var distances = path3D.getDistances();
  65166. var pi2 = Math.PI * 2;
  65167. var step = pi2 / tessellation * arc;
  65168. var returnRadius = function () { return radius; };
  65169. var radiusFunctionFinal = radiusFunction || returnRadius;
  65170. var circlePath;
  65171. var rad;
  65172. var normal;
  65173. var rotated;
  65174. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65175. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65176. for (var i = 0; i < path.length; i++) {
  65177. rad = radiusFunctionFinal(i, distances[i]); // current radius
  65178. circlePath = Array(); // current circle array
  65179. normal = normals[i]; // current normal
  65180. for (var t = 0; t < tessellation; t++) {
  65181. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  65182. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  65183. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  65184. rotated.scaleInPlace(rad).addInPlace(path[i]);
  65185. circlePath[t] = rotated;
  65186. }
  65187. circlePaths[index] = circlePath;
  65188. index++;
  65189. }
  65190. // cap
  65191. var capPath = function (nbPoints, pathIndex) {
  65192. var pointCap = Array();
  65193. for (var i = 0; i < nbPoints; i++) {
  65194. pointCap.push(path[pathIndex]);
  65195. }
  65196. return pointCap;
  65197. };
  65198. switch (cap) {
  65199. case BABYLON.Mesh.NO_CAP:
  65200. break;
  65201. case BABYLON.Mesh.CAP_START:
  65202. circlePaths[0] = capPath(tessellation, 0);
  65203. circlePaths[1] = circlePaths[2].slice(0);
  65204. break;
  65205. case BABYLON.Mesh.CAP_END:
  65206. circlePaths[index] = circlePaths[index - 1].slice(0);
  65207. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65208. break;
  65209. case BABYLON.Mesh.CAP_ALL:
  65210. circlePaths[0] = capPath(tessellation, 0);
  65211. circlePaths[1] = circlePaths[2].slice(0);
  65212. circlePaths[index] = circlePaths[index - 1].slice(0);
  65213. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65214. break;
  65215. default:
  65216. break;
  65217. }
  65218. return circlePaths;
  65219. };
  65220. var path3D;
  65221. var pathArray;
  65222. if (instance) { // tube update
  65223. var arc = options.arc || instance.arc;
  65224. path3D = (instance.path3D).update(path);
  65225. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65226. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65227. instance.path3D = path3D;
  65228. instance.pathArray = pathArray;
  65229. instance.arc = arc;
  65230. instance.radius = radius;
  65231. return instance;
  65232. }
  65233. // tube creation
  65234. path3D = new BABYLON.Path3D(path);
  65235. var newPathArray = new Array();
  65236. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65237. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65238. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65239. tube.pathArray = pathArray;
  65240. tube.path3D = path3D;
  65241. tube.tessellation = tessellation;
  65242. tube.cap = cap;
  65243. tube.arc = options.arc;
  65244. tube.radius = radius;
  65245. return tube;
  65246. };
  65247. /**
  65248. * Creates a polyhedron mesh
  65249. * * 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
  65250. * * The parameter `size` (positive float, default 1) sets the polygon size
  65251. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65252. * * 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`
  65253. * * 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
  65254. * * 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)`)
  65255. * * 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
  65256. * * 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
  65257. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65258. * * 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
  65259. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65260. * @param name defines the name of the mesh
  65261. * @param options defines the options used to create the mesh
  65262. * @param scene defines the hosting scene
  65263. * @returns the polyhedron mesh
  65264. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65265. */
  65266. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65267. var polyhedron = new BABYLON.Mesh(name, scene);
  65268. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65269. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65270. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65271. vertexData.applyToMesh(polyhedron, options.updatable);
  65272. return polyhedron;
  65273. };
  65274. /**
  65275. * Creates a decal mesh.
  65276. * 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
  65277. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65278. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65279. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65280. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65281. * @param name defines the name of the mesh
  65282. * @param sourceMesh defines the mesh where the decal must be applied
  65283. * @param options defines the options used to create the mesh
  65284. * @param scene defines the hosting scene
  65285. * @returns the decal mesh
  65286. * @see http://doc.babylonjs.com/how_to/decals
  65287. */
  65288. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65289. var indices = sourceMesh.getIndices();
  65290. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65291. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65292. var position = options.position || BABYLON.Vector3.Zero();
  65293. var normal = options.normal || BABYLON.Vector3.Up();
  65294. var size = options.size || BABYLON.Vector3.One();
  65295. var angle = options.angle || 0;
  65296. // Getting correct rotation
  65297. if (!normal) {
  65298. var target = new BABYLON.Vector3(0, 0, 1);
  65299. var camera = sourceMesh.getScene().activeCamera;
  65300. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65301. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65302. }
  65303. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65304. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65305. var pitch = Math.atan2(normal.y, len);
  65306. // Matrix
  65307. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65308. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65309. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65310. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65311. var vertexData = new BABYLON.VertexData();
  65312. vertexData.indices = [];
  65313. vertexData.positions = [];
  65314. vertexData.normals = [];
  65315. vertexData.uvs = [];
  65316. var currentVertexDataIndex = 0;
  65317. var extractDecalVector3 = function (indexId) {
  65318. var result = new BABYLON.PositionNormalVertex();
  65319. if (!indices || !positions || !normals) {
  65320. return result;
  65321. }
  65322. var vertexId = indices[indexId];
  65323. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65324. // Send vector to decal local world
  65325. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65326. // Get normal
  65327. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65328. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65329. return result;
  65330. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65331. var clip = function (vertices, axis) {
  65332. if (vertices.length === 0) {
  65333. return vertices;
  65334. }
  65335. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65336. var clipVertices = function (v0, v1) {
  65337. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65338. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65339. };
  65340. var result = new Array();
  65341. for (var index = 0; index < vertices.length; index += 3) {
  65342. var v1Out;
  65343. var v2Out;
  65344. var v3Out;
  65345. var total = 0;
  65346. var nV1 = null;
  65347. var nV2 = null;
  65348. var nV3 = null;
  65349. var nV4 = null;
  65350. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65351. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65352. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65353. v1Out = d1 > 0;
  65354. v2Out = d2 > 0;
  65355. v3Out = d3 > 0;
  65356. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65357. switch (total) {
  65358. case 0:
  65359. result.push(vertices[index]);
  65360. result.push(vertices[index + 1]);
  65361. result.push(vertices[index + 2]);
  65362. break;
  65363. case 1:
  65364. if (v1Out) {
  65365. nV1 = vertices[index + 1];
  65366. nV2 = vertices[index + 2];
  65367. nV3 = clipVertices(vertices[index], nV1);
  65368. nV4 = clipVertices(vertices[index], nV2);
  65369. }
  65370. if (v2Out) {
  65371. nV1 = vertices[index];
  65372. nV2 = vertices[index + 2];
  65373. nV3 = clipVertices(vertices[index + 1], nV1);
  65374. nV4 = clipVertices(vertices[index + 1], nV2);
  65375. result.push(nV3);
  65376. result.push(nV2.clone());
  65377. result.push(nV1.clone());
  65378. result.push(nV2.clone());
  65379. result.push(nV3.clone());
  65380. result.push(nV4);
  65381. break;
  65382. }
  65383. if (v3Out) {
  65384. nV1 = vertices[index];
  65385. nV2 = vertices[index + 1];
  65386. nV3 = clipVertices(vertices[index + 2], nV1);
  65387. nV4 = clipVertices(vertices[index + 2], nV2);
  65388. }
  65389. if (nV1 && nV2 && nV3 && nV4) {
  65390. result.push(nV1.clone());
  65391. result.push(nV2.clone());
  65392. result.push(nV3);
  65393. result.push(nV4);
  65394. result.push(nV3.clone());
  65395. result.push(nV2.clone());
  65396. }
  65397. break;
  65398. case 2:
  65399. if (!v1Out) {
  65400. nV1 = vertices[index].clone();
  65401. nV2 = clipVertices(nV1, vertices[index + 1]);
  65402. nV3 = clipVertices(nV1, vertices[index + 2]);
  65403. result.push(nV1);
  65404. result.push(nV2);
  65405. result.push(nV3);
  65406. }
  65407. if (!v2Out) {
  65408. nV1 = vertices[index + 1].clone();
  65409. nV2 = clipVertices(nV1, vertices[index + 2]);
  65410. nV3 = clipVertices(nV1, vertices[index]);
  65411. result.push(nV1);
  65412. result.push(nV2);
  65413. result.push(nV3);
  65414. }
  65415. if (!v3Out) {
  65416. nV1 = vertices[index + 2].clone();
  65417. nV2 = clipVertices(nV1, vertices[index]);
  65418. nV3 = clipVertices(nV1, vertices[index + 1]);
  65419. result.push(nV1);
  65420. result.push(nV2);
  65421. result.push(nV3);
  65422. }
  65423. break;
  65424. case 3:
  65425. break;
  65426. }
  65427. }
  65428. return result;
  65429. };
  65430. for (var index = 0; index < indices.length; index += 3) {
  65431. var faceVertices = new Array();
  65432. faceVertices.push(extractDecalVector3(index));
  65433. faceVertices.push(extractDecalVector3(index + 1));
  65434. faceVertices.push(extractDecalVector3(index + 2));
  65435. // Clip
  65436. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65437. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65438. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65439. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65440. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65441. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65442. if (faceVertices.length === 0) {
  65443. continue;
  65444. }
  65445. // Add UVs and get back to world
  65446. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65447. var vertex = faceVertices[vIndex];
  65448. //TODO check for Int32Array | Uint32Array | Uint16Array
  65449. vertexData.indices.push(currentVertexDataIndex);
  65450. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65451. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65452. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65453. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65454. currentVertexDataIndex++;
  65455. }
  65456. }
  65457. // Return mesh
  65458. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65459. vertexData.applyToMesh(decal);
  65460. decal.position = position.clone();
  65461. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65462. return decal;
  65463. };
  65464. // Privates
  65465. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65466. // extrusion geometry
  65467. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65468. var tangents = path3D.getTangents();
  65469. var normals = path3D.getNormals();
  65470. var binormals = path3D.getBinormals();
  65471. var distances = path3D.getDistances();
  65472. var angle = 0;
  65473. var returnScale = function () { return scale !== null ? scale : 1; };
  65474. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65475. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65476. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65477. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65478. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65479. for (var i = 0; i < curve.length; i++) {
  65480. var shapePath = new Array();
  65481. var angleStep = rotate(i, distances[i]);
  65482. var scaleRatio = scl(i, distances[i]);
  65483. for (var p = 0; p < shape.length; p++) {
  65484. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65485. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65486. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65487. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65488. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65489. shapePath[p] = rotated;
  65490. }
  65491. shapePaths[index] = shapePath;
  65492. angle += angleStep;
  65493. index++;
  65494. }
  65495. // cap
  65496. var capPath = function (shapePath) {
  65497. var pointCap = Array();
  65498. var barycenter = BABYLON.Vector3.Zero();
  65499. var i;
  65500. for (i = 0; i < shapePath.length; i++) {
  65501. barycenter.addInPlace(shapePath[i]);
  65502. }
  65503. barycenter.scaleInPlace(1.0 / shapePath.length);
  65504. for (i = 0; i < shapePath.length; i++) {
  65505. pointCap.push(barycenter);
  65506. }
  65507. return pointCap;
  65508. };
  65509. switch (cap) {
  65510. case BABYLON.Mesh.NO_CAP:
  65511. break;
  65512. case BABYLON.Mesh.CAP_START:
  65513. shapePaths[0] = capPath(shapePaths[2]);
  65514. shapePaths[1] = shapePaths[2];
  65515. break;
  65516. case BABYLON.Mesh.CAP_END:
  65517. shapePaths[index] = shapePaths[index - 1];
  65518. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65519. break;
  65520. case BABYLON.Mesh.CAP_ALL:
  65521. shapePaths[0] = capPath(shapePaths[2]);
  65522. shapePaths[1] = shapePaths[2];
  65523. shapePaths[index] = shapePaths[index - 1];
  65524. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65525. break;
  65526. default:
  65527. break;
  65528. }
  65529. return shapePaths;
  65530. };
  65531. var path3D;
  65532. var pathArray;
  65533. if (instance) { // instance update
  65534. path3D = (instance.path3D).update(curve);
  65535. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65536. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65537. return instance;
  65538. }
  65539. // extruded shape creation
  65540. path3D = new BABYLON.Path3D(curve);
  65541. var newShapePaths = new Array();
  65542. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65543. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65544. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65545. extrudedGeneric.pathArray = pathArray;
  65546. extrudedGeneric.path3D = path3D;
  65547. extrudedGeneric.cap = cap;
  65548. return extrudedGeneric;
  65549. };
  65550. return MeshBuilder;
  65551. }());
  65552. BABYLON.MeshBuilder = MeshBuilder;
  65553. })(BABYLON || (BABYLON = {}));
  65554. //# sourceMappingURL=babylon.meshBuilder.js.map
  65555. var BABYLON;
  65556. (function (BABYLON) {
  65557. /**
  65558. * Draco compression (https://google.github.io/draco/)
  65559. *
  65560. * This class wraps the Draco module.
  65561. *
  65562. * **Encoder**
  65563. *
  65564. * The encoder is not currently implemented.
  65565. *
  65566. * **Decoder**
  65567. *
  65568. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65569. *
  65570. * To update the configuration, use the following code:
  65571. * ```javascript
  65572. * BABYLON.DracoCompression.Configuration = {
  65573. * decoder: {
  65574. * wasmUrl: "<url to the WebAssembly library>",
  65575. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65576. * fallbackUrl: "<url to the fallback JavaScript library>",
  65577. * }
  65578. * };
  65579. * ```
  65580. *
  65581. * 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.
  65582. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65583. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65584. *
  65585. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65586. * ```javascript
  65587. * var dracoCompression = new BABYLON.DracoCompression();
  65588. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65589. * [BABYLON.VertexBuffer.PositionKind]: 0
  65590. * });
  65591. * ```
  65592. *
  65593. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65594. */
  65595. var DracoCompression = /** @class */ (function () {
  65596. /**
  65597. * Constructor
  65598. */
  65599. function DracoCompression() {
  65600. }
  65601. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65602. /**
  65603. * Returns true if the decoder is available.
  65604. */
  65605. get: function () {
  65606. if (typeof DracoDecoderModule !== "undefined") {
  65607. return true;
  65608. }
  65609. var decoder = DracoCompression.Configuration.decoder;
  65610. if (decoder) {
  65611. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65612. return true;
  65613. }
  65614. if (decoder.fallbackUrl) {
  65615. return true;
  65616. }
  65617. }
  65618. return false;
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. /**
  65624. * Stop all async operations and release resources.
  65625. */
  65626. DracoCompression.prototype.dispose = function () {
  65627. };
  65628. /**
  65629. * Decode Draco compressed mesh data to vertex data.
  65630. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65631. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65632. * @returns A promise that resolves with the decoded vertex data
  65633. */
  65634. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65635. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65636. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65637. var module = wrappedModule.module;
  65638. var vertexData = new BABYLON.VertexData();
  65639. var buffer = new module.DecoderBuffer();
  65640. buffer.Init(dataView, dataView.byteLength);
  65641. var decoder = new module.Decoder();
  65642. var geometry;
  65643. var status;
  65644. try {
  65645. var type = decoder.GetEncodedGeometryType(buffer);
  65646. switch (type) {
  65647. case module.TRIANGULAR_MESH:
  65648. geometry = new module.Mesh();
  65649. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65650. break;
  65651. case module.POINT_CLOUD:
  65652. geometry = new module.PointCloud();
  65653. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65654. break;
  65655. default:
  65656. throw new Error("Invalid geometry type " + type);
  65657. }
  65658. if (!status.ok() || !geometry.ptr) {
  65659. throw new Error(status.error_msg());
  65660. }
  65661. var numPoints = geometry.num_points();
  65662. if (type === module.TRIANGULAR_MESH) {
  65663. var numFaces = geometry.num_faces();
  65664. var faceIndices = new module.DracoInt32Array();
  65665. try {
  65666. var indices = new Uint32Array(numFaces * 3);
  65667. for (var i = 0; i < numFaces; i++) {
  65668. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65669. var offset = i * 3;
  65670. indices[offset + 0] = faceIndices.GetValue(0);
  65671. indices[offset + 1] = faceIndices.GetValue(1);
  65672. indices[offset + 2] = faceIndices.GetValue(2);
  65673. }
  65674. vertexData.indices = indices;
  65675. }
  65676. finally {
  65677. module.destroy(faceIndices);
  65678. }
  65679. }
  65680. for (var kind in attributes) {
  65681. var uniqueId = attributes[kind];
  65682. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65683. var dracoData = new module.DracoFloat32Array();
  65684. try {
  65685. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65686. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65687. for (var i = 0; i < babylonData.length; i++) {
  65688. babylonData[i] = dracoData.GetValue(i);
  65689. }
  65690. vertexData.set(babylonData, kind);
  65691. }
  65692. finally {
  65693. module.destroy(dracoData);
  65694. }
  65695. }
  65696. }
  65697. finally {
  65698. if (geometry) {
  65699. module.destroy(geometry);
  65700. }
  65701. module.destroy(decoder);
  65702. module.destroy(buffer);
  65703. }
  65704. return vertexData;
  65705. });
  65706. };
  65707. DracoCompression._GetDecoderModule = function () {
  65708. if (!DracoCompression._DecoderModulePromise) {
  65709. var promise = null;
  65710. var config_1 = {};
  65711. if (typeof DracoDecoderModule !== "undefined") {
  65712. promise = Promise.resolve();
  65713. }
  65714. else {
  65715. var decoder = DracoCompression.Configuration.decoder;
  65716. if (decoder) {
  65717. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65718. promise = Promise.all([
  65719. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65720. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65721. config_1.wasmBinary = data;
  65722. })
  65723. ]);
  65724. }
  65725. else if (decoder.fallbackUrl) {
  65726. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65727. }
  65728. }
  65729. }
  65730. if (!promise) {
  65731. throw new Error("Draco decoder module is not available");
  65732. }
  65733. DracoCompression._DecoderModulePromise = promise.then(function () {
  65734. return new Promise(function (resolve) {
  65735. config_1.onModuleLoaded = function (decoderModule) {
  65736. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65737. resolve({ module: decoderModule });
  65738. };
  65739. DracoDecoderModule(config_1);
  65740. });
  65741. });
  65742. }
  65743. return DracoCompression._DecoderModulePromise;
  65744. };
  65745. DracoCompression._LoadScriptAsync = function (url) {
  65746. return new Promise(function (resolve, reject) {
  65747. BABYLON.Tools.LoadScript(url, function () {
  65748. resolve();
  65749. }, function (message) {
  65750. reject(new Error(message));
  65751. });
  65752. });
  65753. };
  65754. DracoCompression._LoadFileAsync = function (url) {
  65755. return new Promise(function (resolve, reject) {
  65756. BABYLON.Tools.LoadFile(url, function (data) {
  65757. resolve(data);
  65758. }, undefined, undefined, true, function (request, exception) {
  65759. reject(exception);
  65760. });
  65761. });
  65762. };
  65763. /**
  65764. * The configuration. Defaults to the following urls:
  65765. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65766. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65767. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65768. */
  65769. DracoCompression.Configuration = {
  65770. decoder: {
  65771. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65772. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65773. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65774. }
  65775. };
  65776. return DracoCompression;
  65777. }());
  65778. BABYLON.DracoCompression = DracoCompression;
  65779. })(BABYLON || (BABYLON = {}));
  65780. //# sourceMappingURL=babylon.dracoCompression.js.map
  65781. var BABYLON;
  65782. (function (BABYLON) {
  65783. // Sets the default audio engine to Babylon JS.
  65784. BABYLON.Engine.AudioEngineFactory = function () { return new AudioEngine(); };
  65785. var AudioEngine = /** @class */ (function () {
  65786. function AudioEngine() {
  65787. this._audioContext = null;
  65788. this._audioContextInitialized = false;
  65789. this.canUseWebAudio = false;
  65790. this.WarnedWebAudioUnsupported = false;
  65791. this.unlocked = false;
  65792. this.isMP3supported = false;
  65793. this.isOGGsupported = false;
  65794. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65795. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65796. this.canUseWebAudio = true;
  65797. }
  65798. var audioElem = document.createElement('audio');
  65799. try {
  65800. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65801. this.isMP3supported = true;
  65802. }
  65803. }
  65804. catch (e) {
  65805. // protect error during capability check.
  65806. }
  65807. try {
  65808. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65809. this.isOGGsupported = true;
  65810. }
  65811. }
  65812. catch (e) {
  65813. // protect error during capability check.
  65814. }
  65815. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65816. this._unlockiOSaudio();
  65817. }
  65818. else {
  65819. this.unlocked = true;
  65820. }
  65821. }
  65822. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65823. get: function () {
  65824. if (!this._audioContextInitialized) {
  65825. this._initializeAudioContext();
  65826. }
  65827. return this._audioContext;
  65828. },
  65829. enumerable: true,
  65830. configurable: true
  65831. });
  65832. AudioEngine.prototype._unlockiOSaudio = function () {
  65833. var _this = this;
  65834. var unlockaudio = function () {
  65835. if (!_this.audioContext) {
  65836. return;
  65837. }
  65838. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65839. var source = _this.audioContext.createBufferSource();
  65840. source.buffer = buffer;
  65841. source.connect(_this.audioContext.destination);
  65842. source.start(0);
  65843. setTimeout(function () {
  65844. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65845. _this.unlocked = true;
  65846. window.removeEventListener('touchend', unlockaudio, false);
  65847. if (_this.onAudioUnlocked) {
  65848. _this.onAudioUnlocked();
  65849. }
  65850. }
  65851. }, 0);
  65852. };
  65853. window.addEventListener('touchend', unlockaudio, false);
  65854. };
  65855. AudioEngine.prototype._initializeAudioContext = function () {
  65856. try {
  65857. if (this.canUseWebAudio) {
  65858. this._audioContext = new AudioContext();
  65859. // create a global volume gain node
  65860. this.masterGain = this._audioContext.createGain();
  65861. this.masterGain.gain.value = 1;
  65862. this.masterGain.connect(this._audioContext.destination);
  65863. this._audioContextInitialized = true;
  65864. }
  65865. }
  65866. catch (e) {
  65867. this.canUseWebAudio = false;
  65868. BABYLON.Tools.Error("Web Audio: " + e.message);
  65869. }
  65870. };
  65871. AudioEngine.prototype.dispose = function () {
  65872. if (this.canUseWebAudio && this._audioContextInitialized) {
  65873. if (this._connectedAnalyser && this._audioContext) {
  65874. this._connectedAnalyser.stopDebugCanvas();
  65875. this._connectedAnalyser.dispose();
  65876. this.masterGain.disconnect();
  65877. this.masterGain.connect(this._audioContext.destination);
  65878. this._connectedAnalyser = null;
  65879. }
  65880. this.masterGain.gain.value = 1;
  65881. }
  65882. this.WarnedWebAudioUnsupported = false;
  65883. };
  65884. AudioEngine.prototype.getGlobalVolume = function () {
  65885. if (this.canUseWebAudio && this._audioContextInitialized) {
  65886. return this.masterGain.gain.value;
  65887. }
  65888. else {
  65889. return -1;
  65890. }
  65891. };
  65892. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65893. if (this.canUseWebAudio && this._audioContextInitialized) {
  65894. this.masterGain.gain.value = newVolume;
  65895. }
  65896. };
  65897. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65898. if (this._connectedAnalyser) {
  65899. this._connectedAnalyser.stopDebugCanvas();
  65900. }
  65901. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65902. this._connectedAnalyser = analyser;
  65903. this.masterGain.disconnect();
  65904. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65905. }
  65906. };
  65907. return AudioEngine;
  65908. }());
  65909. BABYLON.AudioEngine = AudioEngine;
  65910. })(BABYLON || (BABYLON = {}));
  65911. //# sourceMappingURL=babylon.audioEngine.js.map
  65912. var BABYLON;
  65913. (function (BABYLON) {
  65914. var Sound = /** @class */ (function () {
  65915. /**
  65916. * Create a sound and attach it to a scene
  65917. * @param name Name of your sound
  65918. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65919. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65920. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65921. */
  65922. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65923. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65924. var _this = this;
  65925. this.autoplay = false;
  65926. this.loop = false;
  65927. this.useCustomAttenuation = false;
  65928. this.spatialSound = false;
  65929. this.refDistance = 1;
  65930. this.rolloffFactor = 1;
  65931. this.maxDistance = 100;
  65932. this.distanceModel = "linear";
  65933. this._panningModel = "equalpower";
  65934. /**
  65935. * Observable event when the current playing sound finishes.
  65936. */
  65937. this.onEndedObservable = new BABYLON.Observable();
  65938. this._playbackRate = 1;
  65939. this._streaming = false;
  65940. this._startTime = 0;
  65941. this._startOffset = 0;
  65942. this._position = BABYLON.Vector3.Zero();
  65943. /** @hidden */
  65944. this._positionInEmitterSpace = false;
  65945. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65946. this._volume = 1;
  65947. this._isReadyToPlay = false;
  65948. this.isPlaying = false;
  65949. this.isPaused = false;
  65950. this._isDirectional = false;
  65951. // Used if you'd like to create a directional sound.
  65952. // If not set, the sound will be omnidirectional
  65953. this._coneInnerAngle = 360;
  65954. this._coneOuterAngle = 360;
  65955. this._coneOuterGain = 0;
  65956. this._isOutputConnected = false;
  65957. this._urlType = "Unknown";
  65958. this.name = name;
  65959. this._scene = scene;
  65960. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  65961. if (!compo) {
  65962. compo = new BABYLON.AudioSceneComponent(scene);
  65963. scene._addComponent(compo);
  65964. }
  65965. this._readyToPlayCallback = readyToPlayCallback;
  65966. // Default custom attenuation function is a linear attenuation
  65967. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65968. if (currentDistance < maxDistance) {
  65969. return currentVolume * (1 - currentDistance / maxDistance);
  65970. }
  65971. else {
  65972. return 0;
  65973. }
  65974. };
  65975. if (options) {
  65976. this.autoplay = options.autoplay || false;
  65977. this.loop = options.loop || false;
  65978. // if volume === 0, we need another way to check this option
  65979. if (options.volume !== undefined) {
  65980. this._volume = options.volume;
  65981. }
  65982. this.spatialSound = options.spatialSound || false;
  65983. this.maxDistance = options.maxDistance || 100;
  65984. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65985. this.rolloffFactor = options.rolloffFactor || 1;
  65986. this.refDistance = options.refDistance || 1;
  65987. this.distanceModel = options.distanceModel || "linear";
  65988. this._playbackRate = options.playbackRate || 1;
  65989. this._streaming = options.streaming || false;
  65990. }
  65991. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65992. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65993. this._soundGain.gain.value = this._volume;
  65994. this._inputAudioNode = this._soundGain;
  65995. this._outputAudioNode = this._soundGain;
  65996. if (this.spatialSound) {
  65997. this._createSpatialParameters();
  65998. }
  65999. this._scene.mainSoundTrack.AddSound(this);
  66000. var validParameter = true;
  66001. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  66002. if (urlOrArrayBuffer) {
  66003. try {
  66004. if (typeof (urlOrArrayBuffer) === "string") {
  66005. this._urlType = "String";
  66006. }
  66007. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  66008. this._urlType = "ArrayBuffer";
  66009. }
  66010. else if (urlOrArrayBuffer instanceof MediaStream) {
  66011. this._urlType = "MediaStream";
  66012. }
  66013. else if (Array.isArray(urlOrArrayBuffer)) {
  66014. this._urlType = "Array";
  66015. }
  66016. var urls = [];
  66017. var codecSupportedFound = false;
  66018. switch (this._urlType) {
  66019. case "MediaStream":
  66020. this._streaming = true;
  66021. this._isReadyToPlay = true;
  66022. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  66023. if (this.autoplay) {
  66024. this.play();
  66025. }
  66026. if (this._readyToPlayCallback) {
  66027. this._readyToPlayCallback();
  66028. }
  66029. break;
  66030. case "ArrayBuffer":
  66031. if (urlOrArrayBuffer.byteLength > 0) {
  66032. codecSupportedFound = true;
  66033. this._soundLoaded(urlOrArrayBuffer);
  66034. }
  66035. break;
  66036. case "String":
  66037. urls.push(urlOrArrayBuffer);
  66038. case "Array":
  66039. if (urls.length === 0)
  66040. urls = urlOrArrayBuffer;
  66041. // If we found a supported format, we load it immediately and stop the loop
  66042. for (var i = 0; i < urls.length; i++) {
  66043. var url = urls[i];
  66044. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  66045. codecSupportedFound = true;
  66046. }
  66047. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  66048. codecSupportedFound = true;
  66049. }
  66050. if (url.indexOf(".wav", url.length - 4) !== -1) {
  66051. codecSupportedFound = true;
  66052. }
  66053. if (url.indexOf("blob:") !== -1) {
  66054. codecSupportedFound = true;
  66055. }
  66056. if (codecSupportedFound) {
  66057. // Loading sound using XHR2
  66058. if (!this._streaming) {
  66059. this._scene._loadFile(url, function (data) {
  66060. _this._soundLoaded(data);
  66061. }, undefined, true, true, function (exception) {
  66062. if (exception) {
  66063. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  66064. }
  66065. BABYLON.Tools.Error("Sound creation aborted.");
  66066. _this._scene.mainSoundTrack.RemoveSound(_this);
  66067. });
  66068. }
  66069. // Streaming sound using HTML5 Audio tag
  66070. else {
  66071. this._htmlAudioElement = new Audio(url);
  66072. this._htmlAudioElement.controls = false;
  66073. this._htmlAudioElement.loop = this.loop;
  66074. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  66075. this._htmlAudioElement.preload = "auto";
  66076. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  66077. _this._isReadyToPlay = true;
  66078. if (_this.autoplay) {
  66079. _this.play();
  66080. }
  66081. if (_this._readyToPlayCallback) {
  66082. _this._readyToPlayCallback();
  66083. }
  66084. });
  66085. document.body.appendChild(this._htmlAudioElement);
  66086. }
  66087. break;
  66088. }
  66089. }
  66090. break;
  66091. default:
  66092. validParameter = false;
  66093. break;
  66094. }
  66095. if (!validParameter) {
  66096. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  66097. }
  66098. else {
  66099. if (!codecSupportedFound) {
  66100. this._isReadyToPlay = true;
  66101. // Simulating a ready to play event to avoid breaking code path
  66102. if (this._readyToPlayCallback) {
  66103. window.setTimeout(function () {
  66104. if (_this._readyToPlayCallback) {
  66105. _this._readyToPlayCallback();
  66106. }
  66107. }, 1000);
  66108. }
  66109. }
  66110. }
  66111. }
  66112. catch (ex) {
  66113. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  66114. this._scene.mainSoundTrack.RemoveSound(this);
  66115. }
  66116. }
  66117. }
  66118. else {
  66119. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  66120. this._scene.mainSoundTrack.AddSound(this);
  66121. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  66122. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  66123. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  66124. }
  66125. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  66126. if (this._readyToPlayCallback) {
  66127. window.setTimeout(function () {
  66128. if (_this._readyToPlayCallback) {
  66129. _this._readyToPlayCallback();
  66130. }
  66131. }, 1000);
  66132. }
  66133. }
  66134. }
  66135. Sound.prototype.dispose = function () {
  66136. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66137. if (this.isPlaying) {
  66138. this.stop();
  66139. }
  66140. this._isReadyToPlay = false;
  66141. if (this.soundTrackId === -1) {
  66142. this._scene.mainSoundTrack.RemoveSound(this);
  66143. }
  66144. else if (this._scene.soundTracks) {
  66145. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  66146. }
  66147. if (this._soundGain) {
  66148. this._soundGain.disconnect();
  66149. this._soundGain = null;
  66150. }
  66151. if (this._soundPanner) {
  66152. this._soundPanner.disconnect();
  66153. this._soundPanner = null;
  66154. }
  66155. if (this._soundSource) {
  66156. this._soundSource.disconnect();
  66157. this._soundSource = null;
  66158. }
  66159. this._audioBuffer = null;
  66160. if (this._htmlAudioElement) {
  66161. this._htmlAudioElement.pause();
  66162. this._htmlAudioElement.src = "";
  66163. document.body.removeChild(this._htmlAudioElement);
  66164. }
  66165. if (this._streamingSource) {
  66166. this._streamingSource.disconnect();
  66167. }
  66168. if (this._connectedMesh && this._registerFunc) {
  66169. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66170. this._connectedMesh = null;
  66171. }
  66172. }
  66173. };
  66174. Sound.prototype.isReady = function () {
  66175. return this._isReadyToPlay;
  66176. };
  66177. Sound.prototype._soundLoaded = function (audioData) {
  66178. var _this = this;
  66179. if (!BABYLON.Engine.audioEngine.audioContext) {
  66180. return;
  66181. }
  66182. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  66183. _this._audioBuffer = buffer;
  66184. _this._isReadyToPlay = true;
  66185. if (_this.autoplay) {
  66186. _this.play();
  66187. }
  66188. if (_this._readyToPlayCallback) {
  66189. _this._readyToPlayCallback();
  66190. }
  66191. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  66192. };
  66193. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  66194. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66195. this._audioBuffer = audioBuffer;
  66196. this._isReadyToPlay = true;
  66197. }
  66198. };
  66199. Sound.prototype.updateOptions = function (options) {
  66200. if (options) {
  66201. this.loop = options.loop || this.loop;
  66202. this.maxDistance = options.maxDistance || this.maxDistance;
  66203. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  66204. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  66205. this.refDistance = options.refDistance || this.refDistance;
  66206. this.distanceModel = options.distanceModel || this.distanceModel;
  66207. this._playbackRate = options.playbackRate || this._playbackRate;
  66208. this._updateSpatialParameters();
  66209. if (this.isPlaying) {
  66210. if (this._streaming && this._htmlAudioElement) {
  66211. this._htmlAudioElement.playbackRate = this._playbackRate;
  66212. }
  66213. else {
  66214. if (this._soundSource) {
  66215. this._soundSource.playbackRate.value = this._playbackRate;
  66216. }
  66217. }
  66218. }
  66219. }
  66220. };
  66221. Sound.prototype._createSpatialParameters = function () {
  66222. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66223. if (this._scene.headphone) {
  66224. this._panningModel = "HRTF";
  66225. }
  66226. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66227. this._updateSpatialParameters();
  66228. this._soundPanner.connect(this._outputAudioNode);
  66229. this._inputAudioNode = this._soundPanner;
  66230. }
  66231. };
  66232. Sound.prototype._updateSpatialParameters = function () {
  66233. if (this.spatialSound && this._soundPanner) {
  66234. if (this.useCustomAttenuation) {
  66235. // Tricks to disable in a way embedded Web Audio attenuation
  66236. this._soundPanner.distanceModel = "linear";
  66237. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66238. this._soundPanner.refDistance = 1;
  66239. this._soundPanner.rolloffFactor = 1;
  66240. this._soundPanner.panningModel = this._panningModel;
  66241. }
  66242. else {
  66243. this._soundPanner.distanceModel = this.distanceModel;
  66244. this._soundPanner.maxDistance = this.maxDistance;
  66245. this._soundPanner.refDistance = this.refDistance;
  66246. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66247. this._soundPanner.panningModel = this._panningModel;
  66248. }
  66249. }
  66250. };
  66251. Sound.prototype.switchPanningModelToHRTF = function () {
  66252. this._panningModel = "HRTF";
  66253. this._switchPanningModel();
  66254. };
  66255. Sound.prototype.switchPanningModelToEqualPower = function () {
  66256. this._panningModel = "equalpower";
  66257. this._switchPanningModel();
  66258. };
  66259. Sound.prototype._switchPanningModel = function () {
  66260. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66261. this._soundPanner.panningModel = this._panningModel;
  66262. }
  66263. };
  66264. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66265. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66266. if (this._isOutputConnected) {
  66267. this._outputAudioNode.disconnect();
  66268. }
  66269. this._outputAudioNode.connect(soundTrackAudioNode);
  66270. this._isOutputConnected = true;
  66271. }
  66272. };
  66273. /**
  66274. * Transform this sound into a directional source
  66275. * @param coneInnerAngle Size of the inner cone in degree
  66276. * @param coneOuterAngle Size of the outer cone in degree
  66277. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66278. */
  66279. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66280. if (coneOuterAngle < coneInnerAngle) {
  66281. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66282. return;
  66283. }
  66284. this._coneInnerAngle = coneInnerAngle;
  66285. this._coneOuterAngle = coneOuterAngle;
  66286. this._coneOuterGain = coneOuterGain;
  66287. this._isDirectional = true;
  66288. if (this.isPlaying && this.loop) {
  66289. this.stop();
  66290. this.play();
  66291. }
  66292. };
  66293. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66294. /**
  66295. * Gets or sets the inner angle for the directional cone.
  66296. */
  66297. get: function () {
  66298. return this._coneInnerAngle;
  66299. },
  66300. /**
  66301. * Gets or sets the inner angle for the directional cone.
  66302. */
  66303. set: function (value) {
  66304. if (value != this._coneInnerAngle) {
  66305. if (this._coneOuterAngle < value) {
  66306. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66307. return;
  66308. }
  66309. this._coneInnerAngle = value;
  66310. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66311. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66312. }
  66313. }
  66314. },
  66315. enumerable: true,
  66316. configurable: true
  66317. });
  66318. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66319. /**
  66320. * Gets or sets the outer angle for the directional cone.
  66321. */
  66322. get: function () {
  66323. return this._coneOuterAngle;
  66324. },
  66325. /**
  66326. * Gets or sets the outer angle for the directional cone.
  66327. */
  66328. set: function (value) {
  66329. if (value != this._coneOuterAngle) {
  66330. if (value < this._coneInnerAngle) {
  66331. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66332. return;
  66333. }
  66334. this._coneOuterAngle = value;
  66335. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66336. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66337. }
  66338. }
  66339. },
  66340. enumerable: true,
  66341. configurable: true
  66342. });
  66343. Sound.prototype.setPosition = function (newPosition) {
  66344. this._position = newPosition;
  66345. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66346. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66347. }
  66348. };
  66349. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66350. this._localDirection = newLocalDirection;
  66351. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66352. this._updateDirection();
  66353. }
  66354. };
  66355. Sound.prototype._updateDirection = function () {
  66356. if (!this._connectedMesh || !this._soundPanner) {
  66357. return;
  66358. }
  66359. var mat = this._connectedMesh.getWorldMatrix();
  66360. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66361. direction.normalize();
  66362. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66363. };
  66364. Sound.prototype.updateDistanceFromListener = function () {
  66365. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66366. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66367. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66368. }
  66369. };
  66370. Sound.prototype.setAttenuationFunction = function (callback) {
  66371. this._customAttenuationFunction = callback;
  66372. };
  66373. /**
  66374. * Play the sound
  66375. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66376. * @param offset (optional) Start the sound setting it at a specific time
  66377. */
  66378. Sound.prototype.play = function (time, offset) {
  66379. var _this = this;
  66380. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66381. try {
  66382. if (this._startOffset < 0) {
  66383. time = -this._startOffset;
  66384. this._startOffset = 0;
  66385. }
  66386. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66387. if (!this._soundSource || !this._streamingSource) {
  66388. if (this.spatialSound && this._soundPanner) {
  66389. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66390. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66391. }
  66392. if (this._isDirectional) {
  66393. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66394. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66395. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66396. if (this._connectedMesh) {
  66397. this._updateDirection();
  66398. }
  66399. else {
  66400. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66401. }
  66402. }
  66403. }
  66404. }
  66405. if (this._streaming) {
  66406. if (!this._streamingSource) {
  66407. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66408. this._htmlAudioElement.onended = function () { _this._onended(); };
  66409. this._htmlAudioElement.playbackRate = this._playbackRate;
  66410. }
  66411. this._streamingSource.disconnect();
  66412. this._streamingSource.connect(this._inputAudioNode);
  66413. if (this._htmlAudioElement) {
  66414. this._htmlAudioElement.play();
  66415. }
  66416. }
  66417. else {
  66418. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66419. this._soundSource.buffer = this._audioBuffer;
  66420. this._soundSource.connect(this._inputAudioNode);
  66421. this._soundSource.loop = this.loop;
  66422. this._soundSource.playbackRate.value = this._playbackRate;
  66423. this._soundSource.onended = function () { _this._onended(); };
  66424. if (this._soundSource.buffer) {
  66425. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66426. }
  66427. }
  66428. this._startTime = startTime;
  66429. this.isPlaying = true;
  66430. this.isPaused = false;
  66431. }
  66432. catch (ex) {
  66433. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66434. }
  66435. }
  66436. };
  66437. Sound.prototype._onended = function () {
  66438. this.isPlaying = false;
  66439. if (this.onended) {
  66440. this.onended();
  66441. }
  66442. this.onEndedObservable.notifyObservers(this);
  66443. };
  66444. /**
  66445. * Stop the sound
  66446. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66447. */
  66448. Sound.prototype.stop = function (time) {
  66449. if (this.isPlaying) {
  66450. if (this._streaming) {
  66451. if (this._htmlAudioElement) {
  66452. this._htmlAudioElement.pause();
  66453. // Test needed for Firefox or it will generate an Invalid State Error
  66454. if (this._htmlAudioElement.currentTime > 0) {
  66455. this._htmlAudioElement.currentTime = 0;
  66456. }
  66457. }
  66458. else {
  66459. this._streamingSource.disconnect();
  66460. }
  66461. }
  66462. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66463. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66464. this._soundSource.stop(stopTime);
  66465. this._soundSource.onended = function () { };
  66466. if (!this.isPaused) {
  66467. this._startOffset = 0;
  66468. }
  66469. }
  66470. this.isPlaying = false;
  66471. }
  66472. };
  66473. Sound.prototype.pause = function () {
  66474. if (this.isPlaying) {
  66475. this.isPaused = true;
  66476. if (this._streaming) {
  66477. if (this._htmlAudioElement) {
  66478. this._htmlAudioElement.pause();
  66479. }
  66480. else {
  66481. this._streamingSource.disconnect();
  66482. }
  66483. }
  66484. else if (BABYLON.Engine.audioEngine.audioContext) {
  66485. this.stop(0);
  66486. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66487. }
  66488. }
  66489. };
  66490. Sound.prototype.setVolume = function (newVolume, time) {
  66491. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66492. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66493. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66494. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66495. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66496. }
  66497. else {
  66498. this._soundGain.gain.value = newVolume;
  66499. }
  66500. }
  66501. this._volume = newVolume;
  66502. };
  66503. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66504. this._playbackRate = newPlaybackRate;
  66505. if (this.isPlaying) {
  66506. if (this._streaming && this._htmlAudioElement) {
  66507. this._htmlAudioElement.playbackRate = this._playbackRate;
  66508. }
  66509. else if (this._soundSource) {
  66510. this._soundSource.playbackRate.value = this._playbackRate;
  66511. }
  66512. }
  66513. };
  66514. Sound.prototype.getVolume = function () {
  66515. return this._volume;
  66516. };
  66517. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66518. var _this = this;
  66519. if (this._connectedMesh && this._registerFunc) {
  66520. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66521. this._registerFunc = null;
  66522. }
  66523. this._connectedMesh = meshToConnectTo;
  66524. if (!this.spatialSound) {
  66525. this.spatialSound = true;
  66526. this._createSpatialParameters();
  66527. if (this.isPlaying && this.loop) {
  66528. this.stop();
  66529. this.play();
  66530. }
  66531. }
  66532. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66533. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66534. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66535. };
  66536. Sound.prototype.detachFromMesh = function () {
  66537. if (this._connectedMesh && this._registerFunc) {
  66538. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66539. this._registerFunc = null;
  66540. this._connectedMesh = null;
  66541. }
  66542. };
  66543. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66544. if (!node.getBoundingInfo) {
  66545. return;
  66546. }
  66547. var mesh = node;
  66548. if (this._positionInEmitterSpace) {
  66549. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66550. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66551. }
  66552. else {
  66553. var boundingInfo = mesh.getBoundingInfo();
  66554. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66555. }
  66556. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66557. this._updateDirection();
  66558. }
  66559. };
  66560. Sound.prototype.clone = function () {
  66561. var _this = this;
  66562. if (!this._streaming) {
  66563. var setBufferAndRun = function () {
  66564. if (_this._isReadyToPlay) {
  66565. clonedSound._audioBuffer = _this.getAudioBuffer();
  66566. clonedSound._isReadyToPlay = true;
  66567. if (clonedSound.autoplay) {
  66568. clonedSound.play();
  66569. }
  66570. }
  66571. else {
  66572. window.setTimeout(setBufferAndRun, 300);
  66573. }
  66574. };
  66575. var currentOptions = {
  66576. autoplay: this.autoplay, loop: this.loop,
  66577. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66578. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66579. refDistance: this.refDistance, distanceModel: this.distanceModel
  66580. };
  66581. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66582. if (this.useCustomAttenuation) {
  66583. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66584. }
  66585. clonedSound.setPosition(this._position);
  66586. clonedSound.setPlaybackRate(this._playbackRate);
  66587. setBufferAndRun();
  66588. return clonedSound;
  66589. }
  66590. // Can't clone a streaming sound
  66591. else {
  66592. return null;
  66593. }
  66594. };
  66595. Sound.prototype.getAudioBuffer = function () {
  66596. return this._audioBuffer;
  66597. };
  66598. Sound.prototype.serialize = function () {
  66599. var serializationObject = {
  66600. name: this.name,
  66601. url: this.name,
  66602. autoplay: this.autoplay,
  66603. loop: this.loop,
  66604. volume: this._volume,
  66605. spatialSound: this.spatialSound,
  66606. maxDistance: this.maxDistance,
  66607. rolloffFactor: this.rolloffFactor,
  66608. refDistance: this.refDistance,
  66609. distanceModel: this.distanceModel,
  66610. playbackRate: this._playbackRate,
  66611. panningModel: this._panningModel,
  66612. soundTrackId: this.soundTrackId
  66613. };
  66614. if (this.spatialSound) {
  66615. if (this._connectedMesh)
  66616. serializationObject.connectedMeshId = this._connectedMesh.id;
  66617. serializationObject.position = this._position.asArray();
  66618. serializationObject.refDistance = this.refDistance;
  66619. serializationObject.distanceModel = this.distanceModel;
  66620. serializationObject.isDirectional = this._isDirectional;
  66621. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66622. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66623. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66624. serializationObject.coneOuterGain = this._coneOuterGain;
  66625. }
  66626. return serializationObject;
  66627. };
  66628. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66629. var soundName = parsedSound.name;
  66630. var soundUrl;
  66631. if (parsedSound.url) {
  66632. soundUrl = rootUrl + parsedSound.url;
  66633. }
  66634. else {
  66635. soundUrl = rootUrl + soundName;
  66636. }
  66637. var options = {
  66638. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66639. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66640. rolloffFactor: parsedSound.rolloffFactor,
  66641. refDistance: parsedSound.refDistance,
  66642. distanceModel: parsedSound.distanceModel,
  66643. playbackRate: parsedSound.playbackRate
  66644. };
  66645. var newSound;
  66646. if (!sourceSound) {
  66647. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66648. scene._addPendingData(newSound);
  66649. }
  66650. else {
  66651. var setBufferAndRun = function () {
  66652. if (sourceSound._isReadyToPlay) {
  66653. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66654. newSound._isReadyToPlay = true;
  66655. if (newSound.autoplay) {
  66656. newSound.play();
  66657. }
  66658. }
  66659. else {
  66660. window.setTimeout(setBufferAndRun, 300);
  66661. }
  66662. };
  66663. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66664. setBufferAndRun();
  66665. }
  66666. if (parsedSound.position) {
  66667. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66668. newSound.setPosition(soundPosition);
  66669. }
  66670. if (parsedSound.isDirectional) {
  66671. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66672. if (parsedSound.localDirectionToMesh) {
  66673. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66674. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66675. }
  66676. }
  66677. if (parsedSound.connectedMeshId) {
  66678. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66679. if (connectedMesh) {
  66680. newSound.attachToMesh(connectedMesh);
  66681. }
  66682. }
  66683. return newSound;
  66684. };
  66685. return Sound;
  66686. }());
  66687. BABYLON.Sound = Sound;
  66688. })(BABYLON || (BABYLON = {}));
  66689. //# sourceMappingURL=babylon.sound.js.map
  66690. var BABYLON;
  66691. (function (BABYLON) {
  66692. var SoundTrack = /** @class */ (function () {
  66693. function SoundTrack(scene, options) {
  66694. this.id = -1;
  66695. this._isMainTrack = false;
  66696. this._isInitialized = false;
  66697. this._scene = scene;
  66698. this.soundCollection = new Array();
  66699. this._options = options;
  66700. if (!this._isMainTrack && this._scene.soundTracks) {
  66701. this._scene.soundTracks.push(this);
  66702. this.id = this._scene.soundTracks.length - 1;
  66703. }
  66704. }
  66705. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66706. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66707. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66708. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66709. if (this._options) {
  66710. if (this._options.volume) {
  66711. this._outputAudioNode.gain.value = this._options.volume;
  66712. }
  66713. if (this._options.mainTrack) {
  66714. this._isMainTrack = this._options.mainTrack;
  66715. }
  66716. }
  66717. this._isInitialized = true;
  66718. }
  66719. };
  66720. SoundTrack.prototype.dispose = function () {
  66721. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66722. if (this._connectedAnalyser) {
  66723. this._connectedAnalyser.stopDebugCanvas();
  66724. }
  66725. while (this.soundCollection.length) {
  66726. this.soundCollection[0].dispose();
  66727. }
  66728. if (this._outputAudioNode) {
  66729. this._outputAudioNode.disconnect();
  66730. }
  66731. this._outputAudioNode = null;
  66732. }
  66733. };
  66734. SoundTrack.prototype.AddSound = function (sound) {
  66735. if (!this._isInitialized) {
  66736. this._initializeSoundTrackAudioGraph();
  66737. }
  66738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66739. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66740. }
  66741. if (sound.soundTrackId) {
  66742. if (sound.soundTrackId === -1) {
  66743. this._scene.mainSoundTrack.RemoveSound(sound);
  66744. }
  66745. else if (this._scene.soundTracks) {
  66746. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66747. }
  66748. }
  66749. this.soundCollection.push(sound);
  66750. sound.soundTrackId = this.id;
  66751. };
  66752. SoundTrack.prototype.RemoveSound = function (sound) {
  66753. var index = this.soundCollection.indexOf(sound);
  66754. if (index !== -1) {
  66755. this.soundCollection.splice(index, 1);
  66756. }
  66757. };
  66758. SoundTrack.prototype.setVolume = function (newVolume) {
  66759. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66760. this._outputAudioNode.gain.value = newVolume;
  66761. }
  66762. };
  66763. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66765. for (var i = 0; i < this.soundCollection.length; i++) {
  66766. this.soundCollection[i].switchPanningModelToHRTF();
  66767. }
  66768. }
  66769. };
  66770. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66772. for (var i = 0; i < this.soundCollection.length; i++) {
  66773. this.soundCollection[i].switchPanningModelToEqualPower();
  66774. }
  66775. }
  66776. };
  66777. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66778. if (this._connectedAnalyser) {
  66779. this._connectedAnalyser.stopDebugCanvas();
  66780. }
  66781. this._connectedAnalyser = analyser;
  66782. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66783. this._outputAudioNode.disconnect();
  66784. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66785. }
  66786. };
  66787. return SoundTrack;
  66788. }());
  66789. BABYLON.SoundTrack = SoundTrack;
  66790. })(BABYLON || (BABYLON = {}));
  66791. //# sourceMappingURL=babylon.soundtrack.js.map
  66792. var BABYLON;
  66793. (function (BABYLON) {
  66794. /**
  66795. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66796. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66797. */
  66798. var Analyser = /** @class */ (function () {
  66799. /**
  66800. * Creates a new analyser
  66801. * @param scene defines hosting scene
  66802. */
  66803. function Analyser(scene) {
  66804. /**
  66805. * Gets or sets the smoothing
  66806. * @ignorenaming
  66807. */
  66808. this.SMOOTHING = 0.75;
  66809. /**
  66810. * Gets or sets the FFT table size
  66811. * @ignorenaming
  66812. */
  66813. this.FFT_SIZE = 512;
  66814. /**
  66815. * Gets or sets the bar graph amplitude
  66816. * @ignorenaming
  66817. */
  66818. this.BARGRAPHAMPLITUDE = 256;
  66819. /**
  66820. * Gets or sets the position of the debug canvas
  66821. * @ignorenaming
  66822. */
  66823. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66824. /**
  66825. * Gets or sets the debug canvas size
  66826. * @ignorenaming
  66827. */
  66828. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66829. this._scene = scene;
  66830. this._audioEngine = BABYLON.Engine.audioEngine;
  66831. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66832. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66833. this._webAudioAnalyser.minDecibels = -140;
  66834. this._webAudioAnalyser.maxDecibels = 0;
  66835. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66836. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66837. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66838. }
  66839. }
  66840. /**
  66841. * Get the number of data values you will have to play with for the visualization
  66842. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66843. * @returns a number
  66844. */
  66845. Analyser.prototype.getFrequencyBinCount = function () {
  66846. if (this._audioEngine.canUseWebAudio) {
  66847. return this._webAudioAnalyser.frequencyBinCount;
  66848. }
  66849. else {
  66850. return 0;
  66851. }
  66852. };
  66853. /**
  66854. * Gets the current frequency data as a byte array
  66855. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66856. * @returns a Uint8Array
  66857. */
  66858. Analyser.prototype.getByteFrequencyData = function () {
  66859. if (this._audioEngine.canUseWebAudio) {
  66860. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66861. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66862. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66863. }
  66864. return this._byteFreqs;
  66865. };
  66866. /**
  66867. * Gets the current waveform as a byte array
  66868. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66869. * @returns a Uint8Array
  66870. */
  66871. Analyser.prototype.getByteTimeDomainData = function () {
  66872. if (this._audioEngine.canUseWebAudio) {
  66873. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66874. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66875. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66876. }
  66877. return this._byteTime;
  66878. };
  66879. /**
  66880. * Gets the current frequency data as a float array
  66881. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66882. * @returns a Float32Array
  66883. */
  66884. Analyser.prototype.getFloatFrequencyData = function () {
  66885. if (this._audioEngine.canUseWebAudio) {
  66886. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66887. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66888. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66889. }
  66890. return this._floatFreqs;
  66891. };
  66892. /**
  66893. * Renders the debug canvas
  66894. */
  66895. Analyser.prototype.drawDebugCanvas = function () {
  66896. var _this = this;
  66897. if (this._audioEngine.canUseWebAudio) {
  66898. if (!this._debugCanvas) {
  66899. this._debugCanvas = document.createElement("canvas");
  66900. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66901. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66902. this._debugCanvas.style.position = "absolute";
  66903. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66904. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66905. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66906. document.body.appendChild(this._debugCanvas);
  66907. this._registerFunc = function () {
  66908. _this.drawDebugCanvas();
  66909. };
  66910. this._scene.registerBeforeRender(this._registerFunc);
  66911. }
  66912. if (this._registerFunc && this._debugCanvasContext) {
  66913. var workingArray = this.getByteFrequencyData();
  66914. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66915. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66916. // Draw the frequency domain chart.
  66917. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66918. var value = workingArray[i];
  66919. var percent = value / this.BARGRAPHAMPLITUDE;
  66920. var height = this.DEBUGCANVASSIZE.height * percent;
  66921. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66922. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66923. var hue = i / this.getFrequencyBinCount() * 360;
  66924. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66925. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66926. }
  66927. }
  66928. }
  66929. };
  66930. /**
  66931. * Stops rendering the debug canvas and removes it
  66932. */
  66933. Analyser.prototype.stopDebugCanvas = function () {
  66934. if (this._debugCanvas) {
  66935. if (this._registerFunc) {
  66936. this._scene.unregisterBeforeRender(this._registerFunc);
  66937. this._registerFunc = null;
  66938. }
  66939. document.body.removeChild(this._debugCanvas);
  66940. this._debugCanvas = null;
  66941. this._debugCanvasContext = null;
  66942. }
  66943. };
  66944. /**
  66945. * Connects two audio nodes
  66946. * @param inputAudioNode defines first node to connect
  66947. * @param outputAudioNode defines second node to connect
  66948. */
  66949. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66950. if (this._audioEngine.canUseWebAudio) {
  66951. inputAudioNode.connect(this._webAudioAnalyser);
  66952. this._webAudioAnalyser.connect(outputAudioNode);
  66953. }
  66954. };
  66955. /**
  66956. * Releases all associated resources
  66957. */
  66958. Analyser.prototype.dispose = function () {
  66959. if (this._audioEngine.canUseWebAudio) {
  66960. this._webAudioAnalyser.disconnect();
  66961. }
  66962. };
  66963. return Analyser;
  66964. }());
  66965. BABYLON.Analyser = Analyser;
  66966. })(BABYLON || (BABYLON = {}));
  66967. //# sourceMappingURL=babylon.analyser.js.map
  66968. var BABYLON;
  66969. (function (BABYLON) {
  66970. /**
  66971. * Wraps one or more Sound objects and selects one with random weight for playback.
  66972. */
  66973. var WeightedSound = /** @class */ (function () {
  66974. /**
  66975. * Creates a new WeightedSound from the list of sounds given.
  66976. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66977. * @param sounds Array of Sounds that will be selected from.
  66978. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66979. */
  66980. function WeightedSound(loop, sounds, weights) {
  66981. var _this = this;
  66982. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66983. this.loop = false;
  66984. this._coneInnerAngle = 360;
  66985. this._coneOuterAngle = 360;
  66986. this._volume = 1;
  66987. /** A Sound is currently playing. */
  66988. this.isPlaying = false;
  66989. /** A Sound is currently paused. */
  66990. this.isPaused = false;
  66991. this._sounds = [];
  66992. this._weights = [];
  66993. if (sounds.length !== weights.length) {
  66994. throw new Error('Sounds length does not equal weights length');
  66995. }
  66996. this.loop = loop;
  66997. this._weights = weights;
  66998. // Normalize the weights
  66999. var weightSum = 0;
  67000. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  67001. var weight = weights_1[_i];
  67002. weightSum += weight;
  67003. }
  67004. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  67005. for (var i = 0; i < this._weights.length; i++) {
  67006. this._weights[i] *= invWeightSum;
  67007. }
  67008. this._sounds = sounds;
  67009. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  67010. var sound = _b[_a];
  67011. sound.onEndedObservable.add(function () { _this._onended(); });
  67012. }
  67013. }
  67014. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  67015. /**
  67016. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  67017. */
  67018. get: function () {
  67019. return this._coneInnerAngle;
  67020. },
  67021. /**
  67022. * The size of cone in degress for a directional sound in which there will be no attenuation.
  67023. */
  67024. set: function (value) {
  67025. if (value !== this._coneInnerAngle) {
  67026. if (this._coneOuterAngle < value) {
  67027. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67028. return;
  67029. }
  67030. this._coneInnerAngle = value;
  67031. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67032. var sound = _a[_i];
  67033. sound.directionalConeInnerAngle = value;
  67034. }
  67035. }
  67036. },
  67037. enumerable: true,
  67038. configurable: true
  67039. });
  67040. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  67041. /**
  67042. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  67043. * Listener angles between innerAngle and outerAngle will falloff linearly.
  67044. */
  67045. get: function () {
  67046. return this._coneOuterAngle;
  67047. },
  67048. /**
  67049. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  67050. * Listener angles between innerAngle and outerAngle will falloff linearly.
  67051. */
  67052. set: function (value) {
  67053. if (value !== this._coneOuterAngle) {
  67054. if (value < this._coneInnerAngle) {
  67055. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67056. return;
  67057. }
  67058. this._coneOuterAngle = value;
  67059. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67060. var sound = _a[_i];
  67061. sound.directionalConeOuterAngle = value;
  67062. }
  67063. }
  67064. },
  67065. enumerable: true,
  67066. configurable: true
  67067. });
  67068. Object.defineProperty(WeightedSound.prototype, "volume", {
  67069. /**
  67070. * Playback volume.
  67071. */
  67072. get: function () {
  67073. return this._volume;
  67074. },
  67075. /**
  67076. * Playback volume.
  67077. */
  67078. set: function (value) {
  67079. if (value !== this._volume) {
  67080. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  67081. var sound = _a[_i];
  67082. sound.setVolume(value);
  67083. }
  67084. }
  67085. },
  67086. enumerable: true,
  67087. configurable: true
  67088. });
  67089. WeightedSound.prototype._onended = function () {
  67090. if (this._currentIndex !== undefined) {
  67091. this._sounds[this._currentIndex].autoplay = false;
  67092. }
  67093. if (this.loop && this.isPlaying) {
  67094. this.play();
  67095. }
  67096. else {
  67097. this.isPlaying = false;
  67098. }
  67099. };
  67100. /**
  67101. * Suspend playback
  67102. */
  67103. WeightedSound.prototype.pause = function () {
  67104. this.isPaused = true;
  67105. if (this._currentIndex !== undefined) {
  67106. this._sounds[this._currentIndex].pause();
  67107. }
  67108. };
  67109. /**
  67110. * Stop playback
  67111. */
  67112. WeightedSound.prototype.stop = function () {
  67113. this.isPlaying = false;
  67114. if (this._currentIndex !== undefined) {
  67115. this._sounds[this._currentIndex].stop();
  67116. }
  67117. };
  67118. /**
  67119. * Start playback.
  67120. * @param startOffset Position the clip head at a specific time in seconds.
  67121. */
  67122. WeightedSound.prototype.play = function (startOffset) {
  67123. if (!this.isPaused) {
  67124. this.stop();
  67125. var randomValue = Math.random();
  67126. var total = 0;
  67127. for (var i = 0; i < this._weights.length; i++) {
  67128. total += this._weights[i];
  67129. if (randomValue <= total) {
  67130. this._currentIndex = i;
  67131. break;
  67132. }
  67133. }
  67134. }
  67135. var sound = this._sounds[this._currentIndex];
  67136. if (sound.isReady()) {
  67137. sound.play(0, this.isPaused ? undefined : startOffset);
  67138. }
  67139. else {
  67140. sound.autoplay = true;
  67141. }
  67142. this.isPlaying = true;
  67143. this.isPaused = false;
  67144. };
  67145. return WeightedSound;
  67146. }());
  67147. BABYLON.WeightedSound = WeightedSound;
  67148. })(BABYLON || (BABYLON = {}));
  67149. //# sourceMappingURL=babylon.weightedsound.js.map
  67150. var BABYLON;
  67151. (function (BABYLON) {
  67152. // Adds the parser to the scene parsers.
  67153. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  67154. // TODO: add sound
  67155. var loadedSounds = [];
  67156. var loadedSound;
  67157. container.sounds = container.sounds || [];
  67158. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67159. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67160. var parsedSound = parsedData.sounds[index];
  67161. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67162. if (!parsedSound.url)
  67163. parsedSound.url = parsedSound.name;
  67164. if (!loadedSounds[parsedSound.url]) {
  67165. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67166. loadedSounds[parsedSound.url] = loadedSound;
  67167. container.sounds.push(loadedSound);
  67168. }
  67169. else {
  67170. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67171. }
  67172. }
  67173. else {
  67174. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67175. }
  67176. }
  67177. }
  67178. loadedSounds = [];
  67179. });
  67180. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  67181. get: function () {
  67182. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67183. if (!compo) {
  67184. compo = new AudioSceneComponent(this);
  67185. this._addComponent(compo);
  67186. }
  67187. if (!this._mainSoundTrack) {
  67188. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  67189. }
  67190. return this._mainSoundTrack;
  67191. },
  67192. enumerable: true,
  67193. configurable: true
  67194. });
  67195. BABYLON.Scene.prototype.getSoundByName = function (name) {
  67196. var index;
  67197. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  67198. if (this.mainSoundTrack.soundCollection[index].name === name) {
  67199. return this.mainSoundTrack.soundCollection[index];
  67200. }
  67201. }
  67202. if (this.soundTracks) {
  67203. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  67204. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  67205. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  67206. return this.soundTracks[sdIndex].soundCollection[index];
  67207. }
  67208. }
  67209. }
  67210. }
  67211. return null;
  67212. };
  67213. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  67214. get: function () {
  67215. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67216. if (!compo) {
  67217. compo = new AudioSceneComponent(this);
  67218. this._addComponent(compo);
  67219. }
  67220. return compo.audioEnabled;
  67221. },
  67222. set: function (value) {
  67223. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67224. if (!compo) {
  67225. compo = new AudioSceneComponent(this);
  67226. this._addComponent(compo);
  67227. }
  67228. if (value) {
  67229. compo.enableAudio();
  67230. }
  67231. else {
  67232. compo.disableAudio();
  67233. }
  67234. },
  67235. enumerable: true,
  67236. configurable: true
  67237. });
  67238. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  67239. get: function () {
  67240. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67241. if (!compo) {
  67242. compo = new AudioSceneComponent(this);
  67243. this._addComponent(compo);
  67244. }
  67245. return compo.headphone;
  67246. },
  67247. set: function (value) {
  67248. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67249. if (!compo) {
  67250. compo = new AudioSceneComponent(this);
  67251. this._addComponent(compo);
  67252. }
  67253. if (value) {
  67254. compo.switchAudioModeForHeadphones();
  67255. }
  67256. else {
  67257. compo.switchAudioModeForNormalSpeakers();
  67258. }
  67259. },
  67260. enumerable: true,
  67261. configurable: true
  67262. });
  67263. /**
  67264. * Defines the sound scene component responsible to manage any sounds
  67265. * in a given scene.
  67266. */
  67267. var AudioSceneComponent = /** @class */ (function () {
  67268. /**
  67269. * Creates a new instance of the component for the given scene
  67270. * @param scene Defines the scene to register the component in
  67271. */
  67272. function AudioSceneComponent(scene) {
  67273. /**
  67274. * The component name helpfull to identify the component in the list of scene components.
  67275. */
  67276. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  67277. this._audioEnabled = true;
  67278. this._headphone = false;
  67279. this.scene = scene;
  67280. scene.soundTracks = new Array();
  67281. scene.sounds = new Array();
  67282. }
  67283. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  67284. /**
  67285. * Gets whether audio is enabled or not.
  67286. * Please use related enable/disable method to switch state.
  67287. */
  67288. get: function () {
  67289. return this._audioEnabled;
  67290. },
  67291. enumerable: true,
  67292. configurable: true
  67293. });
  67294. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  67295. /**
  67296. * Gets whether audio is outputing to headphone or not.
  67297. * Please use the according Switch methods to change output.
  67298. */
  67299. get: function () {
  67300. return this._headphone;
  67301. },
  67302. enumerable: true,
  67303. configurable: true
  67304. });
  67305. /**
  67306. * Registers the component in a given scene
  67307. */
  67308. AudioSceneComponent.prototype.register = function () {
  67309. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  67310. };
  67311. /**
  67312. * Rebuilds the elements related to this component in case of
  67313. * context lost for instance.
  67314. */
  67315. AudioSceneComponent.prototype.rebuild = function () {
  67316. // Nothing to do here. (Not rendering related)
  67317. };
  67318. /**
  67319. * Serializes the component data to the specified json object
  67320. * @param serializationObject The object to serialize to
  67321. */
  67322. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  67323. serializationObject.sounds = [];
  67324. if (this.scene.soundTracks) {
  67325. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  67326. var soundtrack = this.scene.soundTracks[index];
  67327. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67328. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67329. }
  67330. }
  67331. }
  67332. };
  67333. /**
  67334. * Adds all the element from the container to the scene
  67335. * @param container the container holding the elements
  67336. */
  67337. AudioSceneComponent.prototype.addFromContainer = function (container) {
  67338. var _this = this;
  67339. if (!container.sounds) {
  67340. return;
  67341. }
  67342. container.sounds.forEach(function (sound) {
  67343. sound.play();
  67344. sound.autoplay = true;
  67345. _this.scene.mainSoundTrack.AddSound(sound);
  67346. });
  67347. };
  67348. /**
  67349. * Removes all the elements in the container from the scene
  67350. * @param container contains the elements to remove
  67351. */
  67352. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  67353. var _this = this;
  67354. if (!container.sounds) {
  67355. return;
  67356. }
  67357. container.sounds.forEach(function (sound) {
  67358. sound.stop();
  67359. sound.autoplay = false;
  67360. _this.scene.mainSoundTrack.RemoveSound(sound);
  67361. });
  67362. };
  67363. /**
  67364. * Disposes the component and the associated ressources.
  67365. */
  67366. AudioSceneComponent.prototype.dispose = function () {
  67367. var scene = this.scene;
  67368. if (scene._mainSoundTrack) {
  67369. scene.mainSoundTrack.dispose();
  67370. }
  67371. if (scene.soundTracks) {
  67372. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  67373. scene.soundTracks[scIndex].dispose();
  67374. }
  67375. }
  67376. };
  67377. /**
  67378. * Disables audio in the associated scene.
  67379. */
  67380. AudioSceneComponent.prototype.disableAudio = function () {
  67381. var scene = this.scene;
  67382. this._audioEnabled = false;
  67383. var i;
  67384. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67385. scene.mainSoundTrack.soundCollection[i].pause();
  67386. }
  67387. if (scene.soundTracks) {
  67388. for (i = 0; i < scene.soundTracks.length; i++) {
  67389. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67390. scene.soundTracks[i].soundCollection[j].pause();
  67391. }
  67392. }
  67393. }
  67394. };
  67395. /**
  67396. * Enables audio in the associated scene.
  67397. */
  67398. AudioSceneComponent.prototype.enableAudio = function () {
  67399. var scene = this.scene;
  67400. this._audioEnabled = true;
  67401. var i;
  67402. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67403. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  67404. scene.mainSoundTrack.soundCollection[i].play();
  67405. }
  67406. }
  67407. if (scene.soundTracks) {
  67408. for (i = 0; i < scene.soundTracks.length; i++) {
  67409. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67410. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  67411. scene.soundTracks[i].soundCollection[j].play();
  67412. }
  67413. }
  67414. }
  67415. }
  67416. };
  67417. /**
  67418. * Switch audio to headphone output.
  67419. */
  67420. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  67421. var scene = this.scene;
  67422. this._headphone = true;
  67423. scene.mainSoundTrack.switchPanningModelToHRTF();
  67424. if (scene.soundTracks) {
  67425. for (var i = 0; i < scene.soundTracks.length; i++) {
  67426. scene.soundTracks[i].switchPanningModelToHRTF();
  67427. }
  67428. }
  67429. };
  67430. /**
  67431. * Switch audio to normal speakers.
  67432. */
  67433. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  67434. var scene = this.scene;
  67435. this._headphone = false;
  67436. scene.mainSoundTrack.switchPanningModelToEqualPower();
  67437. if (scene.soundTracks) {
  67438. for (var i = 0; i < scene.soundTracks.length; i++) {
  67439. scene.soundTracks[i].switchPanningModelToEqualPower();
  67440. }
  67441. }
  67442. };
  67443. AudioSceneComponent.prototype._afterRender = function () {
  67444. var scene = this.scene;
  67445. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  67446. return;
  67447. }
  67448. var listeningCamera;
  67449. var audioEngine = BABYLON.Engine.audioEngine;
  67450. if (scene.activeCameras.length > 0) {
  67451. listeningCamera = scene.activeCameras[0];
  67452. }
  67453. else {
  67454. listeningCamera = scene.activeCamera;
  67455. }
  67456. if (listeningCamera && audioEngine.audioContext) {
  67457. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  67458. // for VR cameras
  67459. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  67460. listeningCamera = listeningCamera.rigCameras[0];
  67461. }
  67462. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  67463. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  67464. cameraDirection.normalize();
  67465. // To avoid some errors on GearVR
  67466. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  67467. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  67468. }
  67469. var i;
  67470. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67471. var sound = scene.mainSoundTrack.soundCollection[i];
  67472. if (sound.useCustomAttenuation) {
  67473. sound.updateDistanceFromListener();
  67474. }
  67475. }
  67476. if (scene.soundTracks) {
  67477. for (i = 0; i < scene.soundTracks.length; i++) {
  67478. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67479. sound = scene.soundTracks[i].soundCollection[j];
  67480. if (sound.useCustomAttenuation) {
  67481. sound.updateDistanceFromListener();
  67482. }
  67483. }
  67484. }
  67485. }
  67486. }
  67487. };
  67488. return AudioSceneComponent;
  67489. }());
  67490. BABYLON.AudioSceneComponent = AudioSceneComponent;
  67491. })(BABYLON || (BABYLON = {}));
  67492. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  67493. var BABYLON;
  67494. (function (BABYLON) {
  67495. /**
  67496. * This defines an action helpful to play a defined sound on a triggered action.
  67497. */
  67498. var PlaySoundAction = /** @class */ (function (_super) {
  67499. __extends(PlaySoundAction, _super);
  67500. /**
  67501. * Instantiate the action
  67502. * @param triggerOptions defines the trigger options
  67503. * @param sound defines the sound to play
  67504. * @param condition defines the trigger related conditions
  67505. */
  67506. function PlaySoundAction(triggerOptions, sound, condition) {
  67507. var _this = _super.call(this, triggerOptions, condition) || this;
  67508. _this._sound = sound;
  67509. return _this;
  67510. }
  67511. /** @hidden */
  67512. PlaySoundAction.prototype._prepare = function () {
  67513. };
  67514. /**
  67515. * Execute the action and play the sound.
  67516. */
  67517. PlaySoundAction.prototype.execute = function () {
  67518. if (this._sound !== undefined)
  67519. this._sound.play();
  67520. };
  67521. /**
  67522. * Serializes the actions and its related information.
  67523. * @param parent defines the object to serialize in
  67524. * @returns the serialized object
  67525. */
  67526. PlaySoundAction.prototype.serialize = function (parent) {
  67527. return _super.prototype._serialize.call(this, {
  67528. name: "PlaySoundAction",
  67529. properties: [{ name: "sound", value: this._sound.name }]
  67530. }, parent);
  67531. };
  67532. return PlaySoundAction;
  67533. }(BABYLON.Action));
  67534. BABYLON.PlaySoundAction = PlaySoundAction;
  67535. /**
  67536. * This defines an action helpful to stop a defined sound on a triggered action.
  67537. */
  67538. var StopSoundAction = /** @class */ (function (_super) {
  67539. __extends(StopSoundAction, _super);
  67540. /**
  67541. * Instantiate the action
  67542. * @param triggerOptions defines the trigger options
  67543. * @param sound defines the sound to stop
  67544. * @param condition defines the trigger related conditions
  67545. */
  67546. function StopSoundAction(triggerOptions, sound, condition) {
  67547. var _this = _super.call(this, triggerOptions, condition) || this;
  67548. _this._sound = sound;
  67549. return _this;
  67550. }
  67551. /** @hidden */
  67552. StopSoundAction.prototype._prepare = function () {
  67553. };
  67554. /**
  67555. * Execute the action and stop the sound.
  67556. */
  67557. StopSoundAction.prototype.execute = function () {
  67558. if (this._sound !== undefined)
  67559. this._sound.stop();
  67560. };
  67561. /**
  67562. * Serializes the actions and its related information.
  67563. * @param parent defines the object to serialize in
  67564. * @returns the serialized object
  67565. */
  67566. StopSoundAction.prototype.serialize = function (parent) {
  67567. return _super.prototype._serialize.call(this, {
  67568. name: "StopSoundAction",
  67569. properties: [{ name: "sound", value: this._sound.name }]
  67570. }, parent);
  67571. };
  67572. return StopSoundAction;
  67573. }(BABYLON.Action));
  67574. BABYLON.StopSoundAction = StopSoundAction;
  67575. })(BABYLON || (BABYLON = {}));
  67576. //# sourceMappingURL=babylon.directAudioActions.js.map
  67577. var BABYLON;
  67578. (function (BABYLON) {
  67579. var CubeTexture = /** @class */ (function (_super) {
  67580. __extends(CubeTexture, _super);
  67581. /**
  67582. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67583. * as prefiltered data.
  67584. * @param rootUrl defines the url of the texture or the root name of the six images
  67585. * @param scene defines the scene the texture is attached to
  67586. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67587. * @param noMipmap defines if mipmaps should be created or not
  67588. * @param files defines the six files to load for the different faces
  67589. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67590. * @param onError defines a callback triggered in case of error during load
  67591. * @param format defines the internal format to use for the texture once loaded
  67592. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67593. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67594. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67595. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67596. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67597. * @return the cube texture
  67598. */
  67599. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67600. if (extensions === void 0) { extensions = null; }
  67601. if (noMipmap === void 0) { noMipmap = false; }
  67602. if (files === void 0) { files = null; }
  67603. if (onLoad === void 0) { onLoad = null; }
  67604. if (onError === void 0) { onError = null; }
  67605. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67606. if (prefiltered === void 0) { prefiltered = false; }
  67607. if (forcedExtension === void 0) { forcedExtension = null; }
  67608. if (createPolynomials === void 0) { createPolynomials = false; }
  67609. if (lodScale === void 0) { lodScale = 0.8; }
  67610. if (lodOffset === void 0) { lodOffset = 0; }
  67611. var _this = _super.call(this, scene) || this;
  67612. /**
  67613. * Gets or sets the center of the bounding box associated with the cube texture
  67614. * It must define where the camera used to render the texture was set
  67615. */
  67616. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67617. _this._rotationY = 0;
  67618. /** @hidden */
  67619. _this._prefiltered = false;
  67620. _this.name = rootUrl;
  67621. _this.url = rootUrl;
  67622. _this._noMipmap = noMipmap;
  67623. _this.hasAlpha = false;
  67624. _this._format = format;
  67625. _this.isCube = true;
  67626. _this._textureMatrix = BABYLON.Matrix.Identity();
  67627. _this._createPolynomials = createPolynomials;
  67628. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67629. if (!rootUrl && !files) {
  67630. return _this;
  67631. }
  67632. var lastDot = rootUrl.lastIndexOf(".");
  67633. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67634. var isDDS = (extension === ".dds");
  67635. var isEnv = (extension === ".env");
  67636. if (isEnv) {
  67637. _this.gammaSpace = false;
  67638. _this._prefiltered = false;
  67639. }
  67640. else {
  67641. _this._prefiltered = prefiltered;
  67642. if (prefiltered) {
  67643. _this.gammaSpace = false;
  67644. }
  67645. }
  67646. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67647. if (!files) {
  67648. if (!isEnv && !isDDS && !extensions) {
  67649. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67650. }
  67651. files = [];
  67652. if (extensions) {
  67653. for (var index = 0; index < extensions.length; index++) {
  67654. files.push(rootUrl + extensions[index]);
  67655. }
  67656. }
  67657. }
  67658. _this._files = files;
  67659. if (!_this._texture) {
  67660. if (!scene.useDelayedTextureLoading) {
  67661. if (prefiltered) {
  67662. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67663. }
  67664. else {
  67665. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67666. }
  67667. }
  67668. else {
  67669. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67670. }
  67671. }
  67672. else if (onLoad) {
  67673. if (_this._texture.isReady) {
  67674. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67675. }
  67676. else {
  67677. _this._texture.onLoadedObservable.add(onLoad);
  67678. }
  67679. }
  67680. return _this;
  67681. }
  67682. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67683. get: function () {
  67684. return this._boundingBoxSize;
  67685. },
  67686. /**
  67687. * Gets or sets the size of the bounding box associated with the cube texture
  67688. * When defined, the cubemap will switch to local mode
  67689. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67690. * @example https://www.babylonjs-playground.com/#RNASML
  67691. */
  67692. set: function (value) {
  67693. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67694. return;
  67695. }
  67696. this._boundingBoxSize = value;
  67697. var scene = this.getScene();
  67698. if (scene) {
  67699. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67700. }
  67701. },
  67702. enumerable: true,
  67703. configurable: true
  67704. });
  67705. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67706. /**
  67707. * Gets texture matrix rotation angle around Y axis radians.
  67708. */
  67709. get: function () {
  67710. return this._rotationY;
  67711. },
  67712. /**
  67713. * Sets texture matrix rotation angle around Y axis in radians.
  67714. */
  67715. set: function (value) {
  67716. this._rotationY = value;
  67717. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67718. },
  67719. enumerable: true,
  67720. configurable: true
  67721. });
  67722. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67723. var rootUrlKey = "";
  67724. files.forEach(function (url) { return rootUrlKey += url; });
  67725. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67726. };
  67727. /**
  67728. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67729. * @param url defines the url of the prefiltered texture
  67730. * @param scene defines the scene the texture is attached to
  67731. * @param forcedExtension defines the extension of the file if different from the url
  67732. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67733. * @return the prefiltered texture
  67734. */
  67735. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67736. if (forcedExtension === void 0) { forcedExtension = null; }
  67737. if (createPolynomials === void 0) { createPolynomials = true; }
  67738. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67739. };
  67740. // Methods
  67741. CubeTexture.prototype.delayLoad = function () {
  67742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67743. return;
  67744. }
  67745. var scene = this.getScene();
  67746. if (!scene) {
  67747. return;
  67748. }
  67749. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67750. this._texture = this._getFromCache(this.url, this._noMipmap);
  67751. if (!this._texture) {
  67752. if (this._prefiltered) {
  67753. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67754. }
  67755. else {
  67756. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67757. }
  67758. }
  67759. };
  67760. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67761. return this._textureMatrix;
  67762. };
  67763. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67764. this._textureMatrix = value;
  67765. };
  67766. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67767. var texture = BABYLON.SerializationHelper.Parse(function () {
  67768. var prefiltered = false;
  67769. if (parsedTexture.prefiltered) {
  67770. prefiltered = parsedTexture.prefiltered;
  67771. }
  67772. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67773. }, parsedTexture, scene);
  67774. // Local Cubemaps
  67775. if (parsedTexture.boundingBoxPosition) {
  67776. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67777. }
  67778. if (parsedTexture.boundingBoxSize) {
  67779. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67780. }
  67781. // Animations
  67782. if (parsedTexture.animations) {
  67783. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67784. var parsedAnimation = parsedTexture.animations[animationIndex];
  67785. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67786. }
  67787. }
  67788. return texture;
  67789. };
  67790. CubeTexture.prototype.clone = function () {
  67791. var _this = this;
  67792. return BABYLON.SerializationHelper.Clone(function () {
  67793. var scene = _this.getScene();
  67794. if (!scene) {
  67795. return _this;
  67796. }
  67797. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67798. }, this);
  67799. };
  67800. __decorate([
  67801. BABYLON.serialize("rotationY")
  67802. ], CubeTexture.prototype, "rotationY", null);
  67803. return CubeTexture;
  67804. }(BABYLON.BaseTexture));
  67805. BABYLON.CubeTexture = CubeTexture;
  67806. })(BABYLON || (BABYLON = {}));
  67807. //# sourceMappingURL=babylon.cubeTexture.js.map
  67808. var BABYLON;
  67809. (function (BABYLON) {
  67810. /**
  67811. * Raw cube texture where the raw buffers are passed in
  67812. */
  67813. var RawCubeTexture = /** @class */ (function (_super) {
  67814. __extends(RawCubeTexture, _super);
  67815. /**
  67816. * Creates a cube texture where the raw buffers are passed in.
  67817. * @param scene defines the scene the texture is attached to
  67818. * @param data defines the array of data to use to create each face
  67819. * @param size defines the size of the textures
  67820. * @param format defines the format of the data
  67821. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67822. * @param generateMipMaps defines if the engine should generate the mip levels
  67823. * @param invertY defines if data must be stored with Y axis inverted
  67824. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67825. * @param compression defines the compression used (null by default)
  67826. */
  67827. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67828. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67829. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67830. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67831. if (invertY === void 0) { invertY = false; }
  67832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67833. if (compression === void 0) { compression = null; }
  67834. var _this = _super.call(this, "", scene) || this;
  67835. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67836. return _this;
  67837. }
  67838. /**
  67839. * Updates the raw cube texture.
  67840. * @param data defines the data to store
  67841. * @param format defines the data format
  67842. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67843. * @param invertY defines if data must be stored with Y axis inverted
  67844. * @param compression defines the compression used (null by default)
  67845. * @param level defines which level of the texture to update
  67846. */
  67847. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67848. if (compression === void 0) { compression = null; }
  67849. if (level === void 0) { level = 0; }
  67850. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67851. };
  67852. /**
  67853. * Updates a raw cube texture with RGBD encoded data.
  67854. * @param data defines the array of data [mipmap][face] to use to create each face
  67855. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67856. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67857. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67858. * @returns a promsie that resolves when the operation is complete
  67859. */
  67860. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67861. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67862. if (lodScale === void 0) { lodScale = 0.8; }
  67863. if (lodOffset === void 0) { lodOffset = 0; }
  67864. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67865. };
  67866. /**
  67867. * Clones the raw cube texture.
  67868. * @return a new cube texture
  67869. */
  67870. RawCubeTexture.prototype.clone = function () {
  67871. var _this = this;
  67872. return BABYLON.SerializationHelper.Clone(function () {
  67873. var scene = _this.getScene();
  67874. var internalTexture = _this._texture;
  67875. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67876. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67877. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67878. }
  67879. return texture;
  67880. }, this);
  67881. };
  67882. /** @hidden */
  67883. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67884. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67885. internalTexture._bufferViewArrayArray = data;
  67886. internalTexture._lodGenerationScale = lodScale;
  67887. internalTexture._lodGenerationOffset = lodOffset;
  67888. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67889. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67890. internalTexture.isReady = true;
  67891. });
  67892. };
  67893. return RawCubeTexture;
  67894. }(BABYLON.CubeTexture));
  67895. BABYLON.RawCubeTexture = RawCubeTexture;
  67896. })(BABYLON || (BABYLON = {}));
  67897. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67898. var BABYLON;
  67899. (function (BABYLON) {
  67900. var RenderTargetTexture = /** @class */ (function (_super) {
  67901. __extends(RenderTargetTexture, _super);
  67902. /**
  67903. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67904. * or used a shadow, depth texture...
  67905. * @param name The friendly name of the texture
  67906. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  67907. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67908. * @param generateMipMaps True if mip maps need to be generated after render.
  67909. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67910. * @param type The type of the buffer in the RTT (int, half float, float...)
  67911. * @param isCube True if a cube texture needs to be created
  67912. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67913. * @param generateDepthBuffer True to generate a depth buffer
  67914. * @param generateStencilBuffer True to generate a stencil buffer
  67915. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67916. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67917. */
  67918. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67919. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67920. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67921. if (isCube === void 0) { isCube = false; }
  67922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67923. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67924. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67925. if (isMulti === void 0) { isMulti = false; }
  67926. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67927. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67928. _this.isCube = isCube;
  67929. _this.renderParticles = true;
  67930. _this.renderSprites = false;
  67931. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67932. _this.ignoreCameraViewport = false;
  67933. // Events
  67934. /**
  67935. * An event triggered when the texture is unbind.
  67936. */
  67937. _this.onBeforeBindObservable = new BABYLON.Observable();
  67938. /**
  67939. * An event triggered when the texture is unbind.
  67940. */
  67941. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67942. /**
  67943. * An event triggered before rendering the texture
  67944. */
  67945. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67946. /**
  67947. * An event triggered after rendering the texture
  67948. */
  67949. _this.onAfterRenderObservable = new BABYLON.Observable();
  67950. /**
  67951. * An event triggered after the texture clear
  67952. */
  67953. _this.onClearObservable = new BABYLON.Observable();
  67954. _this._currentRefreshId = -1;
  67955. _this._refreshRate = 1;
  67956. _this._samples = 1;
  67957. /**
  67958. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67959. * It must define where the camera used to render the texture is set
  67960. */
  67961. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67962. scene = _this.getScene();
  67963. if (!scene) {
  67964. return _this;
  67965. }
  67966. _this.renderList = new Array();
  67967. _this._engine = scene.getEngine();
  67968. _this.name = name;
  67969. _this.isRenderTarget = true;
  67970. _this._initialSizeParameter = size;
  67971. _this._processSizeParameter(size);
  67972. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67973. });
  67974. _this._generateMipMaps = generateMipMaps ? true : false;
  67975. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67976. // Rendering groups
  67977. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67978. _this._renderingManager._useSceneAutoClearSetup = true;
  67979. if (isMulti) {
  67980. return _this;
  67981. }
  67982. _this._renderTargetOptions = {
  67983. generateMipMaps: generateMipMaps,
  67984. type: type,
  67985. format: format,
  67986. samplingMode: samplingMode,
  67987. generateDepthBuffer: generateDepthBuffer,
  67988. generateStencilBuffer: generateStencilBuffer
  67989. };
  67990. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67991. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67992. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67993. }
  67994. if (isCube) {
  67995. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67996. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67997. _this._textureMatrix = BABYLON.Matrix.Identity();
  67998. }
  67999. else {
  68000. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  68001. }
  68002. return _this;
  68003. }
  68004. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  68005. get: function () {
  68006. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  68007. },
  68008. enumerable: true,
  68009. configurable: true
  68010. });
  68011. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  68012. get: function () {
  68013. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  68014. },
  68015. enumerable: true,
  68016. configurable: true
  68017. });
  68018. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  68019. get: function () {
  68020. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  68021. },
  68022. enumerable: true,
  68023. configurable: true
  68024. });
  68025. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  68026. /**
  68027. * Use this list to define the list of mesh you want to render.
  68028. */
  68029. get: function () {
  68030. return this._renderList;
  68031. },
  68032. set: function (value) {
  68033. this._renderList = value;
  68034. if (this._renderList) {
  68035. this._hookArray(this._renderList);
  68036. }
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. RenderTargetTexture.prototype._hookArray = function (array) {
  68042. var _this = this;
  68043. var oldPush = array.push;
  68044. array.push = function () {
  68045. var items = [];
  68046. for (var _i = 0; _i < arguments.length; _i++) {
  68047. items[_i] = arguments[_i];
  68048. }
  68049. var result = oldPush.apply(array, items);
  68050. _this.getScene().meshes.forEach(function (mesh) {
  68051. mesh._markSubMeshesAsLightDirty();
  68052. });
  68053. return result;
  68054. };
  68055. var oldSplice = array.splice;
  68056. array.splice = function (index, deleteCount) {
  68057. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68058. _this.getScene().meshes.forEach(function (mesh) {
  68059. mesh._markSubMeshesAsLightDirty();
  68060. });
  68061. return deleted;
  68062. };
  68063. };
  68064. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  68065. set: function (callback) {
  68066. if (this._onAfterUnbindObserver) {
  68067. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  68068. }
  68069. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  68070. },
  68071. enumerable: true,
  68072. configurable: true
  68073. });
  68074. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  68075. set: function (callback) {
  68076. if (this._onBeforeRenderObserver) {
  68077. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68078. }
  68079. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68080. },
  68081. enumerable: true,
  68082. configurable: true
  68083. });
  68084. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  68085. set: function (callback) {
  68086. if (this._onAfterRenderObserver) {
  68087. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68088. }
  68089. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68090. },
  68091. enumerable: true,
  68092. configurable: true
  68093. });
  68094. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  68095. set: function (callback) {
  68096. if (this._onClearObserver) {
  68097. this.onClearObservable.remove(this._onClearObserver);
  68098. }
  68099. this._onClearObserver = this.onClearObservable.add(callback);
  68100. },
  68101. enumerable: true,
  68102. configurable: true
  68103. });
  68104. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  68105. get: function () {
  68106. return this._renderTargetOptions;
  68107. },
  68108. enumerable: true,
  68109. configurable: true
  68110. });
  68111. RenderTargetTexture.prototype._onRatioRescale = function () {
  68112. if (this._sizeRatio) {
  68113. this.resize(this._initialSizeParameter);
  68114. }
  68115. };
  68116. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  68117. get: function () {
  68118. return this._boundingBoxSize;
  68119. },
  68120. /**
  68121. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  68122. * When defined, the cubemap will switch to local mode
  68123. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  68124. * @example https://www.babylonjs-playground.com/#RNASML
  68125. */
  68126. set: function (value) {
  68127. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  68128. return;
  68129. }
  68130. this._boundingBoxSize = value;
  68131. var scene = this.getScene();
  68132. if (scene) {
  68133. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  68134. }
  68135. },
  68136. enumerable: true,
  68137. configurable: true
  68138. });
  68139. /**
  68140. * Creates a depth stencil texture.
  68141. * This is only available in WebGL 2 or with the depth texture extension available.
  68142. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  68143. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  68144. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  68145. */
  68146. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  68147. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  68148. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  68149. if (generateStencil === void 0) { generateStencil = false; }
  68150. if (!this.getScene()) {
  68151. return;
  68152. }
  68153. var engine = this.getScene().getEngine();
  68154. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  68155. bilinearFiltering: bilinearFiltering,
  68156. comparisonFunction: comparisonFunction,
  68157. generateStencil: generateStencil,
  68158. isCube: this.isCube
  68159. });
  68160. engine.setFrameBufferDepthStencilTexture(this);
  68161. };
  68162. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  68163. if (size.ratio) {
  68164. this._sizeRatio = size.ratio;
  68165. this._size = {
  68166. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  68167. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  68168. };
  68169. }
  68170. else {
  68171. this._size = size;
  68172. }
  68173. };
  68174. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  68175. get: function () {
  68176. return this._samples;
  68177. },
  68178. set: function (value) {
  68179. if (this._samples === value) {
  68180. return;
  68181. }
  68182. var scene = this.getScene();
  68183. if (!scene) {
  68184. return;
  68185. }
  68186. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  68187. },
  68188. enumerable: true,
  68189. configurable: true
  68190. });
  68191. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  68192. this._currentRefreshId = -1;
  68193. };
  68194. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  68195. get: function () {
  68196. return this._refreshRate;
  68197. },
  68198. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68199. set: function (value) {
  68200. this._refreshRate = value;
  68201. this.resetRefreshCounter();
  68202. },
  68203. enumerable: true,
  68204. configurable: true
  68205. });
  68206. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  68207. if (!this._postProcessManager) {
  68208. var scene = this.getScene();
  68209. if (!scene) {
  68210. return;
  68211. }
  68212. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  68213. this._postProcesses = new Array();
  68214. }
  68215. this._postProcesses.push(postProcess);
  68216. this._postProcesses[0].autoClear = false;
  68217. };
  68218. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  68219. if (!this._postProcesses) {
  68220. return;
  68221. }
  68222. if (dispose) {
  68223. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  68224. var postProcess = _a[_i];
  68225. postProcess.dispose();
  68226. }
  68227. }
  68228. this._postProcesses = [];
  68229. };
  68230. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  68231. if (!this._postProcesses) {
  68232. return;
  68233. }
  68234. var index = this._postProcesses.indexOf(postProcess);
  68235. if (index === -1) {
  68236. return;
  68237. }
  68238. this._postProcesses.splice(index, 1);
  68239. if (this._postProcesses.length > 0) {
  68240. this._postProcesses[0].autoClear = false;
  68241. }
  68242. };
  68243. /** @hidden */
  68244. RenderTargetTexture.prototype._shouldRender = function () {
  68245. if (this._currentRefreshId === -1) { // At least render once
  68246. this._currentRefreshId = 1;
  68247. return true;
  68248. }
  68249. if (this.refreshRate === this._currentRefreshId) {
  68250. this._currentRefreshId = 1;
  68251. return true;
  68252. }
  68253. this._currentRefreshId++;
  68254. return false;
  68255. };
  68256. RenderTargetTexture.prototype.getRenderSize = function () {
  68257. if (this._size.width) {
  68258. return this._size.width;
  68259. }
  68260. return this._size;
  68261. };
  68262. RenderTargetTexture.prototype.getRenderWidth = function () {
  68263. if (this._size.width) {
  68264. return this._size.width;
  68265. }
  68266. return this._size;
  68267. };
  68268. RenderTargetTexture.prototype.getRenderHeight = function () {
  68269. if (this._size.width) {
  68270. return this._size.height;
  68271. }
  68272. return this._size;
  68273. };
  68274. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  68275. get: function () {
  68276. return true;
  68277. },
  68278. enumerable: true,
  68279. configurable: true
  68280. });
  68281. RenderTargetTexture.prototype.scale = function (ratio) {
  68282. var newSize = this.getRenderSize() * ratio;
  68283. this.resize(newSize);
  68284. };
  68285. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  68286. if (this.isCube) {
  68287. return this._textureMatrix;
  68288. }
  68289. return _super.prototype.getReflectionTextureMatrix.call(this);
  68290. };
  68291. RenderTargetTexture.prototype.resize = function (size) {
  68292. this.releaseInternalTexture();
  68293. var scene = this.getScene();
  68294. if (!scene) {
  68295. return;
  68296. }
  68297. this._processSizeParameter(size);
  68298. if (this.isCube) {
  68299. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  68300. }
  68301. else {
  68302. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  68303. }
  68304. };
  68305. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  68306. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  68307. if (dumpForDebug === void 0) { dumpForDebug = false; }
  68308. var scene = this.getScene();
  68309. if (!scene) {
  68310. return;
  68311. }
  68312. var engine = scene.getEngine();
  68313. if (this.useCameraPostProcesses !== undefined) {
  68314. useCameraPostProcess = this.useCameraPostProcesses;
  68315. }
  68316. if (this._waitingRenderList) {
  68317. this.renderList = [];
  68318. for (var index = 0; index < this._waitingRenderList.length; index++) {
  68319. var id = this._waitingRenderList[index];
  68320. var mesh_1 = scene.getMeshByID(id);
  68321. if (mesh_1) {
  68322. this.renderList.push(mesh_1);
  68323. }
  68324. }
  68325. delete this._waitingRenderList;
  68326. }
  68327. // Is predicate defined?
  68328. if (this.renderListPredicate) {
  68329. if (this.renderList) {
  68330. this.renderList.splice(0); // Clear previous renderList
  68331. }
  68332. else {
  68333. this.renderList = [];
  68334. }
  68335. var scene = this.getScene();
  68336. if (!scene) {
  68337. return;
  68338. }
  68339. var sceneMeshes = scene.meshes;
  68340. for (var index = 0; index < sceneMeshes.length; index++) {
  68341. var mesh = sceneMeshes[index];
  68342. if (this.renderListPredicate(mesh)) {
  68343. this.renderList.push(mesh);
  68344. }
  68345. }
  68346. }
  68347. this.onBeforeBindObservable.notifyObservers(this);
  68348. // Set custom projection.
  68349. // Needs to be before binding to prevent changing the aspect ratio.
  68350. var camera;
  68351. if (this.activeCamera) {
  68352. camera = this.activeCamera;
  68353. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68354. if (this.activeCamera !== scene.activeCamera) {
  68355. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  68356. }
  68357. }
  68358. else {
  68359. camera = scene.activeCamera;
  68360. if (camera) {
  68361. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68362. }
  68363. }
  68364. // Prepare renderingManager
  68365. this._renderingManager.reset();
  68366. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  68367. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  68368. var sceneRenderId = scene.getRenderId();
  68369. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  68370. var mesh = currentRenderList[meshIndex];
  68371. if (mesh) {
  68372. if (!mesh.isReady(this.refreshRate === 0)) {
  68373. this.resetRefreshCounter();
  68374. continue;
  68375. }
  68376. mesh._preActivateForIntermediateRendering(sceneRenderId);
  68377. var isMasked = void 0;
  68378. if (!this.renderList && camera) {
  68379. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  68380. }
  68381. else {
  68382. isMasked = false;
  68383. }
  68384. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  68385. mesh._activate(sceneRenderId);
  68386. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  68387. var subMesh = mesh.subMeshes[subIndex];
  68388. scene._activeIndices.addCount(subMesh.indexCount, false);
  68389. this._renderingManager.dispatch(subMesh, mesh);
  68390. }
  68391. }
  68392. }
  68393. }
  68394. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  68395. var particleSystem = scene.particleSystems[particleIndex];
  68396. var emitter = particleSystem.emitter;
  68397. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  68398. continue;
  68399. }
  68400. if (currentRenderList.indexOf(emitter) >= 0) {
  68401. this._renderingManager.dispatchParticles(particleSystem);
  68402. }
  68403. }
  68404. if (this.isCube) {
  68405. for (var face = 0; face < 6; face++) {
  68406. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68407. scene.incrementRenderId();
  68408. scene.resetCachedMaterial();
  68409. }
  68410. }
  68411. else {
  68412. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68413. }
  68414. this.onAfterUnbindObservable.notifyObservers(this);
  68415. if (scene.activeCamera) {
  68416. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  68417. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  68418. }
  68419. engine.setViewport(scene.activeCamera.viewport);
  68420. }
  68421. scene.resetCachedMaterial();
  68422. };
  68423. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  68424. var minimum = 128;
  68425. var x = renderDimension * scale;
  68426. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  68427. // Ensure we don't exceed the render dimension (while staying POT)
  68428. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  68429. };
  68430. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68431. var _this = this;
  68432. if (!this._texture) {
  68433. return;
  68434. }
  68435. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  68436. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68437. });
  68438. };
  68439. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  68440. var scene = this.getScene();
  68441. if (!scene) {
  68442. return;
  68443. }
  68444. var engine = scene.getEngine();
  68445. if (!this._texture) {
  68446. return;
  68447. }
  68448. // Bind
  68449. if (this._postProcessManager) {
  68450. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  68451. }
  68452. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  68453. if (this._texture) {
  68454. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  68455. }
  68456. }
  68457. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  68458. // Clear
  68459. if (this.onClearObservable.hasObservers()) {
  68460. this.onClearObservable.notifyObservers(engine);
  68461. }
  68462. else {
  68463. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  68464. }
  68465. if (!this._doNotChangeAspectRatio) {
  68466. scene.updateTransformMatrix(true);
  68467. }
  68468. // Render
  68469. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  68470. if (this._postProcessManager) {
  68471. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  68472. }
  68473. else if (useCameraPostProcess) {
  68474. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  68475. }
  68476. if (!this._doNotChangeAspectRatio) {
  68477. scene.updateTransformMatrix(true);
  68478. }
  68479. // Dump ?
  68480. if (dumpForDebug) {
  68481. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  68482. }
  68483. // Unbind
  68484. if (!this.isCube || faceIndex === 5) {
  68485. if (this.isCube) {
  68486. if (faceIndex === 5) {
  68487. engine.generateMipMapsForCubemap(this._texture);
  68488. }
  68489. }
  68490. this.unbindFrameBuffer(engine, faceIndex);
  68491. }
  68492. else {
  68493. this.onAfterRenderObservable.notifyObservers(faceIndex);
  68494. }
  68495. };
  68496. /**
  68497. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  68498. * This allowed control for front to back rendering or reversly depending of the special needs.
  68499. *
  68500. * @param renderingGroupId The rendering group id corresponding to its index
  68501. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  68502. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  68503. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  68504. */
  68505. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  68506. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  68507. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  68508. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  68509. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  68510. };
  68511. /**
  68512. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68513. *
  68514. * @param renderingGroupId The rendering group id corresponding to its index
  68515. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68516. */
  68517. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68518. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68519. this._renderingManager._useSceneAutoClearSetup = false;
  68520. };
  68521. RenderTargetTexture.prototype.clone = function () {
  68522. var textureSize = this.getSize();
  68523. 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);
  68524. // Base texture
  68525. newTexture.hasAlpha = this.hasAlpha;
  68526. newTexture.level = this.level;
  68527. // RenderTarget Texture
  68528. newTexture.coordinatesMode = this.coordinatesMode;
  68529. if (this.renderList) {
  68530. newTexture.renderList = this.renderList.slice(0);
  68531. }
  68532. return newTexture;
  68533. };
  68534. RenderTargetTexture.prototype.serialize = function () {
  68535. if (!this.name) {
  68536. return null;
  68537. }
  68538. var serializationObject = _super.prototype.serialize.call(this);
  68539. serializationObject.renderTargetSize = this.getRenderSize();
  68540. serializationObject.renderList = [];
  68541. if (this.renderList) {
  68542. for (var index = 0; index < this.renderList.length; index++) {
  68543. serializationObject.renderList.push(this.renderList[index].id);
  68544. }
  68545. }
  68546. return serializationObject;
  68547. };
  68548. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68549. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68550. var objBuffer = this.getInternalTexture();
  68551. var scene = this.getScene();
  68552. if (objBuffer && scene) {
  68553. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68554. }
  68555. };
  68556. RenderTargetTexture.prototype.dispose = function () {
  68557. if (this._postProcessManager) {
  68558. this._postProcessManager.dispose();
  68559. this._postProcessManager = null;
  68560. }
  68561. this.clearPostProcesses(true);
  68562. if (this._resizeObserver) {
  68563. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68564. this._resizeObserver = null;
  68565. }
  68566. this.renderList = null;
  68567. // Remove from custom render targets
  68568. var scene = this.getScene();
  68569. if (!scene) {
  68570. return;
  68571. }
  68572. var index = scene.customRenderTargets.indexOf(this);
  68573. if (index >= 0) {
  68574. scene.customRenderTargets.splice(index, 1);
  68575. }
  68576. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68577. var camera = _a[_i];
  68578. index = camera.customRenderTargets.indexOf(this);
  68579. if (index >= 0) {
  68580. camera.customRenderTargets.splice(index, 1);
  68581. }
  68582. }
  68583. _super.prototype.dispose.call(this);
  68584. };
  68585. /** @hidden */
  68586. RenderTargetTexture.prototype._rebuild = function () {
  68587. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68588. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68589. }
  68590. if (this._postProcessManager) {
  68591. this._postProcessManager._rebuild();
  68592. }
  68593. };
  68594. /**
  68595. * Clear the info related to rendering groups preventing retention point in material dispose.
  68596. */
  68597. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68598. if (this._renderingManager) {
  68599. this._renderingManager.freeRenderingGroups();
  68600. }
  68601. };
  68602. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68603. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68604. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68605. return RenderTargetTexture;
  68606. }(BABYLON.Texture));
  68607. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68608. })(BABYLON || (BABYLON = {}));
  68609. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68610. var BABYLON;
  68611. (function (BABYLON) {
  68612. ;
  68613. var MultiRenderTarget = /** @class */ (function (_super) {
  68614. __extends(MultiRenderTarget, _super);
  68615. function MultiRenderTarget(name, size, count, scene, options) {
  68616. var _this = this;
  68617. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68618. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68619. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68620. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68621. _this._engine = scene.getEngine();
  68622. if (!_this.isSupported) {
  68623. _this.dispose();
  68624. return;
  68625. }
  68626. var types = [];
  68627. var samplingModes = [];
  68628. for (var i = 0; i < count; i++) {
  68629. if (options && options.types && options.types[i] !== undefined) {
  68630. types.push(options.types[i]);
  68631. }
  68632. else {
  68633. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68634. }
  68635. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68636. samplingModes.push(options.samplingModes[i]);
  68637. }
  68638. else {
  68639. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68640. }
  68641. }
  68642. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68643. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68644. _this._size = size;
  68645. _this._multiRenderTargetOptions = {
  68646. samplingModes: samplingModes,
  68647. generateMipMaps: generateMipMaps,
  68648. generateDepthBuffer: generateDepthBuffer,
  68649. generateStencilBuffer: generateStencilBuffer,
  68650. generateDepthTexture: generateDepthTexture,
  68651. types: types,
  68652. textureCount: count
  68653. };
  68654. _this._createInternalTextures();
  68655. _this._createTextures();
  68656. return _this;
  68657. }
  68658. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68659. get: function () {
  68660. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68661. },
  68662. enumerable: true,
  68663. configurable: true
  68664. });
  68665. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68666. get: function () {
  68667. return this._textures;
  68668. },
  68669. enumerable: true,
  68670. configurable: true
  68671. });
  68672. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68673. get: function () {
  68674. return this._textures[this._textures.length - 1];
  68675. },
  68676. enumerable: true,
  68677. configurable: true
  68678. });
  68679. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68680. set: function (wrap) {
  68681. if (this._textures) {
  68682. for (var i = 0; i < this._textures.length; i++) {
  68683. this._textures[i].wrapU = wrap;
  68684. }
  68685. }
  68686. },
  68687. enumerable: true,
  68688. configurable: true
  68689. });
  68690. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68691. set: function (wrap) {
  68692. if (this._textures) {
  68693. for (var i = 0; i < this._textures.length; i++) {
  68694. this._textures[i].wrapV = wrap;
  68695. }
  68696. }
  68697. },
  68698. enumerable: true,
  68699. configurable: true
  68700. });
  68701. /** @hidden */
  68702. MultiRenderTarget.prototype._rebuild = function () {
  68703. this.releaseInternalTextures();
  68704. this._createInternalTextures();
  68705. for (var i = 0; i < this._internalTextures.length; i++) {
  68706. var texture = this._textures[i];
  68707. texture._texture = this._internalTextures[i];
  68708. }
  68709. // Keeps references to frame buffer and stencil/depth buffer
  68710. this._texture = this._internalTextures[0];
  68711. };
  68712. MultiRenderTarget.prototype._createInternalTextures = function () {
  68713. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68714. };
  68715. MultiRenderTarget.prototype._createTextures = function () {
  68716. this._textures = [];
  68717. for (var i = 0; i < this._internalTextures.length; i++) {
  68718. var texture = new BABYLON.Texture(null, this.getScene());
  68719. texture._texture = this._internalTextures[i];
  68720. this._textures.push(texture);
  68721. }
  68722. // Keeps references to frame buffer and stencil/depth buffer
  68723. this._texture = this._internalTextures[0];
  68724. };
  68725. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68726. get: function () {
  68727. return this._samples;
  68728. },
  68729. set: function (value) {
  68730. if (this._samples === value) {
  68731. return;
  68732. }
  68733. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68734. },
  68735. enumerable: true,
  68736. configurable: true
  68737. });
  68738. MultiRenderTarget.prototype.resize = function (size) {
  68739. this.releaseInternalTextures();
  68740. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68741. this._createInternalTextures();
  68742. };
  68743. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68744. var _this = this;
  68745. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68746. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68747. });
  68748. };
  68749. MultiRenderTarget.prototype.dispose = function () {
  68750. this.releaseInternalTextures();
  68751. _super.prototype.dispose.call(this);
  68752. };
  68753. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68754. if (!this._internalTextures) {
  68755. return;
  68756. }
  68757. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68758. if (this._internalTextures[i] !== undefined) {
  68759. this._internalTextures[i].dispose();
  68760. this._internalTextures.splice(i, 1);
  68761. }
  68762. }
  68763. };
  68764. return MultiRenderTarget;
  68765. }(BABYLON.RenderTargetTexture));
  68766. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68767. })(BABYLON || (BABYLON = {}));
  68768. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68769. var BABYLON;
  68770. (function (BABYLON) {
  68771. var MirrorTexture = /** @class */ (function (_super) {
  68772. __extends(MirrorTexture, _super);
  68773. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68774. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68776. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68777. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68778. _this.scene = scene;
  68779. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68780. _this._transformMatrix = BABYLON.Matrix.Zero();
  68781. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68782. _this._adaptiveBlurKernel = 0;
  68783. _this._blurKernelX = 0;
  68784. _this._blurKernelY = 0;
  68785. _this._blurRatio = 1.0;
  68786. _this.ignoreCameraViewport = true;
  68787. _this._updateGammaSpace();
  68788. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68789. _this._updateGammaSpace;
  68790. });
  68791. _this.onBeforeRenderObservable.add(function () {
  68792. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68793. _this._savedViewMatrix = scene.getViewMatrix();
  68794. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68795. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68796. scene.clipPlane = _this.mirrorPlane;
  68797. scene.getEngine().cullBackFaces = false;
  68798. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68799. });
  68800. _this.onAfterRenderObservable.add(function () {
  68801. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68802. scene.getEngine().cullBackFaces = true;
  68803. scene._mirroredCameraPosition = null;
  68804. delete scene.clipPlane;
  68805. });
  68806. return _this;
  68807. }
  68808. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68809. get: function () {
  68810. return this._blurRatio;
  68811. },
  68812. set: function (value) {
  68813. if (this._blurRatio === value) {
  68814. return;
  68815. }
  68816. this._blurRatio = value;
  68817. this._preparePostProcesses();
  68818. },
  68819. enumerable: true,
  68820. configurable: true
  68821. });
  68822. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68823. set: function (value) {
  68824. this._adaptiveBlurKernel = value;
  68825. this._autoComputeBlurKernel();
  68826. },
  68827. enumerable: true,
  68828. configurable: true
  68829. });
  68830. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68831. set: function (value) {
  68832. this.blurKernelX = value;
  68833. this.blurKernelY = value;
  68834. },
  68835. enumerable: true,
  68836. configurable: true
  68837. });
  68838. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68839. get: function () {
  68840. return this._blurKernelX;
  68841. },
  68842. set: function (value) {
  68843. if (this._blurKernelX === value) {
  68844. return;
  68845. }
  68846. this._blurKernelX = value;
  68847. this._preparePostProcesses();
  68848. },
  68849. enumerable: true,
  68850. configurable: true
  68851. });
  68852. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68853. get: function () {
  68854. return this._blurKernelY;
  68855. },
  68856. set: function (value) {
  68857. if (this._blurKernelY === value) {
  68858. return;
  68859. }
  68860. this._blurKernelY = value;
  68861. this._preparePostProcesses();
  68862. },
  68863. enumerable: true,
  68864. configurable: true
  68865. });
  68866. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68867. var engine = this.getScene().getEngine();
  68868. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68869. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68870. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68871. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68872. };
  68873. MirrorTexture.prototype._onRatioRescale = function () {
  68874. if (this._sizeRatio) {
  68875. this.resize(this._initialSizeParameter);
  68876. if (!this._adaptiveBlurKernel) {
  68877. this._preparePostProcesses();
  68878. }
  68879. }
  68880. if (this._adaptiveBlurKernel) {
  68881. this._autoComputeBlurKernel();
  68882. }
  68883. };
  68884. MirrorTexture.prototype._updateGammaSpace = function () {
  68885. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68886. };
  68887. MirrorTexture.prototype._preparePostProcesses = function () {
  68888. this.clearPostProcesses(true);
  68889. if (this._blurKernelX && this._blurKernelY) {
  68890. var engine = this.getScene().getEngine();
  68891. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68892. 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);
  68893. this._blurX.autoClear = false;
  68894. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68895. this._blurX.inputTexture = this._texture;
  68896. }
  68897. else {
  68898. this._blurX.alwaysForcePOT = true;
  68899. }
  68900. 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);
  68901. this._blurY.autoClear = false;
  68902. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68903. this.addPostProcess(this._blurX);
  68904. this.addPostProcess(this._blurY);
  68905. }
  68906. else {
  68907. if (this._blurY) {
  68908. this.removePostProcess(this._blurY);
  68909. this._blurY.dispose();
  68910. this._blurY = null;
  68911. }
  68912. if (this._blurX) {
  68913. this.removePostProcess(this._blurX);
  68914. this._blurX.dispose();
  68915. this._blurX = null;
  68916. }
  68917. }
  68918. };
  68919. MirrorTexture.prototype.clone = function () {
  68920. var scene = this.getScene();
  68921. if (!scene) {
  68922. return this;
  68923. }
  68924. var textureSize = this.getSize();
  68925. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68926. // Base texture
  68927. newTexture.hasAlpha = this.hasAlpha;
  68928. newTexture.level = this.level;
  68929. // Mirror Texture
  68930. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68931. if (this.renderList) {
  68932. newTexture.renderList = this.renderList.slice(0);
  68933. }
  68934. return newTexture;
  68935. };
  68936. MirrorTexture.prototype.serialize = function () {
  68937. if (!this.name) {
  68938. return null;
  68939. }
  68940. var serializationObject = _super.prototype.serialize.call(this);
  68941. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68942. return serializationObject;
  68943. };
  68944. MirrorTexture.prototype.dispose = function () {
  68945. _super.prototype.dispose.call(this);
  68946. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68947. };
  68948. return MirrorTexture;
  68949. }(BABYLON.RenderTargetTexture));
  68950. BABYLON.MirrorTexture = MirrorTexture;
  68951. })(BABYLON || (BABYLON = {}));
  68952. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68953. var BABYLON;
  68954. (function (BABYLON) {
  68955. /**
  68956. * Creates a refraction texture used by refraction channel of the standard material.
  68957. * @param name the texture name
  68958. * @param size size of the underlying texture
  68959. * @param scene root scene
  68960. */
  68961. var RefractionTexture = /** @class */ (function (_super) {
  68962. __extends(RefractionTexture, _super);
  68963. function RefractionTexture(name, size, scene, generateMipMaps) {
  68964. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68965. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68966. _this.depth = 2.0;
  68967. _this.onBeforeRenderObservable.add(function () {
  68968. scene.clipPlane = _this.refractionPlane;
  68969. });
  68970. _this.onAfterRenderObservable.add(function () {
  68971. delete scene.clipPlane;
  68972. });
  68973. return _this;
  68974. }
  68975. RefractionTexture.prototype.clone = function () {
  68976. var scene = this.getScene();
  68977. if (!scene) {
  68978. return this;
  68979. }
  68980. var textureSize = this.getSize();
  68981. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68982. // Base texture
  68983. newTexture.hasAlpha = this.hasAlpha;
  68984. newTexture.level = this.level;
  68985. // Refraction Texture
  68986. newTexture.refractionPlane = this.refractionPlane.clone();
  68987. if (this.renderList) {
  68988. newTexture.renderList = this.renderList.slice(0);
  68989. }
  68990. newTexture.depth = this.depth;
  68991. return newTexture;
  68992. };
  68993. RefractionTexture.prototype.serialize = function () {
  68994. if (!this.name) {
  68995. return null;
  68996. }
  68997. var serializationObject = _super.prototype.serialize.call(this);
  68998. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68999. serializationObject.depth = this.depth;
  69000. return serializationObject;
  69001. };
  69002. return RefractionTexture;
  69003. }(BABYLON.RenderTargetTexture));
  69004. BABYLON.RefractionTexture = RefractionTexture;
  69005. })(BABYLON || (BABYLON = {}));
  69006. //# sourceMappingURL=babylon.refractionTexture.js.map
  69007. var BABYLON;
  69008. (function (BABYLON) {
  69009. /**
  69010. * A class extending {BABYLON.Texture} allowing drawing on a texture
  69011. * @see http://doc.babylonjs.com/how_to/dynamictexture
  69012. */
  69013. var DynamicTexture = /** @class */ (function (_super) {
  69014. __extends(DynamicTexture, _super);
  69015. /**
  69016. * Creates a {BABYLON.DynamicTexture}
  69017. * @param name defines the name of the texture
  69018. * @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
  69019. * @param scene defines the scene where you want the texture
  69020. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  69021. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  69022. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  69023. */
  69024. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  69025. if (scene === void 0) { scene = null; }
  69026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69027. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69028. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  69029. _this.name = name;
  69030. _this._engine = _this.getScene().getEngine();
  69031. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69032. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69033. _this._generateMipMaps = generateMipMaps;
  69034. if (options.getContext) {
  69035. _this._canvas = options;
  69036. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  69037. }
  69038. else {
  69039. _this._canvas = document.createElement("canvas");
  69040. if (options.width || options.width === 0) {
  69041. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  69042. }
  69043. else {
  69044. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  69045. }
  69046. }
  69047. var textureSize = _this.getSize();
  69048. _this._canvas.width = textureSize.width;
  69049. _this._canvas.height = textureSize.height;
  69050. _this._context = _this._canvas.getContext("2d");
  69051. return _this;
  69052. }
  69053. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  69054. /**
  69055. * Gets the current state of canRescale
  69056. */
  69057. get: function () {
  69058. return true;
  69059. },
  69060. enumerable: true,
  69061. configurable: true
  69062. });
  69063. DynamicTexture.prototype._recreate = function (textureSize) {
  69064. this._canvas.width = textureSize.width;
  69065. this._canvas.height = textureSize.height;
  69066. this.releaseInternalTexture();
  69067. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  69068. };
  69069. /**
  69070. * Scales the texture
  69071. * @param ratio the scale factor to apply to both width and height
  69072. */
  69073. DynamicTexture.prototype.scale = function (ratio) {
  69074. var textureSize = this.getSize();
  69075. textureSize.width *= ratio;
  69076. textureSize.height *= ratio;
  69077. this._recreate(textureSize);
  69078. };
  69079. /**
  69080. * Resizes the texture
  69081. * @param width the new width
  69082. * @param height the new height
  69083. */
  69084. DynamicTexture.prototype.scaleTo = function (width, height) {
  69085. var textureSize = this.getSize();
  69086. textureSize.width = width;
  69087. textureSize.height = height;
  69088. this._recreate(textureSize);
  69089. };
  69090. /**
  69091. * Gets the context of the canvas used by the texture
  69092. * @returns the canvas context of the dynamic texture
  69093. */
  69094. DynamicTexture.prototype.getContext = function () {
  69095. return this._context;
  69096. };
  69097. /**
  69098. * Clears the texture
  69099. */
  69100. DynamicTexture.prototype.clear = function () {
  69101. var size = this.getSize();
  69102. this._context.fillRect(0, 0, size.width, size.height);
  69103. };
  69104. /**
  69105. * Updates the texture
  69106. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  69107. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  69108. */
  69109. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  69110. if (premulAlpha === void 0) { premulAlpha = false; }
  69111. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  69112. };
  69113. /**
  69114. * Draws text onto the texture
  69115. * @param text defines the text to be drawn
  69116. * @param x defines the placement of the text from the left
  69117. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  69118. * @param font defines the font to be used with font-style, font-size, font-name
  69119. * @param color defines the color used for the text
  69120. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  69121. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  69122. * @param update defines whether texture is immediately update (default is true)
  69123. */
  69124. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  69125. if (update === void 0) { update = true; }
  69126. var size = this.getSize();
  69127. if (clearColor) {
  69128. this._context.fillStyle = clearColor;
  69129. this._context.fillRect(0, 0, size.width, size.height);
  69130. }
  69131. this._context.font = font;
  69132. if (x === null || x === undefined) {
  69133. var textSize = this._context.measureText(text);
  69134. x = (size.width - textSize.width) / 2;
  69135. }
  69136. if (y === null || y === undefined) {
  69137. var fontSize = parseInt((font.replace(/\D/g, '')));
  69138. y = (size.height / 2) + (fontSize / 3.65);
  69139. }
  69140. this._context.fillStyle = color;
  69141. this._context.fillText(text, x, y);
  69142. if (update) {
  69143. this.update(invertY);
  69144. }
  69145. };
  69146. /**
  69147. * Clones the texture
  69148. * @returns the clone of the texture.
  69149. */
  69150. DynamicTexture.prototype.clone = function () {
  69151. var scene = this.getScene();
  69152. if (!scene) {
  69153. return this;
  69154. }
  69155. var textureSize = this.getSize();
  69156. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  69157. // Base texture
  69158. newTexture.hasAlpha = this.hasAlpha;
  69159. newTexture.level = this.level;
  69160. // Dynamic Texture
  69161. newTexture.wrapU = this.wrapU;
  69162. newTexture.wrapV = this.wrapV;
  69163. return newTexture;
  69164. };
  69165. /**
  69166. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  69167. * @returns a serialized dynamic texture object
  69168. */
  69169. DynamicTexture.prototype.serialize = function () {
  69170. var scene = this.getScene();
  69171. if (scene && !scene.isReady()) {
  69172. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  69173. }
  69174. var serializationObject = _super.prototype.serialize.call(this);
  69175. serializationObject.base64String = this._canvas.toDataURL();
  69176. serializationObject.invertY = this._invertY;
  69177. serializationObject.samplingMode = this.samplingMode;
  69178. return serializationObject;
  69179. };
  69180. /** @hidden */
  69181. DynamicTexture.prototype._rebuild = function () {
  69182. this.update();
  69183. };
  69184. return DynamicTexture;
  69185. }(BABYLON.Texture));
  69186. BABYLON.DynamicTexture = DynamicTexture;
  69187. })(BABYLON || (BABYLON = {}));
  69188. //# sourceMappingURL=babylon.dynamicTexture.js.map
  69189. var BABYLON;
  69190. (function (BABYLON) {
  69191. var VideoTexture = /** @class */ (function (_super) {
  69192. __extends(VideoTexture, _super);
  69193. /**
  69194. * Creates a video texture.
  69195. * Sample : https://doc.babylonjs.com/how_to/video_texture
  69196. * @param {string | null} name optional name, will detect from video source, if not defined
  69197. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  69198. * @param {BABYLON.Scene} scene is obviously the current scene.
  69199. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  69200. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  69201. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  69202. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  69203. */
  69204. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  69205. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69206. if (invertY === void 0) { invertY = false; }
  69207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69208. if (settings === void 0) { settings = {
  69209. autoPlay: true,
  69210. loop: true,
  69211. autoUpdateTexture: true,
  69212. }; }
  69213. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69214. _this._onUserActionRequestedObservable = null;
  69215. _this._stillImageCaptured = false;
  69216. _this._poster = false;
  69217. _this._createInternalTexture = function () {
  69218. if (_this._texture != null) {
  69219. if (_this._poster) {
  69220. _this._texture.dispose();
  69221. _this._poster = false;
  69222. }
  69223. else {
  69224. return;
  69225. }
  69226. }
  69227. if (!_this._engine.needPOTTextures ||
  69228. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  69229. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69230. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69231. }
  69232. else {
  69233. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69234. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69235. _this._generateMipMaps = false;
  69236. }
  69237. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  69238. if (!_this.video.autoplay) {
  69239. var oldHandler_1 = _this.video.onplaying;
  69240. var error_1 = false;
  69241. _this.video.onplaying = function () {
  69242. _this.video.onplaying = oldHandler_1;
  69243. _this._texture.isReady = true;
  69244. _this._updateInternalTexture();
  69245. if (!error_1) {
  69246. _this.video.pause();
  69247. }
  69248. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69249. _this.onLoadObservable.notifyObservers(_this);
  69250. }
  69251. };
  69252. var playing = _this.video.play();
  69253. if (playing) {
  69254. playing.then(function () {
  69255. // Everything is good.
  69256. })
  69257. .catch(function () {
  69258. error_1 = true;
  69259. // On Chrome for instance, new policies might prevent playing without user interaction.
  69260. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  69261. _this._onUserActionRequestedObservable.notifyObservers(_this);
  69262. }
  69263. });
  69264. }
  69265. else {
  69266. _this.video.onplaying = oldHandler_1;
  69267. _this._texture.isReady = true;
  69268. _this._updateInternalTexture();
  69269. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69270. _this.onLoadObservable.notifyObservers(_this);
  69271. }
  69272. }
  69273. }
  69274. else {
  69275. _this._texture.isReady = true;
  69276. _this._updateInternalTexture();
  69277. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  69278. _this.onLoadObservable.notifyObservers(_this);
  69279. }
  69280. }
  69281. };
  69282. _this.reset = function () {
  69283. if (_this._texture == null) {
  69284. return;
  69285. }
  69286. if (!_this._poster) {
  69287. _this._texture.dispose();
  69288. _this._texture = null;
  69289. }
  69290. };
  69291. _this._updateInternalTexture = function (e) {
  69292. if (_this._texture == null || !_this._texture.isReady) {
  69293. return;
  69294. }
  69295. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  69296. return;
  69297. }
  69298. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  69299. };
  69300. _this._engine = _this.getScene().getEngine();
  69301. _this._generateMipMaps = generateMipMaps;
  69302. _this._samplingMode = samplingMode;
  69303. _this.autoUpdateTexture = settings.autoUpdateTexture;
  69304. _this.name = name || _this._getName(src);
  69305. _this.video = _this._getVideo(src);
  69306. if (settings.poster) {
  69307. _this.video.poster = settings.poster;
  69308. }
  69309. if (settings.autoPlay !== undefined) {
  69310. _this.video.autoplay = settings.autoPlay;
  69311. }
  69312. if (settings.loop !== undefined) {
  69313. _this.video.loop = settings.loop;
  69314. }
  69315. _this.video.setAttribute("playsinline", "");
  69316. _this.video.addEventListener("canplay", _this._createInternalTexture);
  69317. _this.video.addEventListener("paused", _this._updateInternalTexture);
  69318. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  69319. _this.video.addEventListener("emptied", _this.reset);
  69320. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  69321. _this._createInternalTexture();
  69322. }
  69323. if (settings.poster) {
  69324. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  69325. _this._poster = true;
  69326. }
  69327. return _this;
  69328. }
  69329. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  69330. get: function () {
  69331. if (!this._onUserActionRequestedObservable) {
  69332. this._onUserActionRequestedObservable = new BABYLON.Observable();
  69333. }
  69334. return this._onUserActionRequestedObservable;
  69335. },
  69336. enumerable: true,
  69337. configurable: true
  69338. });
  69339. VideoTexture.prototype._getName = function (src) {
  69340. if (src instanceof HTMLVideoElement) {
  69341. return src.currentSrc;
  69342. }
  69343. if (typeof src === "object") {
  69344. return src.toString();
  69345. }
  69346. return src;
  69347. };
  69348. ;
  69349. VideoTexture.prototype._getVideo = function (src) {
  69350. if (src instanceof HTMLVideoElement) {
  69351. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  69352. return src;
  69353. }
  69354. var video = document.createElement("video");
  69355. if (typeof src === "string") {
  69356. BABYLON.Tools.SetCorsBehavior(src, video);
  69357. video.src = src;
  69358. }
  69359. else {
  69360. BABYLON.Tools.SetCorsBehavior(src[0], video);
  69361. src.forEach(function (url) {
  69362. var source = document.createElement("source");
  69363. source.src = url;
  69364. video.appendChild(source);
  69365. });
  69366. }
  69367. return video;
  69368. };
  69369. ;
  69370. /**
  69371. * @hidden Internal method to initiate `update`.
  69372. */
  69373. VideoTexture.prototype._rebuild = function () {
  69374. this.update();
  69375. };
  69376. /**
  69377. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  69378. */
  69379. VideoTexture.prototype.update = function () {
  69380. if (!this.autoUpdateTexture) {
  69381. // Expecting user to call `updateTexture` manually
  69382. return;
  69383. }
  69384. this.updateTexture(true);
  69385. };
  69386. /**
  69387. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  69388. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  69389. */
  69390. VideoTexture.prototype.updateTexture = function (isVisible) {
  69391. if (!isVisible) {
  69392. return;
  69393. }
  69394. if (this.video.paused && this._stillImageCaptured) {
  69395. return;
  69396. }
  69397. this._stillImageCaptured = true;
  69398. this._updateInternalTexture();
  69399. };
  69400. /**
  69401. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  69402. * @param url New url.
  69403. */
  69404. VideoTexture.prototype.updateURL = function (url) {
  69405. this.video.src = url;
  69406. };
  69407. VideoTexture.prototype.dispose = function () {
  69408. _super.prototype.dispose.call(this);
  69409. if (this._onUserActionRequestedObservable) {
  69410. this._onUserActionRequestedObservable.clear();
  69411. this._onUserActionRequestedObservable = null;
  69412. }
  69413. this.video.removeEventListener("canplay", this._createInternalTexture);
  69414. this.video.removeEventListener("paused", this._updateInternalTexture);
  69415. this.video.removeEventListener("seeked", this._updateInternalTexture);
  69416. this.video.removeEventListener("emptied", this.reset);
  69417. this.video.pause();
  69418. };
  69419. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  69420. var video = document.createElement("video");
  69421. video.setAttribute('autoplay', '');
  69422. video.setAttribute('muted', '');
  69423. video.setAttribute('playsinline', '');
  69424. var constraintsDeviceId;
  69425. if (constraints && constraints.deviceId) {
  69426. constraintsDeviceId = {
  69427. exact: constraints.deviceId,
  69428. };
  69429. }
  69430. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  69431. if (navigator.mediaDevices) {
  69432. navigator.mediaDevices.getUserMedia({ video: constraints })
  69433. .then(function (stream) {
  69434. if (video.mozSrcObject !== undefined) {
  69435. // hack for Firefox < 19
  69436. video.mozSrcObject = stream;
  69437. }
  69438. else {
  69439. video.srcObject = stream;
  69440. }
  69441. var onPlaying = function () {
  69442. if (onReady) {
  69443. onReady(new VideoTexture("video", video, scene, true, true));
  69444. }
  69445. video.removeEventListener("playing", onPlaying);
  69446. };
  69447. video.addEventListener("playing", onPlaying);
  69448. video.play();
  69449. })
  69450. .catch(function (err) {
  69451. BABYLON.Tools.Error(err.name);
  69452. });
  69453. }
  69454. else {
  69455. navigator.getUserMedia =
  69456. navigator.getUserMedia ||
  69457. navigator.webkitGetUserMedia ||
  69458. navigator.mozGetUserMedia ||
  69459. navigator.msGetUserMedia;
  69460. if (navigator.getUserMedia) {
  69461. navigator.getUserMedia({
  69462. video: {
  69463. deviceId: constraintsDeviceId,
  69464. width: {
  69465. min: (constraints && constraints.minWidth) || 256,
  69466. max: (constraints && constraints.maxWidth) || 640,
  69467. },
  69468. height: {
  69469. min: (constraints && constraints.minHeight) || 256,
  69470. max: (constraints && constraints.maxHeight) || 480,
  69471. },
  69472. },
  69473. }, function (stream) {
  69474. if (video.mozSrcObject !== undefined) {
  69475. // hack for Firefox < 19
  69476. video.mozSrcObject = stream;
  69477. }
  69478. else {
  69479. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  69480. }
  69481. video.play();
  69482. if (onReady) {
  69483. onReady(new VideoTexture("video", video, scene, true, true));
  69484. }
  69485. }, function (e) {
  69486. BABYLON.Tools.Error(e.name);
  69487. });
  69488. }
  69489. }
  69490. };
  69491. return VideoTexture;
  69492. }(BABYLON.Texture));
  69493. BABYLON.VideoTexture = VideoTexture;
  69494. })(BABYLON || (BABYLON = {}));
  69495. //# sourceMappingURL=babylon.videoTexture.js.map
  69496. var BABYLON;
  69497. (function (BABYLON) {
  69498. var RawTexture = /** @class */ (function (_super) {
  69499. __extends(RawTexture, _super);
  69500. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  69501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69502. if (invertY === void 0) { invertY = false; }
  69503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69505. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69506. _this.format = format;
  69507. _this._engine = scene.getEngine();
  69508. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  69509. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69510. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69511. return _this;
  69512. }
  69513. RawTexture.prototype.update = function (data) {
  69514. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69515. };
  69516. // Statics
  69517. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69519. if (invertY === void 0) { invertY = false; }
  69520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69521. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  69522. };
  69523. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69524. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69525. if (invertY === void 0) { invertY = false; }
  69526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69527. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69528. };
  69529. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69530. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69531. if (invertY === void 0) { invertY = false; }
  69532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69533. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69534. };
  69535. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69537. if (invertY === void 0) { invertY = false; }
  69538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69539. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69540. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69541. };
  69542. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69544. if (invertY === void 0) { invertY = false; }
  69545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69546. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69547. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69548. };
  69549. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69550. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69551. if (invertY === void 0) { invertY = false; }
  69552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69553. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69554. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69555. };
  69556. return RawTexture;
  69557. }(BABYLON.Texture));
  69558. BABYLON.RawTexture = RawTexture;
  69559. })(BABYLON || (BABYLON = {}));
  69560. //# sourceMappingURL=babylon.rawTexture.js.map
  69561. var BABYLON;
  69562. (function (BABYLON) {
  69563. /**
  69564. * Class used to store 3D textures containing user data
  69565. */
  69566. var RawTexture3D = /** @class */ (function (_super) {
  69567. __extends(RawTexture3D, _super);
  69568. /**
  69569. * Create a new RawTexture3D
  69570. * @param data defines the data of the texture
  69571. * @param width defines the width of the texture
  69572. * @param height defines the height of the texture
  69573. * @param depth defines the depth of the texture
  69574. * @param format defines the texture format to use
  69575. * @param scene defines the hosting scene
  69576. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69577. * @param invertY defines if texture must be stored with Y axis inverted
  69578. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69579. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69580. */
  69581. function RawTexture3D(data, width, height, depth,
  69582. /** Gets or sets the texture format to use */
  69583. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69585. if (invertY === void 0) { invertY = false; }
  69586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69587. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69588. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69589. _this.format = format;
  69590. _this._engine = scene.getEngine();
  69591. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69592. _this.is3D = true;
  69593. return _this;
  69594. }
  69595. /**
  69596. * Update the texture with new data
  69597. * @param data defines the data to store in the texture
  69598. */
  69599. RawTexture3D.prototype.update = function (data) {
  69600. if (!this._texture) {
  69601. return;
  69602. }
  69603. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69604. };
  69605. return RawTexture3D;
  69606. }(BABYLON.Texture));
  69607. BABYLON.RawTexture3D = RawTexture3D;
  69608. })(BABYLON || (BABYLON = {}));
  69609. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69610. var BABYLON;
  69611. (function (BABYLON) {
  69612. /**
  69613. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69614. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69615. */
  69616. var PostProcessManager = /** @class */ (function () {
  69617. /**
  69618. * Creates a new instance PostProcess
  69619. * @param scene The scene that the post process is associated with.
  69620. */
  69621. function PostProcessManager(scene) {
  69622. this._vertexBuffers = {};
  69623. this._scene = scene;
  69624. }
  69625. PostProcessManager.prototype._prepareBuffers = function () {
  69626. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69627. return;
  69628. }
  69629. // VBO
  69630. var vertices = [];
  69631. vertices.push(1, 1);
  69632. vertices.push(-1, 1);
  69633. vertices.push(-1, -1);
  69634. vertices.push(1, -1);
  69635. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69636. this._buildIndexBuffer();
  69637. };
  69638. PostProcessManager.prototype._buildIndexBuffer = function () {
  69639. // Indices
  69640. var indices = [];
  69641. indices.push(0);
  69642. indices.push(1);
  69643. indices.push(2);
  69644. indices.push(0);
  69645. indices.push(2);
  69646. indices.push(3);
  69647. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69648. };
  69649. /**
  69650. * Rebuilds the vertex buffers of the manager.
  69651. * @hidden
  69652. */
  69653. PostProcessManager.prototype._rebuild = function () {
  69654. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69655. if (!vb) {
  69656. return;
  69657. }
  69658. vb._rebuild();
  69659. this._buildIndexBuffer();
  69660. };
  69661. // Methods
  69662. /**
  69663. * Prepares a frame to be run through a post process.
  69664. * @param sourceTexture The input texture to the post procesess. (default: null)
  69665. * @param postProcesses An array of post processes to be run. (default: null)
  69666. * @returns True if the post processes were able to be run.
  69667. * @hidden
  69668. */
  69669. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69670. if (sourceTexture === void 0) { sourceTexture = null; }
  69671. if (postProcesses === void 0) { postProcesses = null; }
  69672. var camera = this._scene.activeCamera;
  69673. if (!camera) {
  69674. return false;
  69675. }
  69676. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69677. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69678. return false;
  69679. }
  69680. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69681. return true;
  69682. };
  69683. /**
  69684. * Manually render a set of post processes to a texture.
  69685. * @param postProcesses An array of post processes to be run.
  69686. * @param targetTexture The target texture to render to.
  69687. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69688. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69689. * @param lodLevel defines which lod of the texture to render to
  69690. */
  69691. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69692. if (targetTexture === void 0) { targetTexture = null; }
  69693. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69694. if (faceIndex === void 0) { faceIndex = 0; }
  69695. if (lodLevel === void 0) { lodLevel = 0; }
  69696. var engine = this._scene.getEngine();
  69697. for (var index = 0; index < postProcesses.length; index++) {
  69698. if (index < postProcesses.length - 1) {
  69699. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69700. }
  69701. else {
  69702. if (targetTexture) {
  69703. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69704. }
  69705. else {
  69706. engine.restoreDefaultFramebuffer();
  69707. }
  69708. }
  69709. var pp = postProcesses[index];
  69710. var effect = pp.apply();
  69711. if (effect) {
  69712. pp.onBeforeRenderObservable.notifyObservers(effect);
  69713. // VBOs
  69714. this._prepareBuffers();
  69715. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69716. // Draw order
  69717. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69718. pp.onAfterRenderObservable.notifyObservers(effect);
  69719. }
  69720. }
  69721. // Restore depth buffer
  69722. engine.setDepthBuffer(true);
  69723. engine.setDepthWrite(true);
  69724. };
  69725. /**
  69726. * Finalize the result of the output of the postprocesses.
  69727. * @param doNotPresent If true the result will not be displayed to the screen.
  69728. * @param targetTexture The target texture to render to.
  69729. * @param faceIndex The index of the face to bind the target texture to.
  69730. * @param postProcesses The array of post processes to render.
  69731. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69732. * @hidden
  69733. */
  69734. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69735. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69736. var camera = this._scene.activeCamera;
  69737. if (!camera) {
  69738. return;
  69739. }
  69740. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69741. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69742. return;
  69743. }
  69744. var engine = this._scene.getEngine();
  69745. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69746. var pp = postProcesses[index];
  69747. if (index < len - 1) {
  69748. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69749. }
  69750. else {
  69751. if (targetTexture) {
  69752. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69753. pp._outputTexture = targetTexture;
  69754. }
  69755. else {
  69756. engine.restoreDefaultFramebuffer();
  69757. pp._outputTexture = null;
  69758. }
  69759. }
  69760. if (doNotPresent) {
  69761. break;
  69762. }
  69763. var effect = pp.apply();
  69764. if (effect) {
  69765. pp.onBeforeRenderObservable.notifyObservers(effect);
  69766. // VBOs
  69767. this._prepareBuffers();
  69768. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69769. // Draw order
  69770. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69771. pp.onAfterRenderObservable.notifyObservers(effect);
  69772. }
  69773. }
  69774. // Restore states
  69775. engine.setDepthBuffer(true);
  69776. engine.setDepthWrite(true);
  69777. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69778. };
  69779. /**
  69780. * Disposes of the post process manager.
  69781. */
  69782. PostProcessManager.prototype.dispose = function () {
  69783. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69784. if (buffer) {
  69785. buffer.dispose();
  69786. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69787. }
  69788. if (this._indexBuffer) {
  69789. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69790. this._indexBuffer = null;
  69791. }
  69792. };
  69793. return PostProcessManager;
  69794. }());
  69795. BABYLON.PostProcessManager = PostProcessManager;
  69796. })(BABYLON || (BABYLON = {}));
  69797. //# sourceMappingURL=babylon.postProcessManager.js.map
  69798. var BABYLON;
  69799. (function (BABYLON) {
  69800. /**
  69801. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69802. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69803. */
  69804. var PostProcess = /** @class */ (function () {
  69805. /**
  69806. * Creates a new instance PostProcess
  69807. * @param name The name of the PostProcess.
  69808. * @param fragmentUrl The url of the fragment shader to be used.
  69809. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69810. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69811. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69812. * @param camera The camera to apply the render pass to.
  69813. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69814. * @param engine The engine which the post process will be applied. (default: current engine)
  69815. * @param reusable If the post process can be reused on the same frame. (default: false)
  69816. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69817. * @param textureType Type of textures used when performing the post process. (default: 0)
  69818. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69819. * @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
  69820. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69821. */
  69822. function PostProcess(
  69823. /** Name of the PostProcess. */
  69824. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69825. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69826. if (defines === void 0) { defines = null; }
  69827. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69828. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69829. if (blockCompilation === void 0) { blockCompilation = false; }
  69830. this.name = name;
  69831. /**
  69832. * Width of the texture to apply the post process on
  69833. */
  69834. this.width = -1;
  69835. /**
  69836. * Height of the texture to apply the post process on
  69837. */
  69838. this.height = -1;
  69839. /**
  69840. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69841. * @hidden
  69842. */
  69843. this._outputTexture = null;
  69844. /**
  69845. * If the buffer needs to be cleared before applying the post process. (default: true)
  69846. * Should be set to false if shader will overwrite all previous pixels.
  69847. */
  69848. this.autoClear = true;
  69849. /**
  69850. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69851. */
  69852. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69853. /**
  69854. * Animations to be used for the post processing
  69855. */
  69856. this.animations = new Array();
  69857. /**
  69858. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69859. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69860. */
  69861. this.enablePixelPerfectMode = false;
  69862. /**
  69863. * Force the postprocess to be applied without taking in account viewport
  69864. */
  69865. this.forceFullscreenViewport = true;
  69866. /**
  69867. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69868. *
  69869. * | Value | Type | Description |
  69870. * | ----- | ----------------------------------- | ----------- |
  69871. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69872. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69873. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69874. *
  69875. */
  69876. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69877. /**
  69878. * Force textures to be a power of two (default: false)
  69879. */
  69880. this.alwaysForcePOT = false;
  69881. this._samples = 1;
  69882. /**
  69883. * Modify the scale of the post process to be the same as the viewport (default: false)
  69884. */
  69885. this.adaptScaleToCurrentViewport = false;
  69886. this._reusable = false;
  69887. /**
  69888. * Smart array of input and output textures for the post process.
  69889. * @hidden
  69890. */
  69891. this._textures = new BABYLON.SmartArray(2);
  69892. /**
  69893. * The index in _textures that corresponds to the output texture.
  69894. * @hidden
  69895. */
  69896. this._currentRenderTextureInd = 0;
  69897. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69898. this._texelSize = BABYLON.Vector2.Zero();
  69899. // Events
  69900. /**
  69901. * An event triggered when the postprocess is activated.
  69902. */
  69903. this.onActivateObservable = new BABYLON.Observable();
  69904. /**
  69905. * An event triggered when the postprocess changes its size.
  69906. */
  69907. this.onSizeChangedObservable = new BABYLON.Observable();
  69908. /**
  69909. * An event triggered when the postprocess applies its effect.
  69910. */
  69911. this.onApplyObservable = new BABYLON.Observable();
  69912. /**
  69913. * An event triggered before rendering the postprocess
  69914. */
  69915. this.onBeforeRenderObservable = new BABYLON.Observable();
  69916. /**
  69917. * An event triggered after rendering the postprocess
  69918. */
  69919. this.onAfterRenderObservable = new BABYLON.Observable();
  69920. if (camera != null) {
  69921. this._camera = camera;
  69922. this._scene = camera.getScene();
  69923. camera.attachPostProcess(this);
  69924. this._engine = this._scene.getEngine();
  69925. this._scene.postProcesses.push(this);
  69926. }
  69927. else if (engine) {
  69928. this._engine = engine;
  69929. this._engine.postProcesses.push(this);
  69930. }
  69931. this._options = options;
  69932. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69933. this._reusable = reusable || false;
  69934. this._textureType = textureType;
  69935. this._samplers = samplers || [];
  69936. this._samplers.push("textureSampler");
  69937. this._fragmentUrl = fragmentUrl;
  69938. this._vertexUrl = vertexUrl;
  69939. this._parameters = parameters || [];
  69940. this._parameters.push("scale");
  69941. this._indexParameters = indexParameters;
  69942. if (!blockCompilation) {
  69943. this.updateEffect(defines);
  69944. }
  69945. }
  69946. Object.defineProperty(PostProcess.prototype, "samples", {
  69947. /**
  69948. * Number of sample textures (default: 1)
  69949. */
  69950. get: function () {
  69951. return this._samples;
  69952. },
  69953. set: function (n) {
  69954. var _this = this;
  69955. this._samples = n;
  69956. this._textures.forEach(function (texture) {
  69957. if (texture.samples !== _this._samples) {
  69958. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69959. }
  69960. });
  69961. },
  69962. enumerable: true,
  69963. configurable: true
  69964. });
  69965. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69966. /**
  69967. * A function that is added to the onActivateObservable
  69968. */
  69969. set: function (callback) {
  69970. if (this._onActivateObserver) {
  69971. this.onActivateObservable.remove(this._onActivateObserver);
  69972. }
  69973. if (callback) {
  69974. this._onActivateObserver = this.onActivateObservable.add(callback);
  69975. }
  69976. },
  69977. enumerable: true,
  69978. configurable: true
  69979. });
  69980. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69981. /**
  69982. * A function that is added to the onSizeChangedObservable
  69983. */
  69984. set: function (callback) {
  69985. if (this._onSizeChangedObserver) {
  69986. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69987. }
  69988. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69989. },
  69990. enumerable: true,
  69991. configurable: true
  69992. });
  69993. Object.defineProperty(PostProcess.prototype, "onApply", {
  69994. /**
  69995. * A function that is added to the onApplyObservable
  69996. */
  69997. set: function (callback) {
  69998. if (this._onApplyObserver) {
  69999. this.onApplyObservable.remove(this._onApplyObserver);
  70000. }
  70001. this._onApplyObserver = this.onApplyObservable.add(callback);
  70002. },
  70003. enumerable: true,
  70004. configurable: true
  70005. });
  70006. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  70007. /**
  70008. * A function that is added to the onBeforeRenderObservable
  70009. */
  70010. set: function (callback) {
  70011. if (this._onBeforeRenderObserver) {
  70012. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70013. }
  70014. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70015. },
  70016. enumerable: true,
  70017. configurable: true
  70018. });
  70019. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  70020. /**
  70021. * A function that is added to the onAfterRenderObservable
  70022. */
  70023. set: function (callback) {
  70024. if (this._onAfterRenderObserver) {
  70025. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70026. }
  70027. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70028. },
  70029. enumerable: true,
  70030. configurable: true
  70031. });
  70032. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  70033. /**
  70034. * 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
  70035. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  70036. */
  70037. get: function () {
  70038. return this._textures.data[this._currentRenderTextureInd];
  70039. },
  70040. set: function (value) {
  70041. this._forcedOutputTexture = value;
  70042. },
  70043. enumerable: true,
  70044. configurable: true
  70045. });
  70046. /**
  70047. * Gets the camera which post process is applied to.
  70048. * @returns The camera the post process is applied to.
  70049. */
  70050. PostProcess.prototype.getCamera = function () {
  70051. return this._camera;
  70052. };
  70053. Object.defineProperty(PostProcess.prototype, "texelSize", {
  70054. /**
  70055. * Gets the texel size of the postprocess.
  70056. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  70057. */
  70058. get: function () {
  70059. if (this._shareOutputWithPostProcess) {
  70060. return this._shareOutputWithPostProcess.texelSize;
  70061. }
  70062. if (this._forcedOutputTexture) {
  70063. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  70064. }
  70065. return this._texelSize;
  70066. },
  70067. enumerable: true,
  70068. configurable: true
  70069. });
  70070. /**
  70071. * Gets the engine which this post process belongs to.
  70072. * @returns The engine the post process was enabled with.
  70073. */
  70074. PostProcess.prototype.getEngine = function () {
  70075. return this._engine;
  70076. };
  70077. /**
  70078. * The effect that is created when initializing the post process.
  70079. * @returns The created effect corrisponding the the postprocess.
  70080. */
  70081. PostProcess.prototype.getEffect = function () {
  70082. return this._effect;
  70083. };
  70084. /**
  70085. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  70086. * @param postProcess The post process to share the output with.
  70087. * @returns This post process.
  70088. */
  70089. PostProcess.prototype.shareOutputWith = function (postProcess) {
  70090. this._disposeTextures();
  70091. this._shareOutputWithPostProcess = postProcess;
  70092. return this;
  70093. };
  70094. /**
  70095. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  70096. * This should be called if the post process that shares output with this post process is disabled/disposed.
  70097. */
  70098. PostProcess.prototype.useOwnOutput = function () {
  70099. if (this._textures.length == 0) {
  70100. this._textures = new BABYLON.SmartArray(2);
  70101. }
  70102. this._shareOutputWithPostProcess = null;
  70103. };
  70104. /**
  70105. * Updates the effect with the current post process compile time values and recompiles the shader.
  70106. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70107. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70108. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70109. * @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
  70110. * @param onCompiled Called when the shader has been compiled.
  70111. * @param onError Called if there is an error when compiling a shader.
  70112. */
  70113. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70114. if (defines === void 0) { defines = null; }
  70115. if (uniforms === void 0) { uniforms = null; }
  70116. if (samplers === void 0) { samplers = null; }
  70117. 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);
  70118. };
  70119. /**
  70120. * The post process is reusable if it can be used multiple times within one frame.
  70121. * @returns If the post process is reusable
  70122. */
  70123. PostProcess.prototype.isReusable = function () {
  70124. return this._reusable;
  70125. };
  70126. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  70127. PostProcess.prototype.markTextureDirty = function () {
  70128. this.width = -1;
  70129. };
  70130. /**
  70131. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  70132. * 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.
  70133. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  70134. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  70135. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  70136. * @returns The target texture that was bound to be written to.
  70137. */
  70138. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  70139. var _this = this;
  70140. if (sourceTexture === void 0) { sourceTexture = null; }
  70141. camera = camera || this._camera;
  70142. var scene = camera.getScene();
  70143. var engine = scene.getEngine();
  70144. var maxSize = engine.getCaps().maxTextureSize;
  70145. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  70146. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  70147. // 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
  70148. var webVRCamera = camera.parent;
  70149. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  70150. requiredWidth /= 2;
  70151. }
  70152. var desiredWidth = (this._options.width || requiredWidth);
  70153. var desiredHeight = this._options.height || requiredHeight;
  70154. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  70155. if (this.adaptScaleToCurrentViewport) {
  70156. var currentViewport = engine.currentViewport;
  70157. if (currentViewport) {
  70158. desiredWidth *= currentViewport.width;
  70159. desiredHeight *= currentViewport.height;
  70160. }
  70161. }
  70162. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  70163. if (!this._options.width) {
  70164. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  70165. }
  70166. if (!this._options.height) {
  70167. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  70168. }
  70169. }
  70170. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  70171. if (this._textures.length > 0) {
  70172. for (var i = 0; i < this._textures.length; i++) {
  70173. this._engine._releaseTexture(this._textures.data[i]);
  70174. }
  70175. this._textures.reset();
  70176. }
  70177. this.width = desiredWidth;
  70178. this.height = desiredHeight;
  70179. var textureSize = { width: this.width, height: this.height };
  70180. var textureOptions = {
  70181. generateMipMaps: false,
  70182. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  70183. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  70184. samplingMode: this.renderTargetSamplingMode,
  70185. type: this._textureType
  70186. };
  70187. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  70188. if (this._reusable) {
  70189. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  70190. }
  70191. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  70192. this.onSizeChangedObservable.notifyObservers(this);
  70193. }
  70194. this._textures.forEach(function (texture) {
  70195. if (texture.samples !== _this.samples) {
  70196. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  70197. }
  70198. });
  70199. }
  70200. var target;
  70201. if (this._shareOutputWithPostProcess) {
  70202. target = this._shareOutputWithPostProcess.inputTexture;
  70203. }
  70204. else if (this._forcedOutputTexture) {
  70205. target = this._forcedOutputTexture;
  70206. this.width = this._forcedOutputTexture.width;
  70207. this.height = this._forcedOutputTexture.height;
  70208. }
  70209. else {
  70210. target = this.inputTexture;
  70211. }
  70212. // Bind the input of this post process to be used as the output of the previous post process.
  70213. if (this.enablePixelPerfectMode) {
  70214. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  70215. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  70216. }
  70217. else {
  70218. this._scaleRatio.copyFromFloats(1, 1);
  70219. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  70220. }
  70221. this.onActivateObservable.notifyObservers(camera);
  70222. // Clear
  70223. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  70224. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  70225. }
  70226. if (this._reusable) {
  70227. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  70228. }
  70229. return target;
  70230. };
  70231. Object.defineProperty(PostProcess.prototype, "isSupported", {
  70232. /**
  70233. * If the post process is supported.
  70234. */
  70235. get: function () {
  70236. return this._effect.isSupported;
  70237. },
  70238. enumerable: true,
  70239. configurable: true
  70240. });
  70241. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  70242. /**
  70243. * The aspect ratio of the output texture.
  70244. */
  70245. get: function () {
  70246. if (this._shareOutputWithPostProcess) {
  70247. return this._shareOutputWithPostProcess.aspectRatio;
  70248. }
  70249. if (this._forcedOutputTexture) {
  70250. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  70251. }
  70252. return this.width / this.height;
  70253. },
  70254. enumerable: true,
  70255. configurable: true
  70256. });
  70257. /**
  70258. * Get a value indicating if the post-process is ready to be used
  70259. * @returns true if the post-process is ready (shader is compiled)
  70260. */
  70261. PostProcess.prototype.isReady = function () {
  70262. return this._effect && this._effect.isReady();
  70263. };
  70264. /**
  70265. * Binds all textures and uniforms to the shader, this will be run on every pass.
  70266. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  70267. */
  70268. PostProcess.prototype.apply = function () {
  70269. // Check
  70270. if (!this._effect || !this._effect.isReady())
  70271. return null;
  70272. // States
  70273. this._engine.enableEffect(this._effect);
  70274. this._engine.setState(false);
  70275. this._engine.setDepthBuffer(false);
  70276. this._engine.setDepthWrite(false);
  70277. // Alpha
  70278. this._engine.setAlphaMode(this.alphaMode);
  70279. if (this.alphaConstants) {
  70280. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  70281. }
  70282. // Bind the output texture of the preivous post process as the input to this post process.
  70283. var source;
  70284. if (this._shareOutputWithPostProcess) {
  70285. source = this._shareOutputWithPostProcess.inputTexture;
  70286. }
  70287. else if (this._forcedOutputTexture) {
  70288. source = this._forcedOutputTexture;
  70289. }
  70290. else {
  70291. source = this.inputTexture;
  70292. }
  70293. this._effect._bindTexture("textureSampler", source);
  70294. // Parameters
  70295. this._effect.setVector2("scale", this._scaleRatio);
  70296. this.onApplyObservable.notifyObservers(this._effect);
  70297. return this._effect;
  70298. };
  70299. PostProcess.prototype._disposeTextures = function () {
  70300. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  70301. return;
  70302. }
  70303. if (this._textures.length > 0) {
  70304. for (var i = 0; i < this._textures.length; i++) {
  70305. this._engine._releaseTexture(this._textures.data[i]);
  70306. }
  70307. }
  70308. this._textures.dispose();
  70309. };
  70310. /**
  70311. * Disposes the post process.
  70312. * @param camera The camera to dispose the post process on.
  70313. */
  70314. PostProcess.prototype.dispose = function (camera) {
  70315. camera = camera || this._camera;
  70316. this._disposeTextures();
  70317. if (this._scene) {
  70318. var index_1 = this._scene.postProcesses.indexOf(this);
  70319. if (index_1 !== -1) {
  70320. this._scene.postProcesses.splice(index_1, 1);
  70321. }
  70322. }
  70323. else {
  70324. var index_2 = this._engine.postProcesses.indexOf(this);
  70325. if (index_2 !== -1) {
  70326. this._engine.postProcesses.splice(index_2, 1);
  70327. }
  70328. }
  70329. if (!camera) {
  70330. return;
  70331. }
  70332. camera.detachPostProcess(this);
  70333. var index = camera._postProcesses.indexOf(this);
  70334. if (index === 0 && camera._postProcesses.length > 0) {
  70335. var firstPostProcess = this._camera._getFirstPostProcess();
  70336. if (firstPostProcess) {
  70337. firstPostProcess.markTextureDirty();
  70338. }
  70339. }
  70340. this.onActivateObservable.clear();
  70341. this.onAfterRenderObservable.clear();
  70342. this.onApplyObservable.clear();
  70343. this.onBeforeRenderObservable.clear();
  70344. this.onSizeChangedObservable.clear();
  70345. };
  70346. return PostProcess;
  70347. }());
  70348. BABYLON.PostProcess = PostProcess;
  70349. })(BABYLON || (BABYLON = {}));
  70350. //# sourceMappingURL=babylon.postProcess.js.map
  70351. var BABYLON;
  70352. (function (BABYLON) {
  70353. var PassPostProcess = /** @class */ (function (_super) {
  70354. __extends(PassPostProcess, _super);
  70355. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70356. if (camera === void 0) { camera = null; }
  70357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70358. if (blockCompilation === void 0) { blockCompilation = false; }
  70359. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  70360. }
  70361. return PassPostProcess;
  70362. }(BABYLON.PostProcess));
  70363. BABYLON.PassPostProcess = PassPostProcess;
  70364. })(BABYLON || (BABYLON = {}));
  70365. //# sourceMappingURL=babylon.passPostProcess.js.map
  70366. var __assign = (this && this.__assign) || function () {
  70367. __assign = Object.assign || function(t) {
  70368. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70369. s = arguments[i];
  70370. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  70371. t[p] = s[p];
  70372. }
  70373. return t;
  70374. };
  70375. return __assign.apply(this, arguments);
  70376. };
  70377. var BABYLON;
  70378. (function (BABYLON) {
  70379. /**
  70380. * Default implementation IShadowGenerator.
  70381. * This is the main object responsible of generating shadows in the framework.
  70382. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  70383. */
  70384. var ShadowGenerator = /** @class */ (function () {
  70385. /**
  70386. * Creates a ShadowGenerator object.
  70387. * A ShadowGenerator is the required tool to use the shadows.
  70388. * Each light casting shadows needs to use its own ShadowGenerator.
  70389. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  70390. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  70391. * @param light The light object generating the shadows.
  70392. * @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.
  70393. */
  70394. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  70395. this._bias = 0.00005;
  70396. this._normalBias = 0;
  70397. this._blurBoxOffset = 1;
  70398. this._blurScale = 2;
  70399. this._blurKernel = 1;
  70400. this._useKernelBlur = false;
  70401. this._filter = ShadowGenerator.FILTER_NONE;
  70402. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  70403. this._contactHardeningLightSizeUVRatio = 0.1;
  70404. this._darkness = 0;
  70405. this._transparencyShadow = false;
  70406. /**
  70407. * Controls the extent to which the shadows fade out at the edge of the frustum
  70408. * Used only by directionals and spots
  70409. */
  70410. this.frustumEdgeFalloff = 0;
  70411. /**
  70412. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  70413. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  70414. * It might on the other hand introduce peter panning.
  70415. */
  70416. this.forceBackFacesOnly = false;
  70417. this._lightDirection = BABYLON.Vector3.Zero();
  70418. this._viewMatrix = BABYLON.Matrix.Zero();
  70419. this._projectionMatrix = BABYLON.Matrix.Zero();
  70420. this._transformMatrix = BABYLON.Matrix.Zero();
  70421. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70422. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70423. this._currentFaceIndex = 0;
  70424. this._currentFaceIndexCache = 0;
  70425. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  70426. this._mapSize = mapSize;
  70427. this._light = light;
  70428. this._scene = light.getScene();
  70429. light._shadowGenerator = this;
  70430. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  70431. if (!component) {
  70432. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  70433. this._scene._addComponent(component);
  70434. }
  70435. // Texture type fallback from float to int if not supported.
  70436. var caps = this._scene.getEngine().getCaps();
  70437. if (!useFullFloatFirst) {
  70438. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70439. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70440. }
  70441. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70442. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70443. }
  70444. else {
  70445. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70446. }
  70447. }
  70448. else {
  70449. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70450. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70451. }
  70452. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70453. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70454. }
  70455. else {
  70456. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70457. }
  70458. }
  70459. this._initializeGenerator();
  70460. this._applyFilterValues();
  70461. }
  70462. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  70463. /**
  70464. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  70465. */
  70466. get: function () {
  70467. return this._bias;
  70468. },
  70469. /**
  70470. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  70471. */
  70472. set: function (bias) {
  70473. this._bias = bias;
  70474. },
  70475. enumerable: true,
  70476. configurable: true
  70477. });
  70478. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  70479. /**
  70480. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70481. */
  70482. get: function () {
  70483. return this._normalBias;
  70484. },
  70485. /**
  70486. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70487. */
  70488. set: function (normalBias) {
  70489. this._normalBias = normalBias;
  70490. },
  70491. enumerable: true,
  70492. configurable: true
  70493. });
  70494. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  70495. /**
  70496. * Gets the blur box offset: offset applied during the blur pass.
  70497. * Only usefull if useKernelBlur = false
  70498. */
  70499. get: function () {
  70500. return this._blurBoxOffset;
  70501. },
  70502. /**
  70503. * Sets the blur box offset: offset applied during the blur pass.
  70504. * Only usefull if useKernelBlur = false
  70505. */
  70506. set: function (value) {
  70507. if (this._blurBoxOffset === value) {
  70508. return;
  70509. }
  70510. this._blurBoxOffset = value;
  70511. this._disposeBlurPostProcesses();
  70512. },
  70513. enumerable: true,
  70514. configurable: true
  70515. });
  70516. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  70517. /**
  70518. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  70519. * 2 means half of the size.
  70520. */
  70521. get: function () {
  70522. return this._blurScale;
  70523. },
  70524. /**
  70525. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  70526. * 2 means half of the size.
  70527. */
  70528. set: function (value) {
  70529. if (this._blurScale === value) {
  70530. return;
  70531. }
  70532. this._blurScale = value;
  70533. this._disposeBlurPostProcesses();
  70534. },
  70535. enumerable: true,
  70536. configurable: true
  70537. });
  70538. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70539. /**
  70540. * Gets the blur kernel: kernel size of the blur pass.
  70541. * Only usefull if useKernelBlur = true
  70542. */
  70543. get: function () {
  70544. return this._blurKernel;
  70545. },
  70546. /**
  70547. * Sets the blur kernel: kernel size of the blur pass.
  70548. * Only usefull if useKernelBlur = true
  70549. */
  70550. set: function (value) {
  70551. if (this._blurKernel === value) {
  70552. return;
  70553. }
  70554. this._blurKernel = value;
  70555. this._disposeBlurPostProcesses();
  70556. },
  70557. enumerable: true,
  70558. configurable: true
  70559. });
  70560. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70561. /**
  70562. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70563. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70564. */
  70565. get: function () {
  70566. return this._useKernelBlur;
  70567. },
  70568. /**
  70569. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70570. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70571. */
  70572. set: function (value) {
  70573. if (this._useKernelBlur === value) {
  70574. return;
  70575. }
  70576. this._useKernelBlur = value;
  70577. this._disposeBlurPostProcesses();
  70578. },
  70579. enumerable: true,
  70580. configurable: true
  70581. });
  70582. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70583. /**
  70584. * Gets the depth scale used in ESM mode.
  70585. */
  70586. get: function () {
  70587. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70588. },
  70589. /**
  70590. * Sets the depth scale used in ESM mode.
  70591. * This can override the scale stored on the light.
  70592. */
  70593. set: function (value) {
  70594. this._depthScale = value;
  70595. },
  70596. enumerable: true,
  70597. configurable: true
  70598. });
  70599. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70600. /**
  70601. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70602. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70603. */
  70604. get: function () {
  70605. return this._filter;
  70606. },
  70607. /**
  70608. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70609. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70610. */
  70611. set: function (value) {
  70612. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70613. if (this._light.needCube()) {
  70614. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70615. this.useExponentialShadowMap = true;
  70616. return;
  70617. }
  70618. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70619. this.useCloseExponentialShadowMap = true;
  70620. return;
  70621. }
  70622. // PCF on cubemap would also be expensive
  70623. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70624. this.usePoissonSampling = true;
  70625. return;
  70626. }
  70627. }
  70628. // Weblg1 fallback for PCF.
  70629. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70630. if (this._scene.getEngine().webGLVersion === 1) {
  70631. this.usePoissonSampling = true;
  70632. return;
  70633. }
  70634. }
  70635. if (this._filter === value) {
  70636. return;
  70637. }
  70638. this._filter = value;
  70639. this._disposeBlurPostProcesses();
  70640. this._applyFilterValues();
  70641. this._light._markMeshesAsLightDirty();
  70642. },
  70643. enumerable: true,
  70644. configurable: true
  70645. });
  70646. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70647. /**
  70648. * Gets if the current filter is set to Poisson Sampling.
  70649. */
  70650. get: function () {
  70651. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70652. },
  70653. /**
  70654. * Sets the current filter to Poisson Sampling.
  70655. */
  70656. set: function (value) {
  70657. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70658. return;
  70659. }
  70660. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70661. },
  70662. enumerable: true,
  70663. configurable: true
  70664. });
  70665. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70666. /**
  70667. * Gets if the current filter is set to VSM.
  70668. * DEPRECATED. Should use useExponentialShadowMap instead.
  70669. */
  70670. get: function () {
  70671. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70672. return this.useExponentialShadowMap;
  70673. },
  70674. /**
  70675. * Sets the current filter is to VSM.
  70676. * DEPRECATED. Should use useExponentialShadowMap instead.
  70677. */
  70678. set: function (value) {
  70679. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70680. this.useExponentialShadowMap = value;
  70681. },
  70682. enumerable: true,
  70683. configurable: true
  70684. });
  70685. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70686. /**
  70687. * Gets if the current filter is set to blurred VSM.
  70688. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70689. */
  70690. get: function () {
  70691. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70692. return this.useBlurExponentialShadowMap;
  70693. },
  70694. /**
  70695. * Sets the current filter is to blurred VSM.
  70696. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70697. */
  70698. set: function (value) {
  70699. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70700. this.useBlurExponentialShadowMap = value;
  70701. },
  70702. enumerable: true,
  70703. configurable: true
  70704. });
  70705. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70706. /**
  70707. * Gets if the current filter is set to ESM.
  70708. */
  70709. get: function () {
  70710. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70711. },
  70712. /**
  70713. * Sets the current filter is to ESM.
  70714. */
  70715. set: function (value) {
  70716. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70717. return;
  70718. }
  70719. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70720. },
  70721. enumerable: true,
  70722. configurable: true
  70723. });
  70724. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70725. /**
  70726. * Gets if the current filter is set to filtered ESM.
  70727. */
  70728. get: function () {
  70729. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70730. },
  70731. /**
  70732. * Gets if the current filter is set to filtered ESM.
  70733. */
  70734. set: function (value) {
  70735. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70736. return;
  70737. }
  70738. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70739. },
  70740. enumerable: true,
  70741. configurable: true
  70742. });
  70743. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70744. /**
  70745. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70746. * exponential to prevent steep falloff artifacts).
  70747. */
  70748. get: function () {
  70749. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70750. },
  70751. /**
  70752. * Sets the current filter to "close ESM" (using the inverse of the
  70753. * exponential to prevent steep falloff artifacts).
  70754. */
  70755. set: function (value) {
  70756. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70757. return;
  70758. }
  70759. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70760. },
  70761. enumerable: true,
  70762. configurable: true
  70763. });
  70764. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70765. /**
  70766. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70767. * exponential to prevent steep falloff artifacts).
  70768. */
  70769. get: function () {
  70770. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70771. },
  70772. /**
  70773. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70774. * exponential to prevent steep falloff artifacts).
  70775. */
  70776. set: function (value) {
  70777. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70778. return;
  70779. }
  70780. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70781. },
  70782. enumerable: true,
  70783. configurable: true
  70784. });
  70785. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70786. /**
  70787. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70788. */
  70789. get: function () {
  70790. return this.filter === ShadowGenerator.FILTER_PCF;
  70791. },
  70792. /**
  70793. * Sets the current filter to "PCF" (percentage closer filtering).
  70794. */
  70795. set: function (value) {
  70796. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70797. return;
  70798. }
  70799. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70800. },
  70801. enumerable: true,
  70802. configurable: true
  70803. });
  70804. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70805. /**
  70806. * Gets the PCF or PCSS Quality.
  70807. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70808. */
  70809. get: function () {
  70810. return this._filteringQuality;
  70811. },
  70812. /**
  70813. * Sets the PCF or PCSS Quality.
  70814. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70815. */
  70816. set: function (filteringQuality) {
  70817. this._filteringQuality = filteringQuality;
  70818. },
  70819. enumerable: true,
  70820. configurable: true
  70821. });
  70822. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70823. /**
  70824. * Gets if the current filter is set to "PCSS" (contact hardening).
  70825. */
  70826. get: function () {
  70827. return this.filter === ShadowGenerator.FILTER_PCSS;
  70828. },
  70829. /**
  70830. * Sets the current filter to "PCSS" (contact hardening).
  70831. */
  70832. set: function (value) {
  70833. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70834. return;
  70835. }
  70836. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70837. },
  70838. enumerable: true,
  70839. configurable: true
  70840. });
  70841. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70842. /**
  70843. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70844. * Using a ratio helps keeping shape stability independently of the map size.
  70845. *
  70846. * It does not account for the light projection as it was having too much
  70847. * instability during the light setup or during light position changes.
  70848. *
  70849. * Only valid if useContactHardeningShadow is true.
  70850. */
  70851. get: function () {
  70852. return this._contactHardeningLightSizeUVRatio;
  70853. },
  70854. /**
  70855. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70856. * Using a ratio helps keeping shape stability independently of the map size.
  70857. *
  70858. * It does not account for the light projection as it was having too much
  70859. * instability during the light setup or during light position changes.
  70860. *
  70861. * Only valid if useContactHardeningShadow is true.
  70862. */
  70863. set: function (contactHardeningLightSizeUVRatio) {
  70864. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70865. },
  70866. enumerable: true,
  70867. configurable: true
  70868. });
  70869. /**
  70870. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70871. * 0 means strongest and 1 would means no shadow.
  70872. * @returns the darkness.
  70873. */
  70874. ShadowGenerator.prototype.getDarkness = function () {
  70875. return this._darkness;
  70876. };
  70877. /**
  70878. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70879. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70880. * @returns the shadow generator allowing fluent coding.
  70881. */
  70882. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70883. if (darkness >= 1.0)
  70884. this._darkness = 1.0;
  70885. else if (darkness <= 0.0)
  70886. this._darkness = 0.0;
  70887. else
  70888. this._darkness = darkness;
  70889. return this;
  70890. };
  70891. /**
  70892. * Sets the ability to have transparent shadow (boolean).
  70893. * @param transparent True if transparent else False
  70894. * @returns the shadow generator allowing fluent coding
  70895. */
  70896. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70897. this._transparencyShadow = transparent;
  70898. return this;
  70899. };
  70900. /**
  70901. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70902. * @returns The render target texture if present otherwise, null
  70903. */
  70904. ShadowGenerator.prototype.getShadowMap = function () {
  70905. return this._shadowMap;
  70906. };
  70907. /**
  70908. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70909. * @returns The render target texture if the shadow map is present otherwise, null
  70910. */
  70911. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70912. if (this._shadowMap2) {
  70913. return this._shadowMap2;
  70914. }
  70915. return this._shadowMap;
  70916. };
  70917. /**
  70918. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70919. * @param mesh Mesh to add
  70920. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70921. * @returns the Shadow Generator itself
  70922. */
  70923. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70924. if (includeDescendants === void 0) { includeDescendants = true; }
  70925. var _a;
  70926. if (!this._shadowMap) {
  70927. return this;
  70928. }
  70929. if (!this._shadowMap.renderList) {
  70930. this._shadowMap.renderList = [];
  70931. }
  70932. this._shadowMap.renderList.push(mesh);
  70933. if (includeDescendants) {
  70934. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70935. }
  70936. return this;
  70937. };
  70938. /**
  70939. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70940. * @param mesh Mesh to remove
  70941. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70942. * @returns the Shadow Generator itself
  70943. */
  70944. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70945. if (includeDescendants === void 0) { includeDescendants = true; }
  70946. if (!this._shadowMap || !this._shadowMap.renderList) {
  70947. return this;
  70948. }
  70949. var index = this._shadowMap.renderList.indexOf(mesh);
  70950. if (index !== -1) {
  70951. this._shadowMap.renderList.splice(index, 1);
  70952. }
  70953. if (includeDescendants) {
  70954. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70955. var child = _a[_i];
  70956. this.removeShadowCaster(child);
  70957. }
  70958. }
  70959. return this;
  70960. };
  70961. /**
  70962. * Returns the associated light object.
  70963. * @returns the light generating the shadow
  70964. */
  70965. ShadowGenerator.prototype.getLight = function () {
  70966. return this._light;
  70967. };
  70968. ShadowGenerator.prototype._initializeGenerator = function () {
  70969. this._light._markMeshesAsLightDirty();
  70970. this._initializeShadowMap();
  70971. };
  70972. ShadowGenerator.prototype._initializeShadowMap = function () {
  70973. var _this = this;
  70974. // Render target
  70975. var engine = this._scene.getEngine();
  70976. if (engine.webGLVersion > 1) {
  70977. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70978. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70979. }
  70980. else {
  70981. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70982. }
  70983. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70984. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70985. this._shadowMap.anisotropicFilteringLevel = 1;
  70986. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70987. this._shadowMap.renderParticles = false;
  70988. this._shadowMap.ignoreCameraViewport = true;
  70989. // Record Face Index before render.
  70990. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70991. _this._currentFaceIndex = faceIndex;
  70992. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70993. engine.setColorWrite(false);
  70994. }
  70995. });
  70996. // Custom render function.
  70997. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70998. // Blur if required afer render.
  70999. this._shadowMap.onAfterUnbindObservable.add(function () {
  71000. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  71001. engine.setColorWrite(true);
  71002. }
  71003. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  71004. return;
  71005. }
  71006. var shadowMap = _this.getShadowMapForRendering();
  71007. if (shadowMap) {
  71008. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  71009. }
  71010. });
  71011. // Clear according to the chosen filter.
  71012. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  71013. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  71014. this._shadowMap.onClearObservable.add(function (engine) {
  71015. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  71016. engine.clear(clearOne, false, true, false);
  71017. }
  71018. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  71019. engine.clear(clearZero, true, true, false);
  71020. }
  71021. else {
  71022. engine.clear(clearOne, true, true, false);
  71023. }
  71024. });
  71025. };
  71026. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  71027. var _this = this;
  71028. var engine = this._scene.getEngine();
  71029. var targetSize = this._mapSize / this.blurScale;
  71030. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  71031. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  71032. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71033. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71034. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71035. }
  71036. if (this.useKernelBlur) {
  71037. 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);
  71038. this._kernelBlurXPostprocess.width = targetSize;
  71039. this._kernelBlurXPostprocess.height = targetSize;
  71040. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  71041. effect.setTexture("textureSampler", _this._shadowMap);
  71042. });
  71043. 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);
  71044. this._kernelBlurXPostprocess.autoClear = false;
  71045. this._kernelBlurYPostprocess.autoClear = false;
  71046. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71047. this._kernelBlurXPostprocess.packedFloat = true;
  71048. this._kernelBlurYPostprocess.packedFloat = true;
  71049. }
  71050. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  71051. }
  71052. else {
  71053. 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);
  71054. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  71055. effect.setFloat2("screenSize", targetSize, targetSize);
  71056. effect.setTexture("textureSampler", _this._shadowMap);
  71057. });
  71058. this._boxBlurPostprocess.autoClear = false;
  71059. this._blurPostProcesses = [this._boxBlurPostprocess];
  71060. }
  71061. };
  71062. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71063. var index;
  71064. var engine = this._scene.getEngine();
  71065. if (depthOnlySubMeshes.length) {
  71066. engine.setColorWrite(false);
  71067. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71068. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  71069. }
  71070. engine.setColorWrite(true);
  71071. }
  71072. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71073. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  71074. }
  71075. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71076. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  71077. }
  71078. if (this._transparencyShadow) {
  71079. for (index = 0; index < transparentSubMeshes.length; index++) {
  71080. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  71081. }
  71082. }
  71083. };
  71084. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  71085. var _this = this;
  71086. var mesh = subMesh.getRenderingMesh();
  71087. var scene = this._scene;
  71088. var engine = scene.getEngine();
  71089. var material = subMesh.getMaterial();
  71090. if (!material) {
  71091. return;
  71092. }
  71093. // Culling
  71094. engine.setState(material.backFaceCulling);
  71095. // Managing instances
  71096. var batch = mesh._getInstancesRenderList(subMesh._id);
  71097. if (batch.mustReturn) {
  71098. return;
  71099. }
  71100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71101. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  71102. engine.enableEffect(this._effect);
  71103. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71104. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  71105. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  71106. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  71107. this._effect.setVector3("lightData", this._cachedDirection);
  71108. }
  71109. else {
  71110. this._effect.setVector3("lightData", this._cachedPosition);
  71111. }
  71112. if (scene.activeCamera) {
  71113. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  71114. }
  71115. // Alpha test
  71116. if (material && material.needAlphaTesting()) {
  71117. var alphaTexture = material.getAlphaTestTexture();
  71118. if (alphaTexture) {
  71119. this._effect.setTexture("diffuseSampler", alphaTexture);
  71120. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  71121. }
  71122. }
  71123. // Bones
  71124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71125. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  71126. }
  71127. // Morph targets
  71128. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  71129. if (this.forceBackFacesOnly) {
  71130. engine.setState(true, 0, false, true);
  71131. }
  71132. // Draw
  71133. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71134. if (this.forceBackFacesOnly) {
  71135. engine.setState(true, 0, false, false);
  71136. }
  71137. }
  71138. else {
  71139. // Need to reset refresh rate of the shadowMap
  71140. if (this._shadowMap) {
  71141. this._shadowMap.resetRefreshCounter();
  71142. }
  71143. }
  71144. };
  71145. ShadowGenerator.prototype._applyFilterValues = function () {
  71146. if (!this._shadowMap) {
  71147. return;
  71148. }
  71149. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  71150. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  71151. }
  71152. else {
  71153. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71154. }
  71155. };
  71156. /**
  71157. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  71158. * @param onCompiled Callback triggered at the and of the effects compilation
  71159. * @param options Sets of optional options forcing the compilation with different modes
  71160. */
  71161. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  71162. var _this = this;
  71163. var localOptions = __assign({ useInstances: false }, options);
  71164. var shadowMap = this.getShadowMap();
  71165. if (!shadowMap) {
  71166. if (onCompiled) {
  71167. onCompiled(this);
  71168. }
  71169. return;
  71170. }
  71171. var renderList = shadowMap.renderList;
  71172. if (!renderList) {
  71173. if (onCompiled) {
  71174. onCompiled(this);
  71175. }
  71176. return;
  71177. }
  71178. var subMeshes = new Array();
  71179. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  71180. var mesh = renderList_1[_i];
  71181. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  71182. }
  71183. if (subMeshes.length === 0) {
  71184. if (onCompiled) {
  71185. onCompiled(this);
  71186. }
  71187. return;
  71188. }
  71189. var currentIndex = 0;
  71190. var checkReady = function () {
  71191. if (!_this._scene || !_this._scene.getEngine()) {
  71192. return;
  71193. }
  71194. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  71195. currentIndex++;
  71196. if (currentIndex >= subMeshes.length) {
  71197. if (onCompiled) {
  71198. onCompiled(_this);
  71199. }
  71200. return;
  71201. }
  71202. }
  71203. setTimeout(checkReady, 16);
  71204. };
  71205. checkReady();
  71206. };
  71207. /**
  71208. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  71209. * @param options Sets of optional options forcing the compilation with different modes
  71210. * @returns A promise that resolves when the compilation completes
  71211. */
  71212. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  71213. var _this = this;
  71214. return new Promise(function (resolve) {
  71215. _this.forceCompilation(function () {
  71216. resolve();
  71217. }, options);
  71218. });
  71219. };
  71220. /**
  71221. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  71222. * @param subMesh The submesh we want to render in the shadow map
  71223. * @param useInstances Defines wether will draw in the map using instances
  71224. * @returns true if ready otherwise, false
  71225. */
  71226. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  71227. var defines = [];
  71228. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71229. defines.push("#define FLOAT");
  71230. }
  71231. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71232. defines.push("#define ESM");
  71233. }
  71234. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  71235. defines.push("#define DEPTHTEXTURE");
  71236. }
  71237. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71238. var mesh = subMesh.getMesh();
  71239. var material = subMesh.getMaterial();
  71240. // Normal bias.
  71241. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71242. attribs.push(BABYLON.VertexBuffer.NormalKind);
  71243. defines.push("#define NORMAL");
  71244. if (mesh.nonUniformScaling) {
  71245. defines.push("#define NONUNIFORMSCALING");
  71246. }
  71247. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  71248. defines.push("#define DIRECTIONINLIGHTDATA");
  71249. }
  71250. }
  71251. // Alpha test
  71252. if (material && material.needAlphaTesting()) {
  71253. var alphaTexture = material.getAlphaTestTexture();
  71254. if (alphaTexture) {
  71255. defines.push("#define ALPHATEST");
  71256. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71257. attribs.push(BABYLON.VertexBuffer.UVKind);
  71258. defines.push("#define UV1");
  71259. }
  71260. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71261. if (alphaTexture.coordinatesIndex === 1) {
  71262. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71263. defines.push("#define UV2");
  71264. }
  71265. }
  71266. }
  71267. }
  71268. // Bones
  71269. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71270. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71271. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71272. if (mesh.numBoneInfluencers > 4) {
  71273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71275. }
  71276. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71277. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  71278. }
  71279. else {
  71280. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71281. }
  71282. // Morph targets
  71283. var manager = mesh.morphTargetManager;
  71284. var morphInfluencers = 0;
  71285. if (manager) {
  71286. if (manager.numInfluencers > 0) {
  71287. defines.push("#define MORPHTARGETS");
  71288. morphInfluencers = manager.numInfluencers;
  71289. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  71290. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  71291. }
  71292. }
  71293. // Instances
  71294. if (useInstances) {
  71295. defines.push("#define INSTANCES");
  71296. attribs.push("world0");
  71297. attribs.push("world1");
  71298. attribs.push("world2");
  71299. attribs.push("world3");
  71300. }
  71301. // Get correct effect
  71302. var join = defines.join("\n");
  71303. if (this._cachedDefines !== join) {
  71304. this._cachedDefines = join;
  71305. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  71306. }
  71307. if (!this._effect.isReady()) {
  71308. return false;
  71309. }
  71310. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71311. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  71312. this._initializeBlurRTTAndPostProcesses();
  71313. }
  71314. }
  71315. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  71316. return false;
  71317. }
  71318. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  71319. return false;
  71320. }
  71321. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  71322. return false;
  71323. }
  71324. return true;
  71325. };
  71326. /**
  71327. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  71328. * @param defines Defines of the material we want to update
  71329. * @param lightIndex Index of the light in the enabled light list of the material
  71330. */
  71331. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  71332. var scene = this._scene;
  71333. var light = this._light;
  71334. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71335. return;
  71336. }
  71337. defines["SHADOW" + lightIndex] = true;
  71338. if (this.useContactHardeningShadow) {
  71339. defines["SHADOWPCSS" + lightIndex] = true;
  71340. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71341. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71342. }
  71343. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71344. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71345. }
  71346. // else default to high.
  71347. }
  71348. if (this.usePercentageCloserFiltering) {
  71349. defines["SHADOWPCF" + lightIndex] = true;
  71350. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71351. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71352. }
  71353. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71354. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71355. }
  71356. // else default to high.
  71357. }
  71358. else if (this.usePoissonSampling) {
  71359. defines["SHADOWPOISSON" + lightIndex] = true;
  71360. }
  71361. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71362. defines["SHADOWESM" + lightIndex] = true;
  71363. }
  71364. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71365. defines["SHADOWCLOSEESM" + lightIndex] = true;
  71366. }
  71367. if (light.needCube()) {
  71368. defines["SHADOWCUBE" + lightIndex] = true;
  71369. }
  71370. };
  71371. /**
  71372. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  71373. * defined in the generator but impacting the effect).
  71374. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  71375. * @param effect The effect we are binfing the information for
  71376. */
  71377. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  71378. var light = this._light;
  71379. var scene = this._scene;
  71380. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71381. return;
  71382. }
  71383. var camera = scene.activeCamera;
  71384. if (!camera) {
  71385. return;
  71386. }
  71387. var shadowMap = this.getShadowMap();
  71388. if (!shadowMap) {
  71389. return;
  71390. }
  71391. if (!light.needCube()) {
  71392. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  71393. }
  71394. // Only PCF uses depth stencil texture.
  71395. if (this._filter === ShadowGenerator.FILTER_PCF) {
  71396. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71397. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71398. }
  71399. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  71400. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71401. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  71402. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71403. }
  71404. else {
  71405. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71406. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  71407. }
  71408. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  71409. };
  71410. /**
  71411. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  71412. * (eq to shadow prjection matrix * light transform matrix)
  71413. * @returns The transform matrix used to create the shadow map
  71414. */
  71415. ShadowGenerator.prototype.getTransformMatrix = function () {
  71416. var scene = this._scene;
  71417. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  71418. return this._transformMatrix;
  71419. }
  71420. this._currentRenderID = scene.getRenderId();
  71421. this._currentFaceIndexCache = this._currentFaceIndex;
  71422. var lightPosition = this._light.position;
  71423. if (this._light.computeTransformedInformation()) {
  71424. lightPosition = this._light.transformedPosition;
  71425. }
  71426. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  71427. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  71428. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  71429. }
  71430. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  71431. this._cachedPosition.copyFrom(lightPosition);
  71432. this._cachedDirection.copyFrom(this._lightDirection);
  71433. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  71434. var shadowMap = this.getShadowMap();
  71435. if (shadowMap) {
  71436. var renderList = shadowMap.renderList;
  71437. if (renderList) {
  71438. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  71439. }
  71440. }
  71441. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  71442. }
  71443. return this._transformMatrix;
  71444. };
  71445. /**
  71446. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  71447. * Cube and 2D textures for instance.
  71448. */
  71449. ShadowGenerator.prototype.recreateShadowMap = function () {
  71450. var shadowMap = this._shadowMap;
  71451. if (!shadowMap) {
  71452. return;
  71453. }
  71454. // Track render list.
  71455. var renderList = shadowMap.renderList;
  71456. // Clean up existing data.
  71457. this._disposeRTTandPostProcesses();
  71458. // Reinitializes.
  71459. this._initializeGenerator();
  71460. // Reaffect the filter to ensure a correct fallback if necessary.
  71461. this.filter = this.filter;
  71462. // Reaffect the filter.
  71463. this._applyFilterValues();
  71464. // Reaffect Render List.
  71465. this._shadowMap.renderList = renderList;
  71466. };
  71467. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  71468. if (this._shadowMap2) {
  71469. this._shadowMap2.dispose();
  71470. this._shadowMap2 = null;
  71471. }
  71472. if (this._boxBlurPostprocess) {
  71473. this._boxBlurPostprocess.dispose();
  71474. this._boxBlurPostprocess = null;
  71475. }
  71476. if (this._kernelBlurXPostprocess) {
  71477. this._kernelBlurXPostprocess.dispose();
  71478. this._kernelBlurXPostprocess = null;
  71479. }
  71480. if (this._kernelBlurYPostprocess) {
  71481. this._kernelBlurYPostprocess.dispose();
  71482. this._kernelBlurYPostprocess = null;
  71483. }
  71484. this._blurPostProcesses = [];
  71485. };
  71486. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  71487. if (this._shadowMap) {
  71488. this._shadowMap.dispose();
  71489. this._shadowMap = null;
  71490. }
  71491. this._disposeBlurPostProcesses();
  71492. };
  71493. /**
  71494. * Disposes the ShadowGenerator.
  71495. * Returns nothing.
  71496. */
  71497. ShadowGenerator.prototype.dispose = function () {
  71498. this._disposeRTTandPostProcesses();
  71499. if (this._light) {
  71500. this._light._shadowGenerator = null;
  71501. this._light._markMeshesAsLightDirty();
  71502. }
  71503. };
  71504. /**
  71505. * Serializes the shadow generator setup to a json object.
  71506. * @returns The serialized JSON object
  71507. */
  71508. ShadowGenerator.prototype.serialize = function () {
  71509. var serializationObject = {};
  71510. var shadowMap = this.getShadowMap();
  71511. if (!shadowMap) {
  71512. return serializationObject;
  71513. }
  71514. serializationObject.lightId = this._light.id;
  71515. serializationObject.mapSize = shadowMap.getRenderSize();
  71516. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  71517. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  71518. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71519. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71520. serializationObject.usePoissonSampling = this.usePoissonSampling;
  71521. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  71522. serializationObject.depthScale = this.depthScale;
  71523. serializationObject.darkness = this.getDarkness();
  71524. serializationObject.blurBoxOffset = this.blurBoxOffset;
  71525. serializationObject.blurKernel = this.blurKernel;
  71526. serializationObject.blurScale = this.blurScale;
  71527. serializationObject.useKernelBlur = this.useKernelBlur;
  71528. serializationObject.transparencyShadow = this._transparencyShadow;
  71529. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  71530. serializationObject.bias = this.bias;
  71531. serializationObject.normalBias = this.normalBias;
  71532. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  71533. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  71534. serializationObject.filteringQuality = this.filteringQuality;
  71535. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71536. serializationObject.renderList = [];
  71537. if (shadowMap.renderList) {
  71538. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71539. var mesh = shadowMap.renderList[meshIndex];
  71540. serializationObject.renderList.push(mesh.id);
  71541. }
  71542. }
  71543. return serializationObject;
  71544. };
  71545. /**
  71546. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71547. * @param parsedShadowGenerator The JSON object to parse
  71548. * @param scene The scene to create the shadow map for
  71549. * @returns The parsed shadow generator
  71550. */
  71551. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71552. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71553. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71554. var shadowMap = shadowGenerator.getShadowMap();
  71555. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71556. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71557. meshes.forEach(function (mesh) {
  71558. if (!shadowMap) {
  71559. return;
  71560. }
  71561. if (!shadowMap.renderList) {
  71562. shadowMap.renderList = [];
  71563. }
  71564. shadowMap.renderList.push(mesh);
  71565. });
  71566. }
  71567. if (parsedShadowGenerator.usePoissonSampling) {
  71568. shadowGenerator.usePoissonSampling = true;
  71569. }
  71570. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71571. shadowGenerator.useExponentialShadowMap = true;
  71572. }
  71573. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71574. shadowGenerator.useBlurExponentialShadowMap = true;
  71575. }
  71576. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71577. shadowGenerator.useCloseExponentialShadowMap = true;
  71578. }
  71579. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71580. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71581. }
  71582. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71583. shadowGenerator.usePercentageCloserFiltering = true;
  71584. }
  71585. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71586. shadowGenerator.useContactHardeningShadow = true;
  71587. }
  71588. if (parsedShadowGenerator.filteringQuality) {
  71589. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71590. }
  71591. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71592. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71593. }
  71594. // Backward compat
  71595. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71596. shadowGenerator.useExponentialShadowMap = true;
  71597. }
  71598. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71599. shadowGenerator.useBlurExponentialShadowMap = true;
  71600. }
  71601. if (parsedShadowGenerator.depthScale) {
  71602. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71603. }
  71604. if (parsedShadowGenerator.blurScale) {
  71605. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71606. }
  71607. if (parsedShadowGenerator.blurBoxOffset) {
  71608. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71609. }
  71610. if (parsedShadowGenerator.useKernelBlur) {
  71611. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71612. }
  71613. if (parsedShadowGenerator.blurKernel) {
  71614. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71615. }
  71616. if (parsedShadowGenerator.bias !== undefined) {
  71617. shadowGenerator.bias = parsedShadowGenerator.bias;
  71618. }
  71619. if (parsedShadowGenerator.normalBias !== undefined) {
  71620. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71621. }
  71622. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71623. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71624. }
  71625. if (parsedShadowGenerator.darkness) {
  71626. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71627. }
  71628. if (parsedShadowGenerator.transparencyShadow) {
  71629. shadowGenerator.setTransparencyShadow(true);
  71630. }
  71631. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71632. return shadowGenerator;
  71633. };
  71634. /**
  71635. * Shadow generator mode None: no filtering applied.
  71636. */
  71637. ShadowGenerator.FILTER_NONE = 0;
  71638. /**
  71639. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71640. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71641. */
  71642. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71643. /**
  71644. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71645. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71646. */
  71647. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71648. /**
  71649. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71650. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71651. */
  71652. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71653. /**
  71654. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71655. * edge artifacts on steep falloff.
  71656. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71657. */
  71658. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71659. /**
  71660. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71661. * edge artifacts on steep falloff.
  71662. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71663. */
  71664. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71665. /**
  71666. * Shadow generator mode PCF: Percentage Closer Filtering
  71667. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71668. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71669. */
  71670. ShadowGenerator.FILTER_PCF = 6;
  71671. /**
  71672. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71673. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71674. * Contact Hardening
  71675. */
  71676. ShadowGenerator.FILTER_PCSS = 7;
  71677. /**
  71678. * Reserved for PCF and PCSS
  71679. * Highest Quality.
  71680. *
  71681. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71682. *
  71683. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71684. */
  71685. ShadowGenerator.QUALITY_HIGH = 0;
  71686. /**
  71687. * Reserved for PCF and PCSS
  71688. * Good tradeoff for quality/perf cross devices
  71689. *
  71690. * Execute PCF on a 3*3 kernel.
  71691. *
  71692. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71693. */
  71694. ShadowGenerator.QUALITY_MEDIUM = 1;
  71695. /**
  71696. * Reserved for PCF and PCSS
  71697. * The lowest quality but the fastest.
  71698. *
  71699. * Execute PCF on a 1*1 kernel.
  71700. *
  71701. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71702. */
  71703. ShadowGenerator.QUALITY_LOW = 2;
  71704. return ShadowGenerator;
  71705. }());
  71706. BABYLON.ShadowGenerator = ShadowGenerator;
  71707. })(BABYLON || (BABYLON = {}));
  71708. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71709. var BABYLON;
  71710. (function (BABYLON) {
  71711. // Adds the parser to the scene parsers.
  71712. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71713. // Shadows
  71714. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71715. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71716. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71717. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71718. // SG would be available on their associated lights
  71719. }
  71720. }
  71721. });
  71722. /**
  71723. * Defines the shadow generator component responsible to manage any shadow generators
  71724. * in a given scene.
  71725. */
  71726. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71727. /**
  71728. * Creates a new instance of the component for the given scene
  71729. * @param scene Defines the scene to register the component in
  71730. */
  71731. function ShadowGeneratorSceneComponent(scene) {
  71732. /**
  71733. * The component name helpfull to identify the component in the list of scene components.
  71734. */
  71735. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71736. this.scene = scene;
  71737. }
  71738. /**
  71739. * Registers the component in a given scene
  71740. */
  71741. ShadowGeneratorSceneComponent.prototype.register = function () {
  71742. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71743. };
  71744. /**
  71745. * Rebuilds the elements related to this component in case of
  71746. * context lost for instance.
  71747. */
  71748. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71749. // Nothing To Do Here.
  71750. };
  71751. /**
  71752. * Serializes the component data to the specified json object
  71753. * @param serializationObject The object to serialize to
  71754. */
  71755. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71756. // Shadows
  71757. serializationObject.shadowGenerators = [];
  71758. var lights = this.scene.lights;
  71759. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71760. var light = lights_1[_i];
  71761. var shadowGenerator = light.getShadowGenerator();
  71762. if (shadowGenerator) {
  71763. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71764. }
  71765. }
  71766. };
  71767. /**
  71768. * Adds all the element from the container to the scene
  71769. * @param container the container holding the elements
  71770. */
  71771. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71772. // Nothing To Do Here. (directly attached to a light)
  71773. };
  71774. /**
  71775. * Removes all the elements in the container from the scene
  71776. * @param container contains the elements to remove
  71777. */
  71778. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71779. // Nothing To Do Here. (directly attached to a light)
  71780. };
  71781. /**
  71782. * Rebuilds the elements related to this component in case of
  71783. * context lost for instance.
  71784. */
  71785. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71786. // Nothing To Do Here.
  71787. };
  71788. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71789. // Shadows
  71790. var scene = this.scene;
  71791. if (this.scene.shadowsEnabled) {
  71792. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71793. var light = scene.lights[lightIndex];
  71794. var shadowGenerator = light.getShadowGenerator();
  71795. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71796. var shadowMap = (shadowGenerator.getShadowMap());
  71797. if (scene.textures.indexOf(shadowMap) !== -1) {
  71798. renderTargets.push(shadowMap);
  71799. }
  71800. }
  71801. }
  71802. }
  71803. };
  71804. return ShadowGeneratorSceneComponent;
  71805. }());
  71806. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71807. })(BABYLON || (BABYLON = {}));
  71808. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71809. var BABYLON;
  71810. (function (BABYLON) {
  71811. var DefaultLoadingScreen = /** @class */ (function () {
  71812. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71813. if (_loadingText === void 0) { _loadingText = ""; }
  71814. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71815. var _this = this;
  71816. this._renderingCanvas = _renderingCanvas;
  71817. this._loadingText = _loadingText;
  71818. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71819. // Resize
  71820. this._resizeLoadingUI = function () {
  71821. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71822. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71823. if (!_this._loadingDiv) {
  71824. return;
  71825. }
  71826. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71827. _this._loadingDiv.style.left = canvasRect.left + "px";
  71828. _this._loadingDiv.style.top = canvasRect.top + "px";
  71829. _this._loadingDiv.style.width = canvasRect.width + "px";
  71830. _this._loadingDiv.style.height = canvasRect.height + "px";
  71831. };
  71832. }
  71833. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71834. if (this._loadingDiv) {
  71835. // Do not add a loading screen if there is already one
  71836. return;
  71837. }
  71838. this._loadingDiv = document.createElement("div");
  71839. this._loadingDiv.id = "babylonjsLoadingDiv";
  71840. this._loadingDiv.style.opacity = "0";
  71841. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71842. this._loadingDiv.style.pointerEvents = "none";
  71843. // Loading text
  71844. this._loadingTextDiv = document.createElement("div");
  71845. this._loadingTextDiv.style.position = "absolute";
  71846. this._loadingTextDiv.style.left = "0";
  71847. this._loadingTextDiv.style.top = "50%";
  71848. this._loadingTextDiv.style.marginTop = "80px";
  71849. this._loadingTextDiv.style.width = "100%";
  71850. this._loadingTextDiv.style.height = "20px";
  71851. this._loadingTextDiv.style.fontFamily = "Arial";
  71852. this._loadingTextDiv.style.fontSize = "14px";
  71853. this._loadingTextDiv.style.color = "white";
  71854. this._loadingTextDiv.style.textAlign = "center";
  71855. this._loadingTextDiv.innerHTML = "Loading";
  71856. this._loadingDiv.appendChild(this._loadingTextDiv);
  71857. //set the predefined text
  71858. this._loadingTextDiv.innerHTML = this._loadingText;
  71859. // Generating keyframes
  71860. var style = document.createElement('style');
  71861. style.type = 'text/css';
  71862. 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 }";
  71863. style.innerHTML = keyFrames;
  71864. document.getElementsByTagName('head')[0].appendChild(style);
  71865. // Loading img
  71866. var imgBack = new Image();
  71867. 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";
  71868. imgBack.style.position = "absolute";
  71869. imgBack.style.left = "50%";
  71870. imgBack.style.top = "50%";
  71871. imgBack.style.marginLeft = "-60px";
  71872. imgBack.style.marginTop = "-60px";
  71873. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71874. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71875. imgBack.style.transformOrigin = "50% 50%";
  71876. imgBack.style.webkitTransformOrigin = "50% 50%";
  71877. this._loadingDiv.appendChild(imgBack);
  71878. this._resizeLoadingUI();
  71879. window.addEventListener("resize", this._resizeLoadingUI);
  71880. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71881. document.body.appendChild(this._loadingDiv);
  71882. this._loadingDiv.style.opacity = "1";
  71883. };
  71884. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71885. var _this = this;
  71886. if (!this._loadingDiv) {
  71887. return;
  71888. }
  71889. var onTransitionEnd = function () {
  71890. if (!_this._loadingDiv) {
  71891. return;
  71892. }
  71893. document.body.removeChild(_this._loadingDiv);
  71894. window.removeEventListener("resize", _this._resizeLoadingUI);
  71895. _this._loadingDiv = null;
  71896. };
  71897. this._loadingDiv.style.opacity = "0";
  71898. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71899. };
  71900. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71901. set: function (text) {
  71902. this._loadingText = text;
  71903. if (this._loadingTextDiv) {
  71904. this._loadingTextDiv.innerHTML = this._loadingText;
  71905. }
  71906. },
  71907. enumerable: true,
  71908. configurable: true
  71909. });
  71910. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71911. get: function () {
  71912. return this._loadingDivBackgroundColor;
  71913. },
  71914. set: function (color) {
  71915. this._loadingDivBackgroundColor = color;
  71916. if (!this._loadingDiv) {
  71917. return;
  71918. }
  71919. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71920. },
  71921. enumerable: true,
  71922. configurable: true
  71923. });
  71924. return DefaultLoadingScreen;
  71925. }());
  71926. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71927. })(BABYLON || (BABYLON = {}));
  71928. //# sourceMappingURL=babylon.loadingScreen.js.map
  71929. var BABYLON;
  71930. (function (BABYLON) {
  71931. var SceneLoaderProgressEvent = /** @class */ (function () {
  71932. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71933. this.lengthComputable = lengthComputable;
  71934. this.loaded = loaded;
  71935. this.total = total;
  71936. }
  71937. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71938. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71939. };
  71940. return SceneLoaderProgressEvent;
  71941. }());
  71942. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71943. var SceneLoader = /** @class */ (function () {
  71944. function SceneLoader() {
  71945. }
  71946. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71947. get: function () {
  71948. return 0;
  71949. },
  71950. enumerable: true,
  71951. configurable: true
  71952. });
  71953. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71954. get: function () {
  71955. return 1;
  71956. },
  71957. enumerable: true,
  71958. configurable: true
  71959. });
  71960. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71961. get: function () {
  71962. return 2;
  71963. },
  71964. enumerable: true,
  71965. configurable: true
  71966. });
  71967. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71968. get: function () {
  71969. return 3;
  71970. },
  71971. enumerable: true,
  71972. configurable: true
  71973. });
  71974. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71975. get: function () {
  71976. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71977. },
  71978. set: function (value) {
  71979. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71980. },
  71981. enumerable: true,
  71982. configurable: true
  71983. });
  71984. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71985. get: function () {
  71986. return SceneLoader._ShowLoadingScreen;
  71987. },
  71988. set: function (value) {
  71989. SceneLoader._ShowLoadingScreen = value;
  71990. },
  71991. enumerable: true,
  71992. configurable: true
  71993. });
  71994. Object.defineProperty(SceneLoader, "loggingLevel", {
  71995. get: function () {
  71996. return SceneLoader._loggingLevel;
  71997. },
  71998. set: function (value) {
  71999. SceneLoader._loggingLevel = value;
  72000. },
  72001. enumerable: true,
  72002. configurable: true
  72003. });
  72004. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  72005. get: function () {
  72006. return SceneLoader._CleanBoneMatrixWeights;
  72007. },
  72008. set: function (value) {
  72009. SceneLoader._CleanBoneMatrixWeights = value;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. SceneLoader._getDefaultPlugin = function () {
  72015. return SceneLoader._registeredPlugins[".babylon"];
  72016. };
  72017. SceneLoader._getPluginForExtension = function (extension) {
  72018. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  72019. if (registeredPlugin) {
  72020. return registeredPlugin;
  72021. }
  72022. 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");
  72023. return SceneLoader._getDefaultPlugin();
  72024. };
  72025. SceneLoader._getPluginForDirectLoad = function (data) {
  72026. for (var extension in SceneLoader._registeredPlugins) {
  72027. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  72028. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  72029. return SceneLoader._registeredPlugins[extension];
  72030. }
  72031. }
  72032. return SceneLoader._getDefaultPlugin();
  72033. };
  72034. SceneLoader._getPluginForFilename = function (sceneFilename) {
  72035. var queryStringPosition = sceneFilename.indexOf("?");
  72036. if (queryStringPosition !== -1) {
  72037. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  72038. }
  72039. var dotPosition = sceneFilename.lastIndexOf(".");
  72040. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  72041. return SceneLoader._getPluginForExtension(extension);
  72042. };
  72043. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  72044. SceneLoader._getDirectLoad = function (sceneFilename) {
  72045. if (sceneFilename.substr(0, 5) === "data:") {
  72046. return sceneFilename.substr(5);
  72047. }
  72048. return null;
  72049. };
  72050. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  72051. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  72052. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  72053. var plugin;
  72054. if (registeredPlugin.plugin.createPlugin) {
  72055. plugin = registeredPlugin.plugin.createPlugin();
  72056. }
  72057. else {
  72058. plugin = registeredPlugin.plugin;
  72059. }
  72060. var useArrayBuffer = registeredPlugin.isBinary;
  72061. var database;
  72062. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  72063. var dataCallback = function (data, responseURL) {
  72064. if (scene.isDisposed) {
  72065. onError("Scene has been disposed");
  72066. return;
  72067. }
  72068. scene.database = database;
  72069. onSuccess(plugin, data, responseURL);
  72070. };
  72071. var request = null;
  72072. var pluginDisposed = false;
  72073. var onDisposeObservable = plugin.onDisposeObservable;
  72074. if (onDisposeObservable) {
  72075. onDisposeObservable.add(function () {
  72076. pluginDisposed = true;
  72077. if (request) {
  72078. request.abort();
  72079. request = null;
  72080. }
  72081. onDispose();
  72082. });
  72083. }
  72084. var manifestChecked = function () {
  72085. if (pluginDisposed) {
  72086. return;
  72087. }
  72088. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  72089. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  72090. } : undefined, database, useArrayBuffer, function (request, exception) {
  72091. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  72092. });
  72093. };
  72094. if (directLoad) {
  72095. dataCallback(directLoad);
  72096. return plugin;
  72097. }
  72098. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  72099. var engine = scene.getEngine();
  72100. var canUseOfflineSupport = engine.enableOfflineSupport;
  72101. if (canUseOfflineSupport) {
  72102. // Also check for exceptions
  72103. var exceptionFound = false;
  72104. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  72105. var regex = _a[_i];
  72106. if (regex.test(fileInfo.url)) {
  72107. exceptionFound = true;
  72108. break;
  72109. }
  72110. }
  72111. canUseOfflineSupport = !exceptionFound;
  72112. }
  72113. if (canUseOfflineSupport) {
  72114. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  72115. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  72116. }
  72117. else {
  72118. manifestChecked();
  72119. }
  72120. }
  72121. // Loading file from disk via input file or drag'n'drop
  72122. else {
  72123. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  72124. if (file) {
  72125. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  72126. }
  72127. else {
  72128. onError("Unable to find file named " + fileInfo.name);
  72129. }
  72130. }
  72131. return plugin;
  72132. };
  72133. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  72134. var url;
  72135. var name;
  72136. if (!sceneFilename) {
  72137. url = rootUrl;
  72138. name = BABYLON.Tools.GetFilename(rootUrl);
  72139. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  72140. }
  72141. else {
  72142. if (sceneFilename.substr(0, 1) === "/") {
  72143. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  72144. return null;
  72145. }
  72146. url = rootUrl + sceneFilename;
  72147. name = sceneFilename;
  72148. }
  72149. ;
  72150. return {
  72151. url: url,
  72152. rootUrl: rootUrl,
  72153. name: name
  72154. };
  72155. };
  72156. // Public functions
  72157. SceneLoader.GetPluginForExtension = function (extension) {
  72158. return SceneLoader._getPluginForExtension(extension).plugin;
  72159. };
  72160. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  72161. return !!SceneLoader._registeredPlugins[extension];
  72162. };
  72163. SceneLoader.RegisterPlugin = function (plugin) {
  72164. if (typeof plugin.extensions === "string") {
  72165. var extension = plugin.extensions;
  72166. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  72167. plugin: plugin,
  72168. isBinary: false
  72169. };
  72170. }
  72171. else {
  72172. var extensions = plugin.extensions;
  72173. Object.keys(extensions).forEach(function (extension) {
  72174. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  72175. plugin: plugin,
  72176. isBinary: extensions[extension].isBinary
  72177. };
  72178. });
  72179. }
  72180. };
  72181. /**
  72182. * Import meshes into a scene
  72183. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  72184. * @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)
  72185. * @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)
  72186. * @param scene the instance of BABYLON.Scene to append to
  72187. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  72188. * @param onProgress a callback with a progress event for each file being loaded
  72189. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72190. * @param pluginExtension the extension used to determine the plugin
  72191. * @returns The loaded plugin
  72192. */
  72193. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72194. if (sceneFilename === void 0) { sceneFilename = ""; }
  72195. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72196. if (onSuccess === void 0) { onSuccess = null; }
  72197. if (onProgress === void 0) { onProgress = null; }
  72198. if (onError === void 0) { onError = null; }
  72199. if (pluginExtension === void 0) { pluginExtension = null; }
  72200. if (!scene) {
  72201. BABYLON.Tools.Error("No scene available to import mesh to");
  72202. return null;
  72203. }
  72204. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72205. if (!fileInfo) {
  72206. return null;
  72207. }
  72208. var loadingToken = {};
  72209. scene._addPendingData(loadingToken);
  72210. var disposeHandler = function () {
  72211. scene._removePendingData(loadingToken);
  72212. };
  72213. var errorHandler = function (message, exception) {
  72214. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  72215. if (onError) {
  72216. onError(scene, errorMessage, exception);
  72217. }
  72218. else {
  72219. BABYLON.Tools.Error(errorMessage);
  72220. // should the exception be thrown?
  72221. }
  72222. disposeHandler();
  72223. };
  72224. var progressHandler = onProgress ? function (event) {
  72225. try {
  72226. onProgress(event);
  72227. }
  72228. catch (e) {
  72229. errorHandler("Error in onProgress callback", e);
  72230. }
  72231. } : undefined;
  72232. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  72233. scene.importedMeshesFiles.push(fileInfo.url);
  72234. if (onSuccess) {
  72235. try {
  72236. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  72237. }
  72238. catch (e) {
  72239. errorHandler("Error in onSuccess callback", e);
  72240. }
  72241. }
  72242. scene._removePendingData(loadingToken);
  72243. };
  72244. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72245. if (plugin.rewriteRootURL) {
  72246. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  72247. }
  72248. if (plugin.importMesh) {
  72249. var syncedPlugin = plugin;
  72250. var meshes = new Array();
  72251. var particleSystems = new Array();
  72252. var skeletons = new Array();
  72253. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  72254. return;
  72255. }
  72256. scene.loadingPluginName = plugin.name;
  72257. successHandler(meshes, particleSystems, skeletons, []);
  72258. }
  72259. else {
  72260. var asyncedPlugin = plugin;
  72261. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  72262. scene.loadingPluginName = plugin.name;
  72263. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  72264. }).catch(function (error) {
  72265. errorHandler(error.message, error);
  72266. });
  72267. }
  72268. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72269. };
  72270. /**
  72271. * Import meshes into a scene
  72272. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  72273. * @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)
  72274. * @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)
  72275. * @param scene the instance of BABYLON.Scene to append to
  72276. * @param onProgress a callback with a progress event for each file being loaded
  72277. * @param pluginExtension the extension used to determine the plugin
  72278. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  72279. */
  72280. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72281. if (sceneFilename === void 0) { sceneFilename = ""; }
  72282. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72283. if (onProgress === void 0) { onProgress = null; }
  72284. if (pluginExtension === void 0) { pluginExtension = null; }
  72285. return new Promise(function (resolve, reject) {
  72286. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  72287. resolve({
  72288. meshes: meshes,
  72289. particleSystems: particleSystems,
  72290. skeletons: skeletons,
  72291. animationGroups: animationGroups
  72292. });
  72293. }, onProgress, function (scene, message, exception) {
  72294. reject(exception || new Error(message));
  72295. }, pluginExtension);
  72296. });
  72297. };
  72298. /**
  72299. * Load a scene
  72300. * @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)
  72301. * @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)
  72302. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72303. * @param onSuccess a callback with the scene when import succeeds
  72304. * @param onProgress a callback with a progress event for each file being loaded
  72305. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72306. * @param pluginExtension the extension used to determine the plugin
  72307. * @returns The loaded plugin
  72308. */
  72309. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  72310. if (onSuccess === void 0) { onSuccess = null; }
  72311. if (onProgress === void 0) { onProgress = null; }
  72312. if (onError === void 0) { onError = null; }
  72313. if (pluginExtension === void 0) { pluginExtension = null; }
  72314. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  72315. };
  72316. /**
  72317. * Load a scene
  72318. * @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)
  72319. * @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)
  72320. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72321. * @param onProgress a callback with a progress event for each file being loaded
  72322. * @param pluginExtension the extension used to determine the plugin
  72323. * @returns The loaded scene
  72324. */
  72325. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  72326. if (onProgress === void 0) { onProgress = null; }
  72327. if (pluginExtension === void 0) { pluginExtension = null; }
  72328. return new Promise(function (resolve, reject) {
  72329. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  72330. resolve(scene);
  72331. }, onProgress, function (scene, message, exception) {
  72332. reject(exception || new Error(message));
  72333. }, pluginExtension);
  72334. });
  72335. };
  72336. /**
  72337. * Append a scene
  72338. * @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)
  72339. * @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)
  72340. * @param scene is the instance of BABYLON.Scene to append to
  72341. * @param onSuccess a callback with the scene when import succeeds
  72342. * @param onProgress a callback with a progress event for each file being loaded
  72343. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72344. * @param pluginExtension the extension used to determine the plugin
  72345. * @returns The loaded plugin
  72346. */
  72347. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72348. if (sceneFilename === void 0) { sceneFilename = ""; }
  72349. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72350. if (onSuccess === void 0) { onSuccess = null; }
  72351. if (onProgress === void 0) { onProgress = null; }
  72352. if (onError === void 0) { onError = null; }
  72353. if (pluginExtension === void 0) { pluginExtension = null; }
  72354. if (!scene) {
  72355. BABYLON.Tools.Error("No scene available to append to");
  72356. return null;
  72357. }
  72358. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72359. if (!fileInfo) {
  72360. return null;
  72361. }
  72362. if (SceneLoader.ShowLoadingScreen) {
  72363. scene.getEngine().displayLoadingUI();
  72364. }
  72365. var loadingToken = {};
  72366. scene._addPendingData(loadingToken);
  72367. var disposeHandler = function () {
  72368. scene._removePendingData(loadingToken);
  72369. scene.getEngine().hideLoadingUI();
  72370. };
  72371. var errorHandler = function (message, exception) {
  72372. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  72373. if (onError) {
  72374. onError(scene, errorMessage, exception);
  72375. }
  72376. else {
  72377. BABYLON.Tools.Error(errorMessage);
  72378. // should the exception be thrown?
  72379. }
  72380. disposeHandler();
  72381. };
  72382. var progressHandler = onProgress ? function (event) {
  72383. try {
  72384. onProgress(event);
  72385. }
  72386. catch (e) {
  72387. errorHandler("Error in onProgress callback", e);
  72388. }
  72389. } : undefined;
  72390. var successHandler = function () {
  72391. if (onSuccess) {
  72392. try {
  72393. onSuccess(scene);
  72394. }
  72395. catch (e) {
  72396. errorHandler("Error in onSuccess callback", e);
  72397. }
  72398. }
  72399. scene._removePendingData(loadingToken);
  72400. };
  72401. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72402. if (plugin.load) {
  72403. var syncedPlugin = plugin;
  72404. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  72405. return;
  72406. }
  72407. scene.loadingPluginName = plugin.name;
  72408. successHandler();
  72409. }
  72410. else {
  72411. var asyncedPlugin = plugin;
  72412. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  72413. scene.loadingPluginName = plugin.name;
  72414. successHandler();
  72415. }).catch(function (error) {
  72416. errorHandler(error.message, error);
  72417. });
  72418. }
  72419. if (SceneLoader.ShowLoadingScreen) {
  72420. scene.executeWhenReady(function () {
  72421. scene.getEngine().hideLoadingUI();
  72422. });
  72423. }
  72424. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72425. };
  72426. /**
  72427. * Append a scene
  72428. * @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)
  72429. * @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)
  72430. * @param scene is the instance of BABYLON.Scene to append to
  72431. * @param onProgress a callback with a progress event for each file being loaded
  72432. * @param pluginExtension the extension used to determine the plugin
  72433. * @returns The given scene
  72434. */
  72435. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72436. if (sceneFilename === void 0) { sceneFilename = ""; }
  72437. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72438. if (onProgress === void 0) { onProgress = null; }
  72439. if (pluginExtension === void 0) { pluginExtension = null; }
  72440. return new Promise(function (resolve, reject) {
  72441. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  72442. resolve(scene);
  72443. }, onProgress, function (scene, message, exception) {
  72444. reject(exception || new Error(message));
  72445. }, pluginExtension);
  72446. });
  72447. };
  72448. /**
  72449. * Load a scene into an asset container
  72450. * @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)
  72451. * @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)
  72452. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  72453. * @param onSuccess a callback with the scene when import succeeds
  72454. * @param onProgress a callback with a progress event for each file being loaded
  72455. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72456. * @param pluginExtension the extension used to determine the plugin
  72457. * @returns The loaded plugin
  72458. */
  72459. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72460. if (sceneFilename === void 0) { sceneFilename = ""; }
  72461. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72462. if (onSuccess === void 0) { onSuccess = null; }
  72463. if (onProgress === void 0) { onProgress = null; }
  72464. if (onError === void 0) { onError = null; }
  72465. if (pluginExtension === void 0) { pluginExtension = null; }
  72466. if (!scene) {
  72467. BABYLON.Tools.Error("No scene available to load asset container to");
  72468. return null;
  72469. }
  72470. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72471. if (!fileInfo) {
  72472. return null;
  72473. }
  72474. var loadingToken = {};
  72475. scene._addPendingData(loadingToken);
  72476. var disposeHandler = function () {
  72477. scene._removePendingData(loadingToken);
  72478. };
  72479. var errorHandler = function (message, exception) {
  72480. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  72481. if (onError) {
  72482. onError(scene, errorMessage, exception);
  72483. }
  72484. else {
  72485. BABYLON.Tools.Error(errorMessage);
  72486. // should the exception be thrown?
  72487. }
  72488. disposeHandler();
  72489. };
  72490. var progressHandler = onProgress ? function (event) {
  72491. try {
  72492. onProgress(event);
  72493. }
  72494. catch (e) {
  72495. errorHandler("Error in onProgress callback", e);
  72496. }
  72497. } : undefined;
  72498. var successHandler = function (assets) {
  72499. if (onSuccess) {
  72500. try {
  72501. onSuccess(assets);
  72502. }
  72503. catch (e) {
  72504. errorHandler("Error in onSuccess callback", e);
  72505. }
  72506. }
  72507. scene._removePendingData(loadingToken);
  72508. };
  72509. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72510. if (plugin.loadAssetContainer) {
  72511. var syncedPlugin = plugin;
  72512. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  72513. if (!assetContainer) {
  72514. return;
  72515. }
  72516. scene.loadingPluginName = plugin.name;
  72517. successHandler(assetContainer);
  72518. }
  72519. else if (plugin.loadAssetContainerAsync) {
  72520. var asyncedPlugin = plugin;
  72521. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  72522. scene.loadingPluginName = plugin.name;
  72523. successHandler(assetContainer);
  72524. }).catch(function (error) {
  72525. errorHandler(error.message, error);
  72526. });
  72527. }
  72528. else {
  72529. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  72530. }
  72531. if (SceneLoader.ShowLoadingScreen) {
  72532. scene.executeWhenReady(function () {
  72533. scene.getEngine().hideLoadingUI();
  72534. });
  72535. }
  72536. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72537. };
  72538. /**
  72539. * Load a scene into an asset container
  72540. * @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)
  72541. * @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)
  72542. * @param scene is the instance of BABYLON.Scene to append to
  72543. * @param onProgress a callback with a progress event for each file being loaded
  72544. * @param pluginExtension the extension used to determine the plugin
  72545. * @returns The loaded asset container
  72546. */
  72547. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72548. if (sceneFilename === void 0) { sceneFilename = ""; }
  72549. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72550. if (onProgress === void 0) { onProgress = null; }
  72551. if (pluginExtension === void 0) { pluginExtension = null; }
  72552. return new Promise(function (resolve, reject) {
  72553. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72554. resolve(assetContainer);
  72555. }, onProgress, function (scene, message, exception) {
  72556. reject(exception || new Error(message));
  72557. }, pluginExtension);
  72558. });
  72559. };
  72560. // Flags
  72561. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72562. SceneLoader._ShowLoadingScreen = true;
  72563. SceneLoader._CleanBoneMatrixWeights = false;
  72564. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72565. // Members
  72566. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72567. SceneLoader._registeredPlugins = {};
  72568. return SceneLoader;
  72569. }());
  72570. BABYLON.SceneLoader = SceneLoader;
  72571. ;
  72572. })(BABYLON || (BABYLON = {}));
  72573. //# sourceMappingURL=babylon.sceneLoader.js.map
  72574. var BABYLON;
  72575. (function (BABYLON) {
  72576. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72577. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72578. var parsedMaterial = parsedData.materials[index];
  72579. if (parsedMaterial.id === id) {
  72580. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72581. }
  72582. }
  72583. return null;
  72584. };
  72585. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72586. for (var i in names) {
  72587. if (mesh.name === names[i]) {
  72588. hierarchyIds.push(mesh.id);
  72589. return true;
  72590. }
  72591. }
  72592. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72593. hierarchyIds.push(mesh.id);
  72594. return true;
  72595. }
  72596. return false;
  72597. };
  72598. var logOperation = function (operation, producer) {
  72599. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72600. };
  72601. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72602. if (addToScene === void 0) { addToScene = false; }
  72603. var container = new BABYLON.AssetContainer(scene);
  72604. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72605. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72606. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72607. // and avoid problems with multiple concurrent .babylon loads.
  72608. var log = "importScene has failed JSON parse";
  72609. try {
  72610. var parsedData = JSON.parse(data);
  72611. log = "";
  72612. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72613. var index;
  72614. var cache;
  72615. // Lights
  72616. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72617. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72618. var parsedLight = parsedData.lights[index];
  72619. var light = BABYLON.Light.Parse(parsedLight, scene);
  72620. if (light) {
  72621. container.lights.push(light);
  72622. log += (index === 0 ? "\n\tLights:" : "");
  72623. log += "\n\t\t" + light.toString(fullDetails);
  72624. }
  72625. }
  72626. }
  72627. // Animations
  72628. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72629. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72630. var parsedAnimation = parsedData.animations[index];
  72631. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72632. scene.animations.push(animation);
  72633. container.animations.push(animation);
  72634. log += (index === 0 ? "\n\tAnimations:" : "");
  72635. log += "\n\t\t" + animation.toString(fullDetails);
  72636. }
  72637. }
  72638. // Materials
  72639. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72640. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72641. var parsedMaterial = parsedData.materials[index];
  72642. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72643. container.materials.push(mat);
  72644. log += (index === 0 ? "\n\tMaterials:" : "");
  72645. log += "\n\t\t" + mat.toString(fullDetails);
  72646. }
  72647. }
  72648. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72649. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72650. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72651. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72652. container.multiMaterials.push(mmat);
  72653. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72654. log += "\n\t\t" + mmat.toString(fullDetails);
  72655. }
  72656. }
  72657. // Morph targets
  72658. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72659. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72660. var managerData = _a[_i];
  72661. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72662. }
  72663. }
  72664. // Skeletons
  72665. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72666. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72667. var parsedSkeleton = parsedData.skeletons[index];
  72668. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72669. container.skeletons.push(skeleton);
  72670. log += (index === 0 ? "\n\tSkeletons:" : "");
  72671. log += "\n\t\t" + skeleton.toString(fullDetails);
  72672. }
  72673. }
  72674. // Geometries
  72675. var geometries = parsedData.geometries;
  72676. if (geometries !== undefined && geometries !== null) {
  72677. var addedGeometry = new Array();
  72678. // Boxes
  72679. var boxes = geometries.boxes;
  72680. if (boxes !== undefined && boxes !== null) {
  72681. for (index = 0, cache = boxes.length; index < cache; index++) {
  72682. var parsedBox = boxes[index];
  72683. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72684. }
  72685. }
  72686. // Spheres
  72687. var spheres = geometries.spheres;
  72688. if (spheres !== undefined && spheres !== null) {
  72689. for (index = 0, cache = spheres.length; index < cache; index++) {
  72690. var parsedSphere = spheres[index];
  72691. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72692. }
  72693. }
  72694. // Cylinders
  72695. var cylinders = geometries.cylinders;
  72696. if (cylinders !== undefined && cylinders !== null) {
  72697. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72698. var parsedCylinder = cylinders[index];
  72699. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72700. }
  72701. }
  72702. // Toruses
  72703. var toruses = geometries.toruses;
  72704. if (toruses !== undefined && toruses !== null) {
  72705. for (index = 0, cache = toruses.length; index < cache; index++) {
  72706. var parsedTorus = toruses[index];
  72707. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72708. }
  72709. }
  72710. // Grounds
  72711. var grounds = geometries.grounds;
  72712. if (grounds !== undefined && grounds !== null) {
  72713. for (index = 0, cache = grounds.length; index < cache; index++) {
  72714. var parsedGround = grounds[index];
  72715. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72716. }
  72717. }
  72718. // Planes
  72719. var planes = geometries.planes;
  72720. if (planes !== undefined && planes !== null) {
  72721. for (index = 0, cache = planes.length; index < cache; index++) {
  72722. var parsedPlane = planes[index];
  72723. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72724. }
  72725. }
  72726. // TorusKnots
  72727. var torusKnots = geometries.torusKnots;
  72728. if (torusKnots !== undefined && torusKnots !== null) {
  72729. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72730. var parsedTorusKnot = torusKnots[index];
  72731. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72732. }
  72733. }
  72734. // VertexData
  72735. var vertexData = geometries.vertexData;
  72736. if (vertexData !== undefined && vertexData !== null) {
  72737. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72738. var parsedVertexData = vertexData[index];
  72739. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72740. }
  72741. }
  72742. addedGeometry.forEach(function (g) {
  72743. if (g) {
  72744. container.geometries.push(g);
  72745. }
  72746. });
  72747. }
  72748. // Transform nodes
  72749. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72750. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72751. var parsedTransformNode = parsedData.transformNodes[index];
  72752. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72753. container.transformNodes.push(node);
  72754. }
  72755. }
  72756. // Meshes
  72757. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72758. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72759. var parsedMesh = parsedData.meshes[index];
  72760. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72761. container.meshes.push(mesh);
  72762. log += (index === 0 ? "\n\tMeshes:" : "");
  72763. log += "\n\t\t" + mesh.toString(fullDetails);
  72764. }
  72765. }
  72766. // Cameras
  72767. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72768. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72769. var parsedCamera = parsedData.cameras[index];
  72770. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72771. container.cameras.push(camera);
  72772. log += (index === 0 ? "\n\tCameras:" : "");
  72773. log += "\n\t\t" + camera.toString(fullDetails);
  72774. }
  72775. }
  72776. // Animation Groups
  72777. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72778. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72779. var parsedAnimationGroup = parsedData.animationGroups[index];
  72780. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72781. container.animationGroups.push(animationGroup);
  72782. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72783. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72784. }
  72785. }
  72786. // Browsing all the graph to connect the dots
  72787. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72788. var camera = scene.cameras[index];
  72789. if (camera._waitingParentId) {
  72790. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72791. camera._waitingParentId = null;
  72792. }
  72793. }
  72794. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72795. var light_1 = scene.lights[index];
  72796. if (light_1 && light_1._waitingParentId) {
  72797. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72798. light_1._waitingParentId = null;
  72799. }
  72800. }
  72801. // Connect parents & children and parse actions
  72802. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72803. var transformNode = scene.transformNodes[index];
  72804. if (transformNode._waitingParentId) {
  72805. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72806. transformNode._waitingParentId = null;
  72807. }
  72808. }
  72809. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72810. var mesh = scene.meshes[index];
  72811. if (mesh._waitingParentId) {
  72812. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72813. mesh._waitingParentId = null;
  72814. }
  72815. if (mesh._waitingActions) {
  72816. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72817. mesh._waitingActions = null;
  72818. }
  72819. }
  72820. // freeze world matrix application
  72821. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72822. var currentMesh = scene.meshes[index];
  72823. if (currentMesh._waitingFreezeWorldMatrix) {
  72824. currentMesh.freezeWorldMatrix();
  72825. currentMesh._waitingFreezeWorldMatrix = null;
  72826. }
  72827. else {
  72828. currentMesh.computeWorldMatrix(true);
  72829. }
  72830. }
  72831. // Lights exclusions / inclusions
  72832. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72833. var light_2 = scene.lights[index];
  72834. // Excluded check
  72835. if (light_2._excludedMeshesIds.length > 0) {
  72836. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72837. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72838. if (excludedMesh) {
  72839. light_2.excludedMeshes.push(excludedMesh);
  72840. }
  72841. }
  72842. light_2._excludedMeshesIds = [];
  72843. }
  72844. // Included check
  72845. if (light_2._includedOnlyMeshesIds.length > 0) {
  72846. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72847. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72848. if (includedOnlyMesh) {
  72849. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72850. }
  72851. }
  72852. light_2._includedOnlyMeshesIds = [];
  72853. }
  72854. }
  72855. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72856. // Actions (scene)
  72857. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72858. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72859. }
  72860. if (!addToScene) {
  72861. container.removeAllFromScene();
  72862. }
  72863. }
  72864. catch (err) {
  72865. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72866. if (onError) {
  72867. onError(msg, err);
  72868. }
  72869. else {
  72870. BABYLON.Tools.Log(msg);
  72871. throw err;
  72872. }
  72873. }
  72874. finally {
  72875. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72876. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72877. }
  72878. }
  72879. return container;
  72880. };
  72881. BABYLON.SceneLoader.RegisterPlugin({
  72882. name: "babylon.js",
  72883. extensions: ".babylon",
  72884. canDirectLoad: function (data) {
  72885. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72886. return true;
  72887. }
  72888. return false;
  72889. },
  72890. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72891. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72892. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72893. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72894. // and avoid problems with multiple concurrent .babylon loads.
  72895. var log = "importMesh has failed JSON parse";
  72896. try {
  72897. var parsedData = JSON.parse(data);
  72898. log = "";
  72899. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72900. if (!meshesNames) {
  72901. meshesNames = null;
  72902. }
  72903. else if (!Array.isArray(meshesNames)) {
  72904. meshesNames = [meshesNames];
  72905. }
  72906. var hierarchyIds = new Array();
  72907. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72908. var loadedSkeletonsIds = [];
  72909. var loadedMaterialsIds = [];
  72910. var index;
  72911. var cache;
  72912. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72913. var parsedMesh = parsedData.meshes[index];
  72914. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72915. if (meshesNames !== null) {
  72916. // Remove found mesh name from list.
  72917. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72918. }
  72919. //Geometry?
  72920. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72921. //does the file contain geometries?
  72922. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72923. //find the correct geometry and add it to the scene
  72924. var found = false;
  72925. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72926. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72927. return;
  72928. }
  72929. else {
  72930. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72931. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72932. switch (geometryType) {
  72933. case "boxes":
  72934. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72935. break;
  72936. case "spheres":
  72937. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72938. break;
  72939. case "cylinders":
  72940. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72941. break;
  72942. case "toruses":
  72943. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72944. break;
  72945. case "grounds":
  72946. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72947. break;
  72948. case "planes":
  72949. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72950. break;
  72951. case "torusKnots":
  72952. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72953. break;
  72954. case "vertexData":
  72955. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72956. break;
  72957. }
  72958. found = true;
  72959. }
  72960. });
  72961. }
  72962. });
  72963. if (found === false) {
  72964. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72965. }
  72966. }
  72967. }
  72968. // Material ?
  72969. if (parsedMesh.materialId) {
  72970. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72971. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72972. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72973. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72974. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72975. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72976. var subMatId = parsedMultiMaterial.materials[matIndex];
  72977. loadedMaterialsIds.push(subMatId);
  72978. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72979. if (mat) {
  72980. log += "\n\tMaterial " + mat.toString(fullDetails);
  72981. }
  72982. }
  72983. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72984. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72985. if (mmat) {
  72986. materialFound = true;
  72987. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72988. }
  72989. break;
  72990. }
  72991. }
  72992. }
  72993. if (materialFound === false) {
  72994. loadedMaterialsIds.push(parsedMesh.materialId);
  72995. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72996. if (!mat) {
  72997. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72998. }
  72999. else {
  73000. log += "\n\tMaterial " + mat.toString(fullDetails);
  73001. }
  73002. }
  73003. }
  73004. // Skeleton ?
  73005. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  73006. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  73007. if (skeletonAlreadyLoaded === false) {
  73008. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  73009. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  73010. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  73011. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  73012. skeletons.push(skeleton);
  73013. loadedSkeletonsIds.push(parsedSkeleton.id);
  73014. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  73015. }
  73016. }
  73017. }
  73018. }
  73019. // Morph targets ?
  73020. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  73021. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  73022. var managerData = _a[_i];
  73023. BABYLON.MorphTargetManager.Parse(managerData, scene);
  73024. }
  73025. }
  73026. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  73027. meshes.push(mesh);
  73028. log += "\n\tMesh " + mesh.toString(fullDetails);
  73029. }
  73030. }
  73031. // Connecting parents
  73032. var currentMesh;
  73033. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73034. currentMesh = scene.meshes[index];
  73035. if (currentMesh._waitingParentId) {
  73036. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  73037. currentMesh._waitingParentId = null;
  73038. }
  73039. }
  73040. // freeze and compute world matrix application
  73041. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73042. currentMesh = scene.meshes[index];
  73043. if (currentMesh._waitingFreezeWorldMatrix) {
  73044. currentMesh.freezeWorldMatrix();
  73045. currentMesh._waitingFreezeWorldMatrix = null;
  73046. }
  73047. else {
  73048. currentMesh.computeWorldMatrix(true);
  73049. }
  73050. }
  73051. }
  73052. // Particles
  73053. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  73054. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  73055. if (parser) {
  73056. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  73057. var parsedParticleSystem = parsedData.particleSystems[index];
  73058. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  73059. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  73060. }
  73061. }
  73062. }
  73063. }
  73064. return true;
  73065. }
  73066. catch (err) {
  73067. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  73068. if (onError) {
  73069. onError(msg, err);
  73070. }
  73071. else {
  73072. BABYLON.Tools.Log(msg);
  73073. throw err;
  73074. }
  73075. }
  73076. finally {
  73077. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  73078. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  73079. }
  73080. }
  73081. return false;
  73082. },
  73083. load: function (scene, data, rootUrl, onError) {
  73084. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  73085. // when SceneLoader.debugLogging = true (default), or exception encountered.
  73086. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  73087. // and avoid problems with multiple concurrent .babylon loads.
  73088. var log = "importScene has failed JSON parse";
  73089. try {
  73090. var parsedData = JSON.parse(data);
  73091. log = "";
  73092. // Scene
  73093. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  73094. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  73095. }
  73096. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  73097. scene.autoClear = parsedData.autoClear;
  73098. }
  73099. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  73100. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  73101. }
  73102. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  73103. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  73104. }
  73105. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  73106. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  73107. }
  73108. // Fog
  73109. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  73110. scene.fogMode = parsedData.fogMode;
  73111. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  73112. scene.fogStart = parsedData.fogStart;
  73113. scene.fogEnd = parsedData.fogEnd;
  73114. scene.fogDensity = parsedData.fogDensity;
  73115. log += "\tFog mode for scene: ";
  73116. switch (scene.fogMode) {
  73117. // getters not compiling, so using hardcoded
  73118. case 1:
  73119. log += "exp\n";
  73120. break;
  73121. case 2:
  73122. log += "exp2\n";
  73123. break;
  73124. case 3:
  73125. log += "linear\n";
  73126. break;
  73127. }
  73128. }
  73129. //Physics
  73130. if (parsedData.physicsEnabled) {
  73131. var physicsPlugin;
  73132. if (parsedData.physicsEngine === "cannon") {
  73133. physicsPlugin = new BABYLON.CannonJSPlugin();
  73134. }
  73135. else if (parsedData.physicsEngine === "oimo") {
  73136. physicsPlugin = new BABYLON.OimoJSPlugin();
  73137. }
  73138. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  73139. //else - default engine, which is currently oimo
  73140. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  73141. scene.enablePhysics(physicsGravity, physicsPlugin);
  73142. }
  73143. // Metadata
  73144. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  73145. scene.metadata = parsedData.metadata;
  73146. }
  73147. //collisions, if defined. otherwise, default is true
  73148. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  73149. scene.collisionsEnabled = parsedData.collisionsEnabled;
  73150. }
  73151. scene.workerCollisions = !!parsedData.workerCollisions;
  73152. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  73153. if (!container) {
  73154. return false;
  73155. }
  73156. if (parsedData.autoAnimate) {
  73157. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  73158. }
  73159. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  73160. scene.setActiveCameraByID(parsedData.activeCameraID);
  73161. }
  73162. // Environment texture
  73163. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  73164. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  73165. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  73166. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  73167. if (parsedData.environmentTextureRotationY) {
  73168. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  73169. }
  73170. scene.environmentTexture = hdrTexture;
  73171. }
  73172. else {
  73173. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  73174. if (parsedData.environmentTextureRotationY) {
  73175. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  73176. }
  73177. scene.environmentTexture = cubeTexture;
  73178. }
  73179. if (parsedData.createDefaultSkybox === true) {
  73180. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  73181. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  73182. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  73183. }
  73184. }
  73185. // Finish
  73186. return true;
  73187. }
  73188. catch (err) {
  73189. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  73190. if (onError) {
  73191. onError(msg, err);
  73192. }
  73193. else {
  73194. BABYLON.Tools.Log(msg);
  73195. throw err;
  73196. }
  73197. }
  73198. finally {
  73199. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  73200. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  73201. }
  73202. }
  73203. return false;
  73204. },
  73205. loadAssetContainer: function (scene, data, rootUrl, onError) {
  73206. var container = loadAssetContainer(scene, data, rootUrl, onError);
  73207. return container;
  73208. }
  73209. });
  73210. })(BABYLON || (BABYLON = {}));
  73211. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  73212. var BABYLON;
  73213. (function (BABYLON) {
  73214. var FilesInput = /** @class */ (function () {
  73215. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  73216. this.onProcessFileCallback = function () { return true; };
  73217. this._engine = engine;
  73218. this._currentScene = scene;
  73219. this._sceneLoadedCallback = sceneLoadedCallback;
  73220. this._progressCallback = progressCallback;
  73221. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  73222. this._textureLoadingCallback = textureLoadingCallback;
  73223. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  73224. this._onReloadCallback = onReloadCallback;
  73225. this._errorCallback = errorCallback;
  73226. }
  73227. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  73228. var _this = this;
  73229. if (elementToMonitor) {
  73230. this._elementToMonitor = elementToMonitor;
  73231. this._dragEnterHandler = function (e) { _this.drag(e); };
  73232. this._dragOverHandler = function (e) { _this.drag(e); };
  73233. this._dropHandler = function (e) { _this.drop(e); };
  73234. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  73235. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  73236. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  73237. }
  73238. };
  73239. FilesInput.prototype.dispose = function () {
  73240. if (!this._elementToMonitor) {
  73241. return;
  73242. }
  73243. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  73244. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  73245. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  73246. };
  73247. FilesInput.prototype.renderFunction = function () {
  73248. if (this._additionalRenderLoopLogicCallback) {
  73249. this._additionalRenderLoopLogicCallback();
  73250. }
  73251. if (this._currentScene) {
  73252. if (this._textureLoadingCallback) {
  73253. var remaining = this._currentScene.getWaitingItemsCount();
  73254. if (remaining > 0) {
  73255. this._textureLoadingCallback(remaining);
  73256. }
  73257. }
  73258. this._currentScene.render();
  73259. }
  73260. };
  73261. FilesInput.prototype.drag = function (e) {
  73262. e.stopPropagation();
  73263. e.preventDefault();
  73264. };
  73265. FilesInput.prototype.drop = function (eventDrop) {
  73266. eventDrop.stopPropagation();
  73267. eventDrop.preventDefault();
  73268. this.loadFiles(eventDrop);
  73269. };
  73270. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  73271. var _this = this;
  73272. var reader = folder.createReader();
  73273. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  73274. reader.readEntries(function (entries) {
  73275. remaining.count += entries.length;
  73276. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  73277. var entry = entries_1[_i];
  73278. if (entry.isFile) {
  73279. entry.file(function (file) {
  73280. file.correctName = relativePath + file.name;
  73281. files.push(file);
  73282. if (--remaining.count === 0) {
  73283. callback();
  73284. }
  73285. });
  73286. }
  73287. else if (entry.isDirectory) {
  73288. _this._traverseFolder(entry, files, remaining, callback);
  73289. }
  73290. }
  73291. if (--remaining.count) {
  73292. callback();
  73293. }
  73294. });
  73295. };
  73296. FilesInput.prototype._processFiles = function (files) {
  73297. for (var i = 0; i < files.length; i++) {
  73298. var name = files[i].correctName.toLowerCase();
  73299. var extension = name.split('.').pop();
  73300. if (!this.onProcessFileCallback(files[i], name, extension)) {
  73301. continue;
  73302. }
  73303. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  73304. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  73305. this._sceneFileToLoad = files[i];
  73306. }
  73307. FilesInput.FilesToLoad[name] = files[i];
  73308. }
  73309. };
  73310. FilesInput.prototype.loadFiles = function (event) {
  73311. var _this = this;
  73312. // Handling data transfer via drag'n'drop
  73313. if (event && event.dataTransfer && event.dataTransfer.files) {
  73314. this._filesToLoad = event.dataTransfer.files;
  73315. }
  73316. // Handling files from input files
  73317. if (event && event.target && event.target.files) {
  73318. this._filesToLoad = event.target.files;
  73319. }
  73320. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  73321. return;
  73322. }
  73323. if (this._startingProcessingFilesCallback) {
  73324. this._startingProcessingFilesCallback(this._filesToLoad);
  73325. }
  73326. if (this._filesToLoad && this._filesToLoad.length > 0) {
  73327. var files_1 = new Array();
  73328. var folders = [];
  73329. var items = event.dataTransfer ? event.dataTransfer.items : null;
  73330. for (var i = 0; i < this._filesToLoad.length; i++) {
  73331. var fileToLoad = this._filesToLoad[i];
  73332. var name_1 = fileToLoad.name.toLowerCase();
  73333. var entry = void 0;
  73334. fileToLoad.correctName = name_1;
  73335. if (items) {
  73336. var item = items[i];
  73337. if (item.getAsEntry) {
  73338. entry = item.getAsEntry();
  73339. }
  73340. else if (item.webkitGetAsEntry) {
  73341. entry = item.webkitGetAsEntry();
  73342. }
  73343. }
  73344. if (!entry) {
  73345. files_1.push(fileToLoad);
  73346. }
  73347. else {
  73348. if (entry.isDirectory) {
  73349. folders.push(entry);
  73350. }
  73351. else {
  73352. files_1.push(fileToLoad);
  73353. }
  73354. }
  73355. }
  73356. if (folders.length === 0) {
  73357. this._processFiles(files_1);
  73358. this._processReload();
  73359. }
  73360. else {
  73361. var remaining = { count: folders.length };
  73362. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  73363. var folder = folders_1[_i];
  73364. this._traverseFolder(folder, files_1, remaining, function () {
  73365. _this._processFiles(files_1);
  73366. if (remaining.count === 0) {
  73367. _this._processReload();
  73368. }
  73369. });
  73370. }
  73371. }
  73372. }
  73373. };
  73374. FilesInput.prototype._processReload = function () {
  73375. if (this._onReloadCallback) {
  73376. this._onReloadCallback(this._sceneFileToLoad);
  73377. }
  73378. else {
  73379. this.reload();
  73380. }
  73381. };
  73382. FilesInput.prototype.reload = function () {
  73383. var _this = this;
  73384. // If a scene file has been provided
  73385. if (this._sceneFileToLoad) {
  73386. if (this._currentScene) {
  73387. if (BABYLON.Tools.errorsCount > 0) {
  73388. BABYLON.Tools.ClearLogCache();
  73389. }
  73390. this._engine.stopRenderLoop();
  73391. }
  73392. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  73393. if (_this._progressCallback) {
  73394. _this._progressCallback(progress);
  73395. }
  73396. }).then(function (scene) {
  73397. if (_this._currentScene) {
  73398. _this._currentScene.dispose();
  73399. }
  73400. _this._currentScene = scene;
  73401. if (_this._sceneLoadedCallback) {
  73402. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  73403. }
  73404. // Wait for textures and shaders to be ready
  73405. _this._currentScene.executeWhenReady(function () {
  73406. _this._engine.runRenderLoop(function () {
  73407. _this.renderFunction();
  73408. });
  73409. });
  73410. }).catch(function (error) {
  73411. if (_this._errorCallback) {
  73412. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  73413. }
  73414. });
  73415. }
  73416. else {
  73417. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  73418. }
  73419. };
  73420. FilesInput.FilesToLoad = {};
  73421. return FilesInput;
  73422. }());
  73423. BABYLON.FilesInput = FilesInput;
  73424. })(BABYLON || (BABYLON = {}));
  73425. //# sourceMappingURL=babylon.filesInput.js.map
  73426. var BABYLON;
  73427. (function (BABYLON) {
  73428. var Tags = /** @class */ (function () {
  73429. function Tags() {
  73430. }
  73431. Tags.EnableFor = function (obj) {
  73432. obj._tags = obj._tags || {};
  73433. obj.hasTags = function () {
  73434. return Tags.HasTags(obj);
  73435. };
  73436. obj.addTags = function (tagsString) {
  73437. return Tags.AddTagsTo(obj, tagsString);
  73438. };
  73439. obj.removeTags = function (tagsString) {
  73440. return Tags.RemoveTagsFrom(obj, tagsString);
  73441. };
  73442. obj.matchesTagsQuery = function (tagsQuery) {
  73443. return Tags.MatchesQuery(obj, tagsQuery);
  73444. };
  73445. };
  73446. Tags.DisableFor = function (obj) {
  73447. delete obj._tags;
  73448. delete obj.hasTags;
  73449. delete obj.addTags;
  73450. delete obj.removeTags;
  73451. delete obj.matchesTagsQuery;
  73452. };
  73453. Tags.HasTags = function (obj) {
  73454. if (!obj._tags) {
  73455. return false;
  73456. }
  73457. return !BABYLON.Tools.IsEmpty(obj._tags);
  73458. };
  73459. Tags.GetTags = function (obj, asString) {
  73460. if (asString === void 0) { asString = true; }
  73461. if (!obj._tags) {
  73462. return null;
  73463. }
  73464. if (asString) {
  73465. var tagsArray = [];
  73466. for (var tag in obj._tags) {
  73467. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  73468. tagsArray.push(tag);
  73469. }
  73470. }
  73471. return tagsArray.join(" ");
  73472. }
  73473. else {
  73474. return obj._tags;
  73475. }
  73476. };
  73477. // the tags 'true' and 'false' are reserved and cannot be used as tags
  73478. // a tag cannot start with '||', '&&', and '!'
  73479. // it cannot contain whitespaces
  73480. Tags.AddTagsTo = function (obj, tagsString) {
  73481. if (!tagsString) {
  73482. return;
  73483. }
  73484. if (typeof tagsString !== "string") {
  73485. return;
  73486. }
  73487. var tags = tagsString.split(" ");
  73488. tags.forEach(function (tag, index, array) {
  73489. Tags._AddTagTo(obj, tag);
  73490. });
  73491. };
  73492. Tags._AddTagTo = function (obj, tag) {
  73493. tag = tag.trim();
  73494. if (tag === "" || tag === "true" || tag === "false") {
  73495. return;
  73496. }
  73497. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  73498. return;
  73499. }
  73500. Tags.EnableFor(obj);
  73501. obj._tags[tag] = true;
  73502. };
  73503. Tags.RemoveTagsFrom = function (obj, tagsString) {
  73504. if (!Tags.HasTags(obj)) {
  73505. return;
  73506. }
  73507. var tags = tagsString.split(" ");
  73508. for (var t in tags) {
  73509. Tags._RemoveTagFrom(obj, tags[t]);
  73510. }
  73511. };
  73512. Tags._RemoveTagFrom = function (obj, tag) {
  73513. delete obj._tags[tag];
  73514. };
  73515. Tags.MatchesQuery = function (obj, tagsQuery) {
  73516. if (tagsQuery === undefined) {
  73517. return true;
  73518. }
  73519. if (tagsQuery === "") {
  73520. return Tags.HasTags(obj);
  73521. }
  73522. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73523. };
  73524. return Tags;
  73525. }());
  73526. BABYLON.Tags = Tags;
  73527. })(BABYLON || (BABYLON = {}));
  73528. //# sourceMappingURL=babylon.tags.js.map
  73529. var BABYLON;
  73530. (function (BABYLON) {
  73531. /**
  73532. * Class used to evalaute queries containing `and` and `or` operators
  73533. */
  73534. var AndOrNotEvaluator = /** @class */ (function () {
  73535. function AndOrNotEvaluator() {
  73536. }
  73537. /**
  73538. * Evaluate a query
  73539. * @param query defines the query to evaluate
  73540. * @param evaluateCallback defines the callback used to filter result
  73541. * @returns true if the query matches
  73542. */
  73543. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73544. if (!query.match(/\([^\(\)]*\)/g)) {
  73545. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73546. }
  73547. else {
  73548. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73549. // remove parenthesis
  73550. r = r.slice(1, r.length - 1);
  73551. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73552. });
  73553. }
  73554. if (query === "true") {
  73555. return true;
  73556. }
  73557. if (query === "false") {
  73558. return false;
  73559. }
  73560. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73561. };
  73562. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73563. evaluateCallback = evaluateCallback || (function (r) {
  73564. return r === "true" ? true : false;
  73565. });
  73566. var result;
  73567. var or = parenthesisContent.split("||");
  73568. for (var i in or) {
  73569. if (or.hasOwnProperty(i)) {
  73570. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73571. var and = ori.split("&&");
  73572. if (and.length > 1) {
  73573. for (var j = 0; j < and.length; ++j) {
  73574. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73575. if (andj !== "true" && andj !== "false") {
  73576. if (andj[0] === "!") {
  73577. result = !evaluateCallback(andj.substring(1));
  73578. }
  73579. else {
  73580. result = evaluateCallback(andj);
  73581. }
  73582. }
  73583. else {
  73584. result = andj === "true" ? true : false;
  73585. }
  73586. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73587. ori = "false";
  73588. break;
  73589. }
  73590. }
  73591. }
  73592. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73593. result = true;
  73594. break;
  73595. }
  73596. // result equals false (or undefined)
  73597. if (ori !== "true" && ori !== "false") {
  73598. if (ori[0] === "!") {
  73599. result = !evaluateCallback(ori.substring(1));
  73600. }
  73601. else {
  73602. result = evaluateCallback(ori);
  73603. }
  73604. }
  73605. else {
  73606. result = ori === "true" ? true : false;
  73607. }
  73608. }
  73609. }
  73610. // the whole parenthesis scope is replaced by 'true' or 'false'
  73611. return result ? "true" : "false";
  73612. };
  73613. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73614. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73615. // remove whitespaces
  73616. r = r.replace(/[\s]/g, function () { return ""; });
  73617. return r.length % 2 ? "!" : "";
  73618. });
  73619. booleanString = booleanString.trim();
  73620. if (booleanString === "!true") {
  73621. booleanString = "false";
  73622. }
  73623. else if (booleanString === "!false") {
  73624. booleanString = "true";
  73625. }
  73626. return booleanString;
  73627. };
  73628. return AndOrNotEvaluator;
  73629. }());
  73630. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73631. })(BABYLON || (BABYLON = {}));
  73632. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73633. var BABYLON;
  73634. (function (BABYLON) {
  73635. /**
  73636. * Class used to enable access to IndexedDB
  73637. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73638. */
  73639. var Database = /** @class */ (function () {
  73640. /**
  73641. * Creates a new Database
  73642. * @param urlToScene defines the url to load the scene
  73643. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73644. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73645. */
  73646. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73647. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73648. var _this = this;
  73649. // Handling various flavors of prefixed version of IndexedDB
  73650. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73651. this.callbackManifestChecked = callbackManifestChecked;
  73652. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73653. this.db = null;
  73654. this._enableSceneOffline = false;
  73655. this._enableTexturesOffline = false;
  73656. this.manifestVersionFound = 0;
  73657. this.mustUpdateRessources = false;
  73658. this.hasReachedQuota = false;
  73659. if (!Database.IDBStorageEnabled) {
  73660. this.callbackManifestChecked(true);
  73661. }
  73662. else {
  73663. if (disableManifestCheck) {
  73664. this._enableSceneOffline = true;
  73665. this._enableTexturesOffline = true;
  73666. this.manifestVersionFound = 1;
  73667. BABYLON.Tools.SetImmediate(function () {
  73668. _this.callbackManifestChecked(true);
  73669. });
  73670. }
  73671. else {
  73672. this._checkManifestFile();
  73673. }
  73674. }
  73675. }
  73676. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73677. /**
  73678. * Gets a boolean indicating if scene must be saved in the database
  73679. */
  73680. get: function () {
  73681. return this._enableSceneOffline;
  73682. },
  73683. enumerable: true,
  73684. configurable: true
  73685. });
  73686. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73687. /**
  73688. * Gets a boolean indicating if textures must be saved in the database
  73689. */
  73690. get: function () {
  73691. return this._enableTexturesOffline;
  73692. },
  73693. enumerable: true,
  73694. configurable: true
  73695. });
  73696. Database.prototype._checkManifestFile = function () {
  73697. var _this = this;
  73698. var noManifestFile = function () {
  73699. _this._enableSceneOffline = false;
  73700. _this._enableTexturesOffline = false;
  73701. _this.callbackManifestChecked(false);
  73702. };
  73703. var timeStampUsed = false;
  73704. var manifestURL = this.currentSceneUrl + ".manifest";
  73705. var xhr = new XMLHttpRequest();
  73706. if (navigator.onLine) {
  73707. // Adding a timestamp to by-pass browsers' cache
  73708. timeStampUsed = true;
  73709. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73710. }
  73711. xhr.open("GET", manifestURL, true);
  73712. xhr.addEventListener("load", function () {
  73713. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73714. try {
  73715. var manifestFile = JSON.parse(xhr.response);
  73716. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73717. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73718. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73719. _this.manifestVersionFound = manifestFile.version;
  73720. }
  73721. if (_this.callbackManifestChecked) {
  73722. _this.callbackManifestChecked(true);
  73723. }
  73724. }
  73725. catch (ex) {
  73726. noManifestFile();
  73727. }
  73728. }
  73729. else {
  73730. noManifestFile();
  73731. }
  73732. }, false);
  73733. xhr.addEventListener("error", function (event) {
  73734. if (timeStampUsed) {
  73735. timeStampUsed = false;
  73736. // Let's retry without the timeStamp
  73737. // It could fail when coupled with HTML5 Offline API
  73738. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73739. xhr.open("GET", retryManifestURL, true);
  73740. xhr.send();
  73741. }
  73742. else {
  73743. noManifestFile();
  73744. }
  73745. }, false);
  73746. try {
  73747. xhr.send();
  73748. }
  73749. catch (ex) {
  73750. BABYLON.Tools.Error("Error on XHR send request.");
  73751. this.callbackManifestChecked(false);
  73752. }
  73753. };
  73754. /**
  73755. * Open the database and make it available
  73756. * @param successCallback defines the callback to call on success
  73757. * @param errorCallback defines the callback to call on error
  73758. */
  73759. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73760. var _this = this;
  73761. var handleError = function () {
  73762. _this.isSupported = false;
  73763. if (errorCallback)
  73764. errorCallback();
  73765. };
  73766. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73767. // Your browser doesn't support IndexedDB
  73768. this.isSupported = false;
  73769. if (errorCallback)
  73770. errorCallback();
  73771. }
  73772. else {
  73773. // If the DB hasn't been opened or created yet
  73774. if (!this.db) {
  73775. this.hasReachedQuota = false;
  73776. this.isSupported = true;
  73777. var request = this.idbFactory.open("babylonjs", 1);
  73778. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73779. request.onerror = function (event) {
  73780. handleError();
  73781. };
  73782. // executes when a version change transaction cannot complete due to other active transactions
  73783. request.onblocked = function (event) {
  73784. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73785. handleError();
  73786. };
  73787. // DB has been opened successfully
  73788. request.onsuccess = function (event) {
  73789. _this.db = request.result;
  73790. successCallback();
  73791. };
  73792. // Initialization of the DB. Creating Scenes & Textures stores
  73793. request.onupgradeneeded = function (event) {
  73794. _this.db = (event.target).result;
  73795. if (_this.db) {
  73796. try {
  73797. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73798. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73799. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73800. }
  73801. catch (ex) {
  73802. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73803. handleError();
  73804. }
  73805. }
  73806. };
  73807. }
  73808. // DB has already been created and opened
  73809. else {
  73810. if (successCallback)
  73811. successCallback();
  73812. }
  73813. }
  73814. };
  73815. /**
  73816. * Loads an image from the database
  73817. * @param url defines the url to load from
  73818. * @param image defines the target DOM image
  73819. */
  73820. Database.prototype.loadImageFromDB = function (url, image) {
  73821. var _this = this;
  73822. var completeURL = Database._ReturnFullUrlLocation(url);
  73823. var saveAndLoadImage = function () {
  73824. if (!_this.hasReachedQuota && _this.db !== null) {
  73825. // the texture is not yet in the DB, let's try to save it
  73826. _this._saveImageIntoDBAsync(completeURL, image);
  73827. }
  73828. // If the texture is not in the DB and we've reached the DB quota limit
  73829. // let's load it directly from the web
  73830. else {
  73831. image.src = url;
  73832. }
  73833. };
  73834. if (!this.mustUpdateRessources) {
  73835. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73836. }
  73837. // First time we're download the images or update requested in the manifest file by a version change
  73838. else {
  73839. saveAndLoadImage();
  73840. }
  73841. };
  73842. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73843. if (this.isSupported && this.db !== null) {
  73844. var texture;
  73845. var transaction = this.db.transaction(["textures"]);
  73846. transaction.onabort = function (event) {
  73847. image.src = url;
  73848. };
  73849. transaction.oncomplete = function (event) {
  73850. var blobTextureURL;
  73851. if (texture) {
  73852. var URL = window.URL || window.webkitURL;
  73853. blobTextureURL = URL.createObjectURL(texture.data);
  73854. image.onerror = function () {
  73855. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73856. image.src = url;
  73857. };
  73858. image.src = blobTextureURL;
  73859. }
  73860. else {
  73861. notInDBCallback();
  73862. }
  73863. };
  73864. var getRequest = transaction.objectStore("textures").get(url);
  73865. getRequest.onsuccess = function (event) {
  73866. texture = (event.target).result;
  73867. };
  73868. getRequest.onerror = function (event) {
  73869. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73870. image.src = url;
  73871. };
  73872. }
  73873. else {
  73874. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73875. image.src = url;
  73876. }
  73877. };
  73878. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73879. var _this = this;
  73880. if (this.isSupported) {
  73881. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73882. var generateBlobUrl = function () {
  73883. var blobTextureURL;
  73884. if (blob) {
  73885. var URL = window.URL || window.webkitURL;
  73886. try {
  73887. blobTextureURL = URL.createObjectURL(blob);
  73888. }
  73889. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73890. catch (ex) {
  73891. blobTextureURL = URL.createObjectURL(blob);
  73892. }
  73893. }
  73894. if (blobTextureURL) {
  73895. image.src = blobTextureURL;
  73896. }
  73897. };
  73898. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73899. var xhr = new XMLHttpRequest(), blob;
  73900. xhr.open("GET", url, true);
  73901. xhr.responseType = "blob";
  73902. xhr.addEventListener("load", function () {
  73903. if (xhr.status === 200 && _this.db) {
  73904. // Blob as response (XHR2)
  73905. blob = xhr.response;
  73906. var transaction = _this.db.transaction(["textures"], "readwrite");
  73907. // the transaction could abort because of a QuotaExceededError error
  73908. transaction.onabort = function (event) {
  73909. try {
  73910. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73911. var srcElement = (event.srcElement || event.target);
  73912. var error = srcElement.error;
  73913. if (error && error.name === "QuotaExceededError") {
  73914. _this.hasReachedQuota = true;
  73915. }
  73916. }
  73917. catch (ex) { }
  73918. generateBlobUrl();
  73919. };
  73920. transaction.oncomplete = function (event) {
  73921. generateBlobUrl();
  73922. };
  73923. var newTexture = { textureUrl: url, data: blob };
  73924. try {
  73925. // Put the blob into the dabase
  73926. var addRequest = transaction.objectStore("textures").put(newTexture);
  73927. addRequest.onsuccess = function (event) {
  73928. };
  73929. addRequest.onerror = function (event) {
  73930. generateBlobUrl();
  73931. };
  73932. }
  73933. catch (ex) {
  73934. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73935. if (ex.code === 25) {
  73936. Database.IsUASupportingBlobStorage = false;
  73937. }
  73938. image.src = url;
  73939. }
  73940. }
  73941. else {
  73942. image.src = url;
  73943. }
  73944. }, false);
  73945. xhr.addEventListener("error", function (event) {
  73946. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73947. image.src = url;
  73948. }, false);
  73949. xhr.send();
  73950. }
  73951. else {
  73952. image.src = url;
  73953. }
  73954. }
  73955. else {
  73956. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73957. image.src = url;
  73958. }
  73959. };
  73960. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73961. var _this = this;
  73962. var updateVersion = function () {
  73963. // the version is not yet in the DB or we need to update it
  73964. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73965. };
  73966. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73967. };
  73968. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73969. var _this = this;
  73970. if (this.isSupported && this.db) {
  73971. var version;
  73972. try {
  73973. var transaction = this.db.transaction(["versions"]);
  73974. transaction.oncomplete = function (event) {
  73975. if (version) {
  73976. // If the version in the JSON file is different from the version in DB
  73977. if (_this.manifestVersionFound !== version.data) {
  73978. _this.mustUpdateRessources = true;
  73979. updateInDBCallback();
  73980. }
  73981. else {
  73982. callback(version.data);
  73983. }
  73984. }
  73985. // version was not found in DB
  73986. else {
  73987. _this.mustUpdateRessources = true;
  73988. updateInDBCallback();
  73989. }
  73990. };
  73991. transaction.onabort = function (event) {
  73992. callback(-1);
  73993. };
  73994. var getRequest = transaction.objectStore("versions").get(url);
  73995. getRequest.onsuccess = function (event) {
  73996. version = (event.target).result;
  73997. };
  73998. getRequest.onerror = function (event) {
  73999. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  74000. callback(-1);
  74001. };
  74002. }
  74003. catch (ex) {
  74004. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  74005. callback(-1);
  74006. }
  74007. }
  74008. else {
  74009. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74010. callback(-1);
  74011. }
  74012. };
  74013. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  74014. var _this = this;
  74015. if (this.isSupported && !this.hasReachedQuota && this.db) {
  74016. try {
  74017. // Open a transaction to the database
  74018. var transaction = this.db.transaction(["versions"], "readwrite");
  74019. // the transaction could abort because of a QuotaExceededError error
  74020. transaction.onabort = function (event) {
  74021. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  74022. var error = event.srcElement['error'];
  74023. if (error && error.name === "QuotaExceededError") {
  74024. _this.hasReachedQuota = true;
  74025. }
  74026. }
  74027. catch (ex) { }
  74028. callback(-1);
  74029. };
  74030. transaction.oncomplete = function (event) {
  74031. callback(_this.manifestVersionFound);
  74032. };
  74033. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  74034. // Put the scene into the database
  74035. var addRequest = transaction.objectStore("versions").put(newVersion);
  74036. addRequest.onsuccess = function (event) {
  74037. };
  74038. addRequest.onerror = function (event) {
  74039. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  74040. };
  74041. }
  74042. catch (ex) {
  74043. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  74044. callback(-1);
  74045. }
  74046. }
  74047. else {
  74048. callback(-1);
  74049. }
  74050. };
  74051. /**
  74052. * Loads a file from database
  74053. * @param url defines the URL to load from
  74054. * @param sceneLoaded defines a callback to call on success
  74055. * @param progressCallBack defines a callback to call when progress changed
  74056. * @param errorCallback defines a callback to call on error
  74057. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  74058. */
  74059. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  74060. var _this = this;
  74061. var completeUrl = Database._ReturnFullUrlLocation(url);
  74062. var saveAndLoadFile = function () {
  74063. // the scene is not yet in the DB, let's try to save it
  74064. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  74065. };
  74066. this._checkVersionFromDB(completeUrl, function (version) {
  74067. if (version !== -1) {
  74068. if (!_this.mustUpdateRessources) {
  74069. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  74070. }
  74071. else {
  74072. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  74073. }
  74074. }
  74075. else {
  74076. if (errorCallback) {
  74077. errorCallback();
  74078. }
  74079. }
  74080. });
  74081. };
  74082. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  74083. if (this.isSupported && this.db) {
  74084. var targetStore;
  74085. if (url.indexOf(".babylon") !== -1) {
  74086. targetStore = "scenes";
  74087. }
  74088. else {
  74089. targetStore = "textures";
  74090. }
  74091. var file;
  74092. var transaction = this.db.transaction([targetStore]);
  74093. transaction.oncomplete = function (event) {
  74094. if (file) {
  74095. callback(file.data);
  74096. }
  74097. // file was not found in DB
  74098. else {
  74099. notInDBCallback();
  74100. }
  74101. };
  74102. transaction.onabort = function (event) {
  74103. notInDBCallback();
  74104. };
  74105. var getRequest = transaction.objectStore(targetStore).get(url);
  74106. getRequest.onsuccess = function (event) {
  74107. file = (event.target).result;
  74108. };
  74109. getRequest.onerror = function (event) {
  74110. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  74111. notInDBCallback();
  74112. };
  74113. }
  74114. else {
  74115. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74116. callback();
  74117. }
  74118. };
  74119. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  74120. var _this = this;
  74121. if (this.isSupported) {
  74122. var targetStore;
  74123. if (url.indexOf(".babylon") !== -1) {
  74124. targetStore = "scenes";
  74125. }
  74126. else {
  74127. targetStore = "textures";
  74128. }
  74129. // Create XHR
  74130. var xhr = new XMLHttpRequest();
  74131. var fileData;
  74132. xhr.open("GET", url + "?" + Date.now(), true);
  74133. if (useArrayBuffer) {
  74134. xhr.responseType = "arraybuffer";
  74135. }
  74136. if (progressCallback) {
  74137. xhr.onprogress = progressCallback;
  74138. }
  74139. xhr.addEventListener("load", function () {
  74140. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  74141. // Blob as response (XHR2)
  74142. //fileData = xhr.responseText;
  74143. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  74144. if (!_this.hasReachedQuota && _this.db) {
  74145. // Open a transaction to the database
  74146. var transaction = _this.db.transaction([targetStore], "readwrite");
  74147. // the transaction could abort because of a QuotaExceededError error
  74148. transaction.onabort = function (event) {
  74149. try {
  74150. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  74151. var error = event.srcElement['error'];
  74152. if (error && error.name === "QuotaExceededError") {
  74153. _this.hasReachedQuota = true;
  74154. }
  74155. }
  74156. catch (ex) { }
  74157. callback(fileData);
  74158. };
  74159. transaction.oncomplete = function (event) {
  74160. callback(fileData);
  74161. };
  74162. var newFile;
  74163. if (targetStore === "scenes") {
  74164. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  74165. }
  74166. else {
  74167. newFile = { textureUrl: url, data: fileData };
  74168. }
  74169. try {
  74170. // Put the scene into the database
  74171. var addRequest = transaction.objectStore(targetStore).put(newFile);
  74172. addRequest.onsuccess = function (event) {
  74173. };
  74174. addRequest.onerror = function (event) {
  74175. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  74176. };
  74177. }
  74178. catch (ex) {
  74179. callback(fileData);
  74180. }
  74181. }
  74182. else {
  74183. callback(fileData);
  74184. }
  74185. }
  74186. else {
  74187. if (xhr.status >= 400 && errorCallback) {
  74188. errorCallback(xhr);
  74189. }
  74190. else {
  74191. callback();
  74192. }
  74193. }
  74194. }, false);
  74195. xhr.addEventListener("error", function (event) {
  74196. BABYLON.Tools.Error("error on XHR request.");
  74197. callback();
  74198. }, false);
  74199. xhr.send();
  74200. }
  74201. else {
  74202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74203. callback();
  74204. }
  74205. };
  74206. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  74207. Database.IsUASupportingBlobStorage = true;
  74208. /** Gets a boolean indicating if Database storate is enabled */
  74209. Database.IDBStorageEnabled = true;
  74210. Database._ParseURL = function (url) {
  74211. var a = document.createElement('a');
  74212. a.href = url;
  74213. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  74214. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  74215. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  74216. return absLocation;
  74217. };
  74218. Database._ReturnFullUrlLocation = function (url) {
  74219. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  74220. return (Database._ParseURL(window.location.href) + url);
  74221. }
  74222. else {
  74223. return url;
  74224. }
  74225. };
  74226. return Database;
  74227. }());
  74228. BABYLON.Database = Database;
  74229. })(BABYLON || (BABYLON = {}));
  74230. //# sourceMappingURL=babylon.database.js.map
  74231. var BABYLON;
  74232. (function (BABYLON) {
  74233. var FresnelParameters = /** @class */ (function () {
  74234. function FresnelParameters() {
  74235. this._isEnabled = true;
  74236. this.leftColor = BABYLON.Color3.White();
  74237. this.rightColor = BABYLON.Color3.Black();
  74238. this.bias = 0;
  74239. this.power = 1;
  74240. }
  74241. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  74242. get: function () {
  74243. return this._isEnabled;
  74244. },
  74245. set: function (value) {
  74246. if (this._isEnabled === value) {
  74247. return;
  74248. }
  74249. this._isEnabled = value;
  74250. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  74251. },
  74252. enumerable: true,
  74253. configurable: true
  74254. });
  74255. FresnelParameters.prototype.clone = function () {
  74256. var newFresnelParameters = new FresnelParameters();
  74257. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  74258. return newFresnelParameters;
  74259. };
  74260. FresnelParameters.prototype.serialize = function () {
  74261. var serializationObject = {};
  74262. serializationObject.isEnabled = this.isEnabled;
  74263. serializationObject.leftColor = this.leftColor.asArray();
  74264. serializationObject.rightColor = this.rightColor.asArray();
  74265. serializationObject.bias = this.bias;
  74266. serializationObject.power = this.power;
  74267. return serializationObject;
  74268. };
  74269. FresnelParameters.Parse = function (parsedFresnelParameters) {
  74270. var fresnelParameters = new FresnelParameters();
  74271. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  74272. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  74273. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  74274. fresnelParameters.bias = parsedFresnelParameters.bias;
  74275. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  74276. return fresnelParameters;
  74277. };
  74278. return FresnelParameters;
  74279. }());
  74280. BABYLON.FresnelParameters = FresnelParameters;
  74281. })(BABYLON || (BABYLON = {}));
  74282. //# sourceMappingURL=babylon.fresnelParameters.js.map
  74283. var BABYLON;
  74284. (function (BABYLON) {
  74285. var MultiMaterial = /** @class */ (function (_super) {
  74286. __extends(MultiMaterial, _super);
  74287. function MultiMaterial(name, scene) {
  74288. var _this = _super.call(this, name, scene, true) || this;
  74289. scene.multiMaterials.push(_this);
  74290. _this.subMaterials = new Array();
  74291. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  74292. return _this;
  74293. }
  74294. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  74295. get: function () {
  74296. return this._subMaterials;
  74297. },
  74298. set: function (value) {
  74299. this._subMaterials = value;
  74300. this._hookArray(value);
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. MultiMaterial.prototype._hookArray = function (array) {
  74306. var _this = this;
  74307. var oldPush = array.push;
  74308. array.push = function () {
  74309. var items = [];
  74310. for (var _i = 0; _i < arguments.length; _i++) {
  74311. items[_i] = arguments[_i];
  74312. }
  74313. var result = oldPush.apply(array, items);
  74314. _this._markAllSubMeshesAsTexturesDirty();
  74315. return result;
  74316. };
  74317. var oldSplice = array.splice;
  74318. array.splice = function (index, deleteCount) {
  74319. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74320. _this._markAllSubMeshesAsTexturesDirty();
  74321. return deleted;
  74322. };
  74323. };
  74324. // Properties
  74325. MultiMaterial.prototype.getSubMaterial = function (index) {
  74326. if (index < 0 || index >= this.subMaterials.length) {
  74327. return this.getScene().defaultMaterial;
  74328. }
  74329. return this.subMaterials[index];
  74330. };
  74331. MultiMaterial.prototype.getActiveTextures = function () {
  74332. var _a;
  74333. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  74334. if (subMaterial) {
  74335. return subMaterial.getActiveTextures();
  74336. }
  74337. else {
  74338. return [];
  74339. }
  74340. }));
  74341. };
  74342. // Methods
  74343. MultiMaterial.prototype.getClassName = function () {
  74344. return "MultiMaterial";
  74345. };
  74346. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74347. for (var index = 0; index < this.subMaterials.length; index++) {
  74348. var subMaterial = this.subMaterials[index];
  74349. if (subMaterial) {
  74350. if (subMaterial.storeEffectOnSubMeshes) {
  74351. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  74352. return false;
  74353. }
  74354. continue;
  74355. }
  74356. if (!subMaterial.isReady(mesh)) {
  74357. return false;
  74358. }
  74359. }
  74360. }
  74361. return true;
  74362. };
  74363. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  74364. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  74365. for (var index = 0; index < this.subMaterials.length; index++) {
  74366. var subMaterial = null;
  74367. var current = this.subMaterials[index];
  74368. if (cloneChildren && current) {
  74369. subMaterial = current.clone(name + "-" + current.name);
  74370. }
  74371. else {
  74372. subMaterial = this.subMaterials[index];
  74373. }
  74374. newMultiMaterial.subMaterials.push(subMaterial);
  74375. }
  74376. return newMultiMaterial;
  74377. };
  74378. MultiMaterial.prototype.serialize = function () {
  74379. var serializationObject = {};
  74380. serializationObject.name = this.name;
  74381. serializationObject.id = this.id;
  74382. if (BABYLON.Tags) {
  74383. serializationObject.tags = BABYLON.Tags.GetTags(this);
  74384. }
  74385. serializationObject.materials = [];
  74386. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  74387. var subMat = this.subMaterials[matIndex];
  74388. if (subMat) {
  74389. serializationObject.materials.push(subMat.id);
  74390. }
  74391. else {
  74392. serializationObject.materials.push(null);
  74393. }
  74394. }
  74395. return serializationObject;
  74396. };
  74397. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74398. var scene = this.getScene();
  74399. if (!scene) {
  74400. return;
  74401. }
  74402. var index = scene.multiMaterials.indexOf(this);
  74403. if (index >= 0) {
  74404. scene.multiMaterials.splice(index, 1);
  74405. }
  74406. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  74407. };
  74408. return MultiMaterial;
  74409. }(BABYLON.Material));
  74410. BABYLON.MultiMaterial = MultiMaterial;
  74411. })(BABYLON || (BABYLON = {}));
  74412. //# sourceMappingURL=babylon.multiMaterial.js.map
  74413. var BABYLON;
  74414. (function (BABYLON) {
  74415. var FreeCameraTouchInput = /** @class */ (function () {
  74416. function FreeCameraTouchInput() {
  74417. this._offsetX = null;
  74418. this._offsetY = null;
  74419. this._pointerPressed = new Array();
  74420. this.touchAngularSensibility = 200000.0;
  74421. this.touchMoveSensibility = 250.0;
  74422. }
  74423. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  74424. var _this = this;
  74425. var previousPosition = null;
  74426. if (this._pointerInput === undefined) {
  74427. this._onLostFocus = function (evt) {
  74428. _this._offsetX = null;
  74429. _this._offsetY = null;
  74430. };
  74431. this._pointerInput = function (p, s) {
  74432. var evt = p.event;
  74433. if (evt.pointerType === "mouse") {
  74434. return;
  74435. }
  74436. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74437. if (!noPreventDefault) {
  74438. evt.preventDefault();
  74439. }
  74440. _this._pointerPressed.push(evt.pointerId);
  74441. if (_this._pointerPressed.length !== 1) {
  74442. return;
  74443. }
  74444. previousPosition = {
  74445. x: evt.clientX,
  74446. y: evt.clientY
  74447. };
  74448. }
  74449. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  74450. if (!noPreventDefault) {
  74451. evt.preventDefault();
  74452. }
  74453. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74454. if (index === -1) {
  74455. return;
  74456. }
  74457. _this._pointerPressed.splice(index, 1);
  74458. if (index != 0) {
  74459. return;
  74460. }
  74461. previousPosition = null;
  74462. _this._offsetX = null;
  74463. _this._offsetY = null;
  74464. }
  74465. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  74466. if (!noPreventDefault) {
  74467. evt.preventDefault();
  74468. }
  74469. if (!previousPosition) {
  74470. return;
  74471. }
  74472. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74473. if (index != 0) {
  74474. return;
  74475. }
  74476. _this._offsetX = evt.clientX - previousPosition.x;
  74477. _this._offsetY = -(evt.clientY - previousPosition.y);
  74478. }
  74479. };
  74480. }
  74481. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  74482. if (this._onLostFocus) {
  74483. element.addEventListener("blur", this._onLostFocus);
  74484. }
  74485. };
  74486. FreeCameraTouchInput.prototype.detachControl = function (element) {
  74487. if (this._pointerInput && element) {
  74488. if (this._observer) {
  74489. this.camera.getScene().onPointerObservable.remove(this._observer);
  74490. this._observer = null;
  74491. }
  74492. if (this._onLostFocus) {
  74493. element.removeEventListener("blur", this._onLostFocus);
  74494. this._onLostFocus = null;
  74495. }
  74496. this._pointerPressed = [];
  74497. this._offsetX = null;
  74498. this._offsetY = null;
  74499. }
  74500. };
  74501. FreeCameraTouchInput.prototype.checkInputs = function () {
  74502. if (this._offsetX && this._offsetY) {
  74503. var camera = this.camera;
  74504. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74505. if (this._pointerPressed.length > 1) {
  74506. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74507. }
  74508. else {
  74509. var speed = camera._computeLocalCameraSpeed();
  74510. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74511. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74512. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74513. }
  74514. }
  74515. };
  74516. FreeCameraTouchInput.prototype.getClassName = function () {
  74517. return "FreeCameraTouchInput";
  74518. };
  74519. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74520. return "touch";
  74521. };
  74522. __decorate([
  74523. BABYLON.serialize()
  74524. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74525. __decorate([
  74526. BABYLON.serialize()
  74527. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74528. return FreeCameraTouchInput;
  74529. }());
  74530. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74531. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74532. })(BABYLON || (BABYLON = {}));
  74533. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74534. var BABYLON;
  74535. (function (BABYLON) {
  74536. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74537. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74538. });
  74539. // We're mainly based on the logic defined into the FreeCamera code
  74540. var TouchCamera = /** @class */ (function (_super) {
  74541. __extends(TouchCamera, _super);
  74542. //-- end properties for backward compatibility for inputs
  74543. function TouchCamera(name, position, scene) {
  74544. var _this = _super.call(this, name, position, scene) || this;
  74545. _this.inputs.addTouch();
  74546. _this._setupInputs();
  74547. return _this;
  74548. }
  74549. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74550. //-- Begin properties for backward compatibility for inputs
  74551. get: function () {
  74552. var touch = this.inputs.attached["touch"];
  74553. if (touch)
  74554. return touch.touchAngularSensibility;
  74555. return 0;
  74556. },
  74557. set: function (value) {
  74558. var touch = this.inputs.attached["touch"];
  74559. if (touch)
  74560. touch.touchAngularSensibility = value;
  74561. },
  74562. enumerable: true,
  74563. configurable: true
  74564. });
  74565. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74566. get: function () {
  74567. var touch = this.inputs.attached["touch"];
  74568. if (touch)
  74569. return touch.touchMoveSensibility;
  74570. return 0;
  74571. },
  74572. set: function (value) {
  74573. var touch = this.inputs.attached["touch"];
  74574. if (touch)
  74575. touch.touchMoveSensibility = value;
  74576. },
  74577. enumerable: true,
  74578. configurable: true
  74579. });
  74580. TouchCamera.prototype.getClassName = function () {
  74581. return "TouchCamera";
  74582. };
  74583. /** @hidden */
  74584. TouchCamera.prototype._setupInputs = function () {
  74585. var mouse = this.inputs.attached["mouse"];
  74586. if (mouse) {
  74587. mouse.touchEnabled = false;
  74588. }
  74589. };
  74590. return TouchCamera;
  74591. }(BABYLON.FreeCamera));
  74592. BABYLON.TouchCamera = TouchCamera;
  74593. })(BABYLON || (BABYLON = {}));
  74594. //# sourceMappingURL=babylon.touchCamera.js.map
  74595. var BABYLON;
  74596. (function (BABYLON) {
  74597. var ProceduralTexture = /** @class */ (function (_super) {
  74598. __extends(ProceduralTexture, _super);
  74599. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74600. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74601. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74602. if (isCube === void 0) { isCube = false; }
  74603. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74604. _this.isCube = isCube;
  74605. _this.isEnabled = true;
  74606. _this._currentRefreshId = -1;
  74607. _this._refreshRate = 1;
  74608. /**
  74609. * Event raised when the texture is generated
  74610. */
  74611. _this.onGeneratedObservable = new BABYLON.Observable();
  74612. _this._vertexBuffers = {};
  74613. _this._uniforms = new Array();
  74614. _this._samplers = new Array();
  74615. /** @hidden */
  74616. _this._textures = {};
  74617. _this._floats = {};
  74618. _this._ints = {};
  74619. _this._floatsArrays = {};
  74620. _this._colors3 = {};
  74621. _this._colors4 = {};
  74622. _this._vectors2 = {};
  74623. _this._vectors3 = {};
  74624. _this._matrices = {};
  74625. _this._fallbackTextureUsed = false;
  74626. _this._cachedDefines = "";
  74627. _this._contentUpdateId = -1;
  74628. scene = _this.getScene();
  74629. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74630. if (!component) {
  74631. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74632. scene._addComponent(component);
  74633. }
  74634. scene.proceduralTextures.push(_this);
  74635. _this._engine = scene.getEngine();
  74636. _this.name = name;
  74637. _this.isRenderTarget = true;
  74638. _this._size = size;
  74639. _this._generateMipMaps = generateMipMaps;
  74640. _this.setFragment(fragment);
  74641. _this._fallbackTexture = fallbackTexture;
  74642. if (isCube) {
  74643. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74644. _this.setFloat("face", 0);
  74645. }
  74646. else {
  74647. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74648. }
  74649. // VBO
  74650. var vertices = [];
  74651. vertices.push(1, 1);
  74652. vertices.push(-1, 1);
  74653. vertices.push(-1, -1);
  74654. vertices.push(1, -1);
  74655. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74656. _this._createIndexBuffer();
  74657. return _this;
  74658. }
  74659. /**
  74660. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  74661. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  74662. */
  74663. ProceduralTexture.prototype.getContent = function () {
  74664. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  74665. return this._contentData;
  74666. }
  74667. this._contentData = this.readPixels(0, 0, this._contentData);
  74668. this._contentUpdateId = this._currentRefreshId;
  74669. return this._contentData;
  74670. };
  74671. ProceduralTexture.prototype._createIndexBuffer = function () {
  74672. var engine = this._engine;
  74673. // Indices
  74674. var indices = [];
  74675. indices.push(0);
  74676. indices.push(1);
  74677. indices.push(2);
  74678. indices.push(0);
  74679. indices.push(2);
  74680. indices.push(3);
  74681. this._indexBuffer = engine.createIndexBuffer(indices);
  74682. };
  74683. /** @hidden */
  74684. ProceduralTexture.prototype._rebuild = function () {
  74685. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74686. if (vb) {
  74687. vb._rebuild();
  74688. }
  74689. this._createIndexBuffer();
  74690. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74691. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74692. }
  74693. };
  74694. ProceduralTexture.prototype.reset = function () {
  74695. if (this._effect === undefined) {
  74696. return;
  74697. }
  74698. var engine = this._engine;
  74699. engine._releaseEffect(this._effect);
  74700. };
  74701. ProceduralTexture.prototype._getDefines = function () {
  74702. return "";
  74703. };
  74704. ProceduralTexture.prototype.isReady = function () {
  74705. var _this = this;
  74706. var engine = this._engine;
  74707. var shaders;
  74708. if (!this._fragment) {
  74709. return false;
  74710. }
  74711. if (this._fallbackTextureUsed) {
  74712. return true;
  74713. }
  74714. var defines = this._getDefines();
  74715. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74716. return true;
  74717. }
  74718. if (this._fragment.fragmentElement !== undefined) {
  74719. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74720. }
  74721. else {
  74722. shaders = { vertex: "procedural", fragment: this._fragment };
  74723. }
  74724. this._cachedDefines = defines;
  74725. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74726. _this.releaseInternalTexture();
  74727. if (_this._fallbackTexture) {
  74728. _this._texture = _this._fallbackTexture._texture;
  74729. if (_this._texture) {
  74730. _this._texture.incrementReferences();
  74731. }
  74732. }
  74733. _this._fallbackTextureUsed = true;
  74734. });
  74735. return this._effect.isReady();
  74736. };
  74737. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74738. this._currentRefreshId = -1;
  74739. };
  74740. ProceduralTexture.prototype.setFragment = function (fragment) {
  74741. this._fragment = fragment;
  74742. };
  74743. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74744. get: function () {
  74745. return this._refreshRate;
  74746. },
  74747. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74748. set: function (value) {
  74749. this._refreshRate = value;
  74750. this.resetRefreshCounter();
  74751. },
  74752. enumerable: true,
  74753. configurable: true
  74754. });
  74755. /** @hidden */
  74756. ProceduralTexture.prototype._shouldRender = function () {
  74757. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74758. if (this._texture) {
  74759. this._texture.isReady = false;
  74760. }
  74761. return false;
  74762. }
  74763. if (this._fallbackTextureUsed) {
  74764. return false;
  74765. }
  74766. if (this._currentRefreshId === -1) { // At least render once
  74767. this._currentRefreshId = 1;
  74768. return true;
  74769. }
  74770. if (this.refreshRate === this._currentRefreshId) {
  74771. this._currentRefreshId = 1;
  74772. return true;
  74773. }
  74774. this._currentRefreshId++;
  74775. return false;
  74776. };
  74777. ProceduralTexture.prototype.getRenderSize = function () {
  74778. return this._size;
  74779. };
  74780. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74781. if (this._fallbackTextureUsed) {
  74782. return;
  74783. }
  74784. this.releaseInternalTexture();
  74785. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74786. // Update properties
  74787. this._size = size;
  74788. this._generateMipMaps = generateMipMaps;
  74789. };
  74790. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74791. if (this._uniforms.indexOf(uniformName) === -1) {
  74792. this._uniforms.push(uniformName);
  74793. }
  74794. };
  74795. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74796. if (this._samplers.indexOf(name) === -1) {
  74797. this._samplers.push(name);
  74798. }
  74799. this._textures[name] = texture;
  74800. return this;
  74801. };
  74802. ProceduralTexture.prototype.setFloat = function (name, value) {
  74803. this._checkUniform(name);
  74804. this._floats[name] = value;
  74805. return this;
  74806. };
  74807. /**
  74808. * Set the value of an uniform to an integer value
  74809. * @param name defines the name of the uniform
  74810. * @param value defines the value to set
  74811. * @returns the current procedural texture
  74812. */
  74813. ProceduralTexture.prototype.setInt = function (name, value) {
  74814. this._checkUniform(name);
  74815. this._ints[name] = value;
  74816. return this;
  74817. };
  74818. ProceduralTexture.prototype.setFloats = function (name, value) {
  74819. this._checkUniform(name);
  74820. this._floatsArrays[name] = value;
  74821. return this;
  74822. };
  74823. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74824. this._checkUniform(name);
  74825. this._colors3[name] = value;
  74826. return this;
  74827. };
  74828. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74829. this._checkUniform(name);
  74830. this._colors4[name] = value;
  74831. return this;
  74832. };
  74833. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74834. this._checkUniform(name);
  74835. this._vectors2[name] = value;
  74836. return this;
  74837. };
  74838. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74839. this._checkUniform(name);
  74840. this._vectors3[name] = value;
  74841. return this;
  74842. };
  74843. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74844. this._checkUniform(name);
  74845. this._matrices[name] = value;
  74846. return this;
  74847. };
  74848. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74849. var scene = this.getScene();
  74850. if (!scene) {
  74851. return;
  74852. }
  74853. var engine = this._engine;
  74854. // Render
  74855. engine.enableEffect(this._effect);
  74856. engine.setState(false);
  74857. // Texture
  74858. for (var name in this._textures) {
  74859. this._effect.setTexture(name, this._textures[name]);
  74860. }
  74861. // Float
  74862. for (name in this._ints) {
  74863. this._effect.setInt(name, this._ints[name]);
  74864. }
  74865. // Float
  74866. for (name in this._floats) {
  74867. this._effect.setFloat(name, this._floats[name]);
  74868. }
  74869. // Floats
  74870. for (name in this._floatsArrays) {
  74871. this._effect.setArray(name, this._floatsArrays[name]);
  74872. }
  74873. // Color3
  74874. for (name in this._colors3) {
  74875. this._effect.setColor3(name, this._colors3[name]);
  74876. }
  74877. // Color4
  74878. for (name in this._colors4) {
  74879. var color = this._colors4[name];
  74880. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74881. }
  74882. // Vector2
  74883. for (name in this._vectors2) {
  74884. this._effect.setVector2(name, this._vectors2[name]);
  74885. }
  74886. // Vector3
  74887. for (name in this._vectors3) {
  74888. this._effect.setVector3(name, this._vectors3[name]);
  74889. }
  74890. // Matrix
  74891. for (name in this._matrices) {
  74892. this._effect.setMatrix(name, this._matrices[name]);
  74893. }
  74894. if (!this._texture) {
  74895. return;
  74896. }
  74897. if (this.isCube) {
  74898. for (var face = 0; face < 6; face++) {
  74899. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74900. // VBOs
  74901. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74902. this._effect.setFloat("face", face);
  74903. // Clear
  74904. engine.clear(scene.clearColor, true, true, true);
  74905. // Draw order
  74906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74907. // Mipmaps
  74908. if (face === 5) {
  74909. engine.generateMipMapsForCubemap(this._texture);
  74910. }
  74911. }
  74912. }
  74913. else {
  74914. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74915. // VBOs
  74916. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74917. // Clear
  74918. engine.clear(scene.clearColor, true, true, true);
  74919. // Draw order
  74920. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74921. }
  74922. // Unbind
  74923. engine.unBindFramebuffer(this._texture, this.isCube);
  74924. if (this.onGenerated) {
  74925. this.onGenerated();
  74926. }
  74927. this.onGeneratedObservable.notifyObservers(this);
  74928. };
  74929. ProceduralTexture.prototype.clone = function () {
  74930. var textureSize = this.getSize();
  74931. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74932. // Base texture
  74933. newTexture.hasAlpha = this.hasAlpha;
  74934. newTexture.level = this.level;
  74935. // RenderTarget Texture
  74936. newTexture.coordinatesMode = this.coordinatesMode;
  74937. return newTexture;
  74938. };
  74939. ProceduralTexture.prototype.dispose = function () {
  74940. var scene = this.getScene();
  74941. if (!scene) {
  74942. return;
  74943. }
  74944. var index = scene.proceduralTextures.indexOf(this);
  74945. if (index >= 0) {
  74946. scene.proceduralTextures.splice(index, 1);
  74947. }
  74948. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74949. if (vertexBuffer) {
  74950. vertexBuffer.dispose();
  74951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74952. }
  74953. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74954. this._indexBuffer = null;
  74955. }
  74956. _super.prototype.dispose.call(this);
  74957. };
  74958. __decorate([
  74959. BABYLON.serialize()
  74960. ], ProceduralTexture.prototype, "_size", void 0);
  74961. __decorate([
  74962. BABYLON.serialize()
  74963. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74964. __decorate([
  74965. BABYLON.serialize()
  74966. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74967. __decorate([
  74968. BABYLON.serialize()
  74969. ], ProceduralTexture.prototype, "refreshRate", null);
  74970. return ProceduralTexture;
  74971. }(BABYLON.Texture));
  74972. BABYLON.ProceduralTexture = ProceduralTexture;
  74973. })(BABYLON || (BABYLON = {}));
  74974. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74975. var BABYLON;
  74976. (function (BABYLON) {
  74977. /**
  74978. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74979. * in a given scene.
  74980. */
  74981. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74982. /**
  74983. * Creates a new instance of the component for the given scene
  74984. * @param scene Defines the scene to register the component in
  74985. */
  74986. function ProceduralTextureSceneComponent(scene) {
  74987. /**
  74988. * The component name helpfull to identify the component in the list of scene components.
  74989. */
  74990. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74991. this.scene = scene;
  74992. this.scene.proceduralTextures = new Array();
  74993. scene.layers = new Array();
  74994. }
  74995. /**
  74996. * Registers the component in a given scene
  74997. */
  74998. ProceduralTextureSceneComponent.prototype.register = function () {
  74999. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  75000. };
  75001. /**
  75002. * Rebuilds the elements related to this component in case of
  75003. * context lost for instance.
  75004. */
  75005. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  75006. // Nothing to do here.
  75007. };
  75008. /**
  75009. * Disposes the component and the associated ressources.
  75010. */
  75011. ProceduralTextureSceneComponent.prototype.dispose = function () {
  75012. // Nothing to do here.
  75013. };
  75014. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  75015. if (this.scene.proceduralTexturesEnabled) {
  75016. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  75017. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  75018. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  75019. if (proceduralTexture._shouldRender()) {
  75020. proceduralTexture.render();
  75021. }
  75022. }
  75023. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  75024. }
  75025. };
  75026. return ProceduralTextureSceneComponent;
  75027. }());
  75028. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  75029. })(BABYLON || (BABYLON = {}));
  75030. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  75031. var BABYLON;
  75032. (function (BABYLON) {
  75033. var CustomProceduralTexture = /** @class */ (function (_super) {
  75034. __extends(CustomProceduralTexture, _super);
  75035. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  75036. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  75037. _this._animate = true;
  75038. _this._time = 0;
  75039. _this._texturePath = texturePath;
  75040. //Try to load json
  75041. _this.loadJson(texturePath);
  75042. _this.refreshRate = 1;
  75043. return _this;
  75044. }
  75045. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  75046. var _this = this;
  75047. var noConfigFile = function () {
  75048. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  75049. try {
  75050. _this.setFragment(_this._texturePath);
  75051. }
  75052. catch (ex) {
  75053. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  75054. }
  75055. };
  75056. var configFileUrl = jsonUrl + "/config.json";
  75057. var xhr = new XMLHttpRequest();
  75058. xhr.open("GET", configFileUrl, true);
  75059. xhr.addEventListener("load", function () {
  75060. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75061. try {
  75062. _this._config = JSON.parse(xhr.response);
  75063. _this.updateShaderUniforms();
  75064. _this.updateTextures();
  75065. _this.setFragment(_this._texturePath + "/custom");
  75066. _this._animate = _this._config.animate;
  75067. _this.refreshRate = _this._config.refreshrate;
  75068. }
  75069. catch (ex) {
  75070. noConfigFile();
  75071. }
  75072. }
  75073. else {
  75074. noConfigFile();
  75075. }
  75076. }, false);
  75077. xhr.addEventListener("error", function () {
  75078. noConfigFile();
  75079. }, false);
  75080. try {
  75081. xhr.send();
  75082. }
  75083. catch (ex) {
  75084. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  75085. }
  75086. };
  75087. CustomProceduralTexture.prototype.isReady = function () {
  75088. if (!_super.prototype.isReady.call(this)) {
  75089. return false;
  75090. }
  75091. for (var name in this._textures) {
  75092. var texture = this._textures[name];
  75093. if (!texture.isReady()) {
  75094. return false;
  75095. }
  75096. }
  75097. return true;
  75098. };
  75099. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  75100. var scene = this.getScene();
  75101. if (this._animate && scene) {
  75102. this._time += scene.getAnimationRatio() * 0.03;
  75103. this.updateShaderUniforms();
  75104. }
  75105. _super.prototype.render.call(this, useCameraPostProcess);
  75106. };
  75107. CustomProceduralTexture.prototype.updateTextures = function () {
  75108. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  75109. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  75110. }
  75111. };
  75112. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  75113. if (this._config) {
  75114. for (var j = 0; j < this._config.uniforms.length; j++) {
  75115. var uniform = this._config.uniforms[j];
  75116. switch (uniform.type) {
  75117. case "float":
  75118. this.setFloat(uniform.name, uniform.value);
  75119. break;
  75120. case "color3":
  75121. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  75122. break;
  75123. case "color4":
  75124. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  75125. break;
  75126. case "vector2":
  75127. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  75128. break;
  75129. case "vector3":
  75130. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  75131. break;
  75132. }
  75133. }
  75134. }
  75135. this.setFloat("time", this._time);
  75136. };
  75137. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  75138. get: function () {
  75139. return this._animate;
  75140. },
  75141. set: function (value) {
  75142. this._animate = value;
  75143. },
  75144. enumerable: true,
  75145. configurable: true
  75146. });
  75147. return CustomProceduralTexture;
  75148. }(BABYLON.ProceduralTexture));
  75149. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  75150. })(BABYLON || (BABYLON = {}));
  75151. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  75152. var BABYLON;
  75153. (function (BABYLON) {
  75154. var FreeCameraGamepadInput = /** @class */ (function () {
  75155. function FreeCameraGamepadInput() {
  75156. this.gamepadAngularSensibility = 200;
  75157. this.gamepadMoveSensibility = 40;
  75158. // private members
  75159. this._cameraTransform = BABYLON.Matrix.Identity();
  75160. this._deltaTransform = BABYLON.Vector3.Zero();
  75161. this._vector3 = BABYLON.Vector3.Zero();
  75162. this._vector2 = BABYLON.Vector2.Zero();
  75163. }
  75164. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  75165. var _this = this;
  75166. var manager = this.camera.getScene().gamepadManager;
  75167. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75168. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75169. // prioritize XBOX gamepads.
  75170. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  75171. _this.gamepad = gamepad;
  75172. }
  75173. }
  75174. });
  75175. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75176. if (_this.gamepad === gamepad) {
  75177. _this.gamepad = null;
  75178. }
  75179. });
  75180. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  75181. };
  75182. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  75183. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75184. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75185. this.gamepad = null;
  75186. };
  75187. FreeCameraGamepadInput.prototype.checkInputs = function () {
  75188. if (this.gamepad && this.gamepad.leftStick) {
  75189. var camera = this.camera;
  75190. var LSValues = this.gamepad.leftStick;
  75191. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  75192. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75193. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  75194. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  75195. var RSValues = this.gamepad.rightStick;
  75196. if (RSValues) {
  75197. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  75198. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  75199. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  75200. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  75201. }
  75202. else {
  75203. RSValues = { x: 0, y: 0 };
  75204. }
  75205. if (!camera.rotationQuaternion) {
  75206. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  75207. }
  75208. else {
  75209. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  75210. }
  75211. var speed = camera._computeLocalCameraSpeed() * 50.0;
  75212. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  75213. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  75214. camera.cameraDirection.addInPlace(this._deltaTransform);
  75215. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  75216. camera.cameraRotation.addInPlace(this._vector2);
  75217. }
  75218. };
  75219. FreeCameraGamepadInput.prototype.getClassName = function () {
  75220. return "FreeCameraGamepadInput";
  75221. };
  75222. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  75223. return "gamepad";
  75224. };
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75231. return FreeCameraGamepadInput;
  75232. }());
  75233. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  75234. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  75235. })(BABYLON || (BABYLON = {}));
  75236. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  75237. var BABYLON;
  75238. (function (BABYLON) {
  75239. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  75240. function ArcRotateCameraGamepadInput() {
  75241. this.gamepadRotationSensibility = 80;
  75242. this.gamepadMoveSensibility = 40;
  75243. }
  75244. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  75245. var _this = this;
  75246. var manager = this.camera.getScene().gamepadManager;
  75247. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75248. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75249. // prioritize XBOX gamepads.
  75250. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  75251. _this.gamepad = gamepad;
  75252. }
  75253. }
  75254. });
  75255. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75256. if (_this.gamepad === gamepad) {
  75257. _this.gamepad = null;
  75258. }
  75259. });
  75260. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  75261. };
  75262. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  75263. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75264. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75265. this.gamepad = null;
  75266. };
  75267. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  75268. if (this.gamepad) {
  75269. var camera = this.camera;
  75270. var RSValues = this.gamepad.rightStick;
  75271. if (RSValues) {
  75272. if (RSValues.x != 0) {
  75273. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  75274. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  75275. camera.inertialAlphaOffset += normalizedRX;
  75276. }
  75277. }
  75278. if (RSValues.y != 0) {
  75279. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  75280. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  75281. camera.inertialBetaOffset += normalizedRY;
  75282. }
  75283. }
  75284. }
  75285. var LSValues = this.gamepad.leftStick;
  75286. if (LSValues && LSValues.y != 0) {
  75287. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75288. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  75289. this.camera.inertialRadiusOffset -= normalizedLY;
  75290. }
  75291. }
  75292. }
  75293. };
  75294. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  75295. return "ArcRotateCameraGamepadInput";
  75296. };
  75297. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  75298. return "gamepad";
  75299. };
  75300. __decorate([
  75301. BABYLON.serialize()
  75302. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  75303. __decorate([
  75304. BABYLON.serialize()
  75305. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75306. return ArcRotateCameraGamepadInput;
  75307. }());
  75308. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  75309. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  75310. })(BABYLON || (BABYLON = {}));
  75311. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  75312. var BABYLON;
  75313. (function (BABYLON) {
  75314. var GamepadManager = /** @class */ (function () {
  75315. function GamepadManager(_scene) {
  75316. var _this = this;
  75317. this._scene = _scene;
  75318. this._babylonGamepads = [];
  75319. this._oneGamepadConnected = false;
  75320. /** @hidden */
  75321. this._isMonitoring = false;
  75322. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  75323. if (!BABYLON.Tools.IsWindowObjectExist()) {
  75324. this._gamepadEventSupported = false;
  75325. }
  75326. else {
  75327. this._gamepadEventSupported = 'GamepadEvent' in window;
  75328. this._gamepadSupport = (navigator.getGamepads ||
  75329. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  75330. }
  75331. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  75332. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  75333. for (var i in _this._babylonGamepads) {
  75334. var gamepad = _this._babylonGamepads[i];
  75335. if (gamepad && gamepad._isConnected) {
  75336. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  75337. }
  75338. }
  75339. });
  75340. this._onGamepadConnectedEvent = function (evt) {
  75341. var gamepad = evt.gamepad;
  75342. if (gamepad.index in _this._babylonGamepads) {
  75343. if (_this._babylonGamepads[gamepad.index].isConnected) {
  75344. return;
  75345. }
  75346. }
  75347. var newGamepad;
  75348. if (_this._babylonGamepads[gamepad.index]) {
  75349. newGamepad = _this._babylonGamepads[gamepad.index];
  75350. newGamepad.browserGamepad = gamepad;
  75351. newGamepad._isConnected = true;
  75352. }
  75353. else {
  75354. newGamepad = _this._addNewGamepad(gamepad);
  75355. }
  75356. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75357. _this._startMonitoringGamepads();
  75358. };
  75359. this._onGamepadDisconnectedEvent = function (evt) {
  75360. var gamepad = evt.gamepad;
  75361. // Remove the gamepad from the list of gamepads to monitor.
  75362. for (var i in _this._babylonGamepads) {
  75363. if (_this._babylonGamepads[i].index === gamepad.index) {
  75364. var disconnectedGamepad = _this._babylonGamepads[i];
  75365. disconnectedGamepad._isConnected = false;
  75366. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  75367. break;
  75368. }
  75369. }
  75370. };
  75371. if (this._gamepadSupport) {
  75372. //first add already-connected gamepads
  75373. this._updateGamepadObjects();
  75374. if (this._babylonGamepads.length) {
  75375. this._startMonitoringGamepads();
  75376. }
  75377. // Checking if the gamepad connected event is supported (like in Firefox)
  75378. if (this._gamepadEventSupported) {
  75379. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  75380. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  75381. }
  75382. else {
  75383. this._startMonitoringGamepads();
  75384. }
  75385. }
  75386. }
  75387. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  75388. get: function () {
  75389. return this._babylonGamepads;
  75390. },
  75391. enumerable: true,
  75392. configurable: true
  75393. });
  75394. GamepadManager.prototype.getGamepadByType = function (type) {
  75395. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  75396. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  75397. var gamepad = _a[_i];
  75398. if (gamepad && gamepad.type === type) {
  75399. return gamepad;
  75400. }
  75401. }
  75402. return null;
  75403. };
  75404. GamepadManager.prototype.dispose = function () {
  75405. if (this._gamepadEventSupported) {
  75406. if (this._onGamepadConnectedEvent) {
  75407. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  75408. }
  75409. if (this._onGamepadDisconnectedEvent) {
  75410. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  75411. }
  75412. this._onGamepadConnectedEvent = null;
  75413. this._onGamepadDisconnectedEvent = null;
  75414. }
  75415. this._babylonGamepads.forEach(function (gamepad) {
  75416. gamepad.dispose();
  75417. });
  75418. this.onGamepadConnectedObservable.clear();
  75419. this.onGamepadDisconnectedObservable.clear();
  75420. this._oneGamepadConnected = false;
  75421. this._stopMonitoringGamepads();
  75422. this._babylonGamepads = [];
  75423. };
  75424. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  75425. if (!this._oneGamepadConnected) {
  75426. this._oneGamepadConnected = true;
  75427. }
  75428. var newGamepad;
  75429. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  75430. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  75431. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  75432. }
  75433. // if pose is supported, use the (WebVR) pose enabled controller
  75434. else if (gamepad.pose) {
  75435. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  75436. }
  75437. else {
  75438. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  75439. }
  75440. this._babylonGamepads[newGamepad.index] = newGamepad;
  75441. return newGamepad;
  75442. };
  75443. GamepadManager.prototype._startMonitoringGamepads = function () {
  75444. if (!this._isMonitoring) {
  75445. this._isMonitoring = true;
  75446. //back-comp
  75447. if (!this._scene) {
  75448. this._checkGamepadsStatus();
  75449. }
  75450. }
  75451. };
  75452. GamepadManager.prototype._stopMonitoringGamepads = function () {
  75453. this._isMonitoring = false;
  75454. };
  75455. /** @hidden */
  75456. GamepadManager.prototype._checkGamepadsStatus = function () {
  75457. var _this = this;
  75458. // Hack to be compatible Chrome
  75459. this._updateGamepadObjects();
  75460. for (var i in this._babylonGamepads) {
  75461. var gamepad = this._babylonGamepads[i];
  75462. if (!gamepad || !gamepad.isConnected) {
  75463. continue;
  75464. }
  75465. gamepad.update();
  75466. }
  75467. if (this._isMonitoring && !this._scene) {
  75468. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  75469. }
  75470. };
  75471. // This function is called only on Chrome, which does not properly support
  75472. // connection/disconnection events and forces you to recopy again the gamepad object
  75473. GamepadManager.prototype._updateGamepadObjects = function () {
  75474. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  75475. for (var i = 0; i < gamepads.length; i++) {
  75476. var gamepad = gamepads[i];
  75477. if (gamepad) {
  75478. if (!this._babylonGamepads[gamepad.index]) {
  75479. var newGamepad = this._addNewGamepad(gamepad);
  75480. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75481. }
  75482. else {
  75483. // Forced to copy again this object for Chrome for unknown reason
  75484. this._babylonGamepads[i].browserGamepad = gamepad;
  75485. if (!this._babylonGamepads[i].isConnected) {
  75486. this._babylonGamepads[i]._isConnected = true;
  75487. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  75488. }
  75489. }
  75490. }
  75491. }
  75492. };
  75493. return GamepadManager;
  75494. }());
  75495. BABYLON.GamepadManager = GamepadManager;
  75496. })(BABYLON || (BABYLON = {}));
  75497. //# sourceMappingURL=babylon.gamepadManager.js.map
  75498. var BABYLON;
  75499. (function (BABYLON) {
  75500. var StickValues = /** @class */ (function () {
  75501. function StickValues(x, y) {
  75502. this.x = x;
  75503. this.y = y;
  75504. }
  75505. return StickValues;
  75506. }());
  75507. BABYLON.StickValues = StickValues;
  75508. var Gamepad = /** @class */ (function () {
  75509. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  75510. if (leftStickX === void 0) { leftStickX = 0; }
  75511. if (leftStickY === void 0) { leftStickY = 1; }
  75512. if (rightStickX === void 0) { rightStickX = 2; }
  75513. if (rightStickY === void 0) { rightStickY = 3; }
  75514. this.id = id;
  75515. this.index = index;
  75516. this.browserGamepad = browserGamepad;
  75517. this._leftStick = { x: 0, y: 0 };
  75518. this._rightStick = { x: 0, y: 0 };
  75519. /** @hidden */
  75520. this._isConnected = true;
  75521. this._invertLeftStickY = false;
  75522. this.type = Gamepad.GAMEPAD;
  75523. this._leftStickAxisX = leftStickX;
  75524. this._leftStickAxisY = leftStickY;
  75525. this._rightStickAxisX = rightStickX;
  75526. this._rightStickAxisY = rightStickY;
  75527. if (this.browserGamepad.axes.length >= 2) {
  75528. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75529. }
  75530. if (this.browserGamepad.axes.length >= 4) {
  75531. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75532. }
  75533. }
  75534. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75535. get: function () {
  75536. return this._isConnected;
  75537. },
  75538. enumerable: true,
  75539. configurable: true
  75540. });
  75541. Gamepad.prototype.onleftstickchanged = function (callback) {
  75542. this._onleftstickchanged = callback;
  75543. };
  75544. Gamepad.prototype.onrightstickchanged = function (callback) {
  75545. this._onrightstickchanged = callback;
  75546. };
  75547. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75548. get: function () {
  75549. return this._leftStick;
  75550. },
  75551. set: function (newValues) {
  75552. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75553. this._onleftstickchanged(newValues);
  75554. }
  75555. this._leftStick = newValues;
  75556. },
  75557. enumerable: true,
  75558. configurable: true
  75559. });
  75560. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75561. get: function () {
  75562. return this._rightStick;
  75563. },
  75564. set: function (newValues) {
  75565. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75566. this._onrightstickchanged(newValues);
  75567. }
  75568. this._rightStick = newValues;
  75569. },
  75570. enumerable: true,
  75571. configurable: true
  75572. });
  75573. Gamepad.prototype.update = function () {
  75574. if (this._leftStick) {
  75575. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75576. if (this._invertLeftStickY) {
  75577. this.leftStick.y *= -1;
  75578. }
  75579. }
  75580. if (this._rightStick) {
  75581. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75582. }
  75583. };
  75584. Gamepad.prototype.dispose = function () {
  75585. };
  75586. Gamepad.GAMEPAD = 0;
  75587. Gamepad.GENERIC = 1;
  75588. Gamepad.XBOX = 2;
  75589. Gamepad.POSE_ENABLED = 3;
  75590. return Gamepad;
  75591. }());
  75592. BABYLON.Gamepad = Gamepad;
  75593. var GenericPad = /** @class */ (function (_super) {
  75594. __extends(GenericPad, _super);
  75595. function GenericPad(id, index, browserGamepad) {
  75596. var _this = _super.call(this, id, index, browserGamepad) || this;
  75597. _this.onButtonDownObservable = new BABYLON.Observable();
  75598. _this.onButtonUpObservable = new BABYLON.Observable();
  75599. _this.type = Gamepad.GENERIC;
  75600. _this._buttons = new Array(browserGamepad.buttons.length);
  75601. return _this;
  75602. }
  75603. GenericPad.prototype.onbuttondown = function (callback) {
  75604. this._onbuttondown = callback;
  75605. };
  75606. GenericPad.prototype.onbuttonup = function (callback) {
  75607. this._onbuttonup = callback;
  75608. };
  75609. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75610. if (newValue !== currentValue) {
  75611. if (newValue === 1) {
  75612. if (this._onbuttondown) {
  75613. this._onbuttondown(buttonIndex);
  75614. }
  75615. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75616. }
  75617. if (newValue === 0) {
  75618. if (this._onbuttonup) {
  75619. this._onbuttonup(buttonIndex);
  75620. }
  75621. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75622. }
  75623. }
  75624. return newValue;
  75625. };
  75626. GenericPad.prototype.update = function () {
  75627. _super.prototype.update.call(this);
  75628. for (var index = 0; index < this._buttons.length; index++) {
  75629. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75630. }
  75631. };
  75632. GenericPad.prototype.dispose = function () {
  75633. _super.prototype.dispose.call(this);
  75634. this.onButtonDownObservable.clear();
  75635. this.onButtonUpObservable.clear();
  75636. };
  75637. return GenericPad;
  75638. }(Gamepad));
  75639. BABYLON.GenericPad = GenericPad;
  75640. })(BABYLON || (BABYLON = {}));
  75641. //# sourceMappingURL=babylon.gamepad.js.map
  75642. var BABYLON;
  75643. (function (BABYLON) {
  75644. /**
  75645. * Defines supported buttons for XBox360 compatible gamepads
  75646. */
  75647. var Xbox360Button;
  75648. (function (Xbox360Button) {
  75649. /** A */
  75650. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75651. /** B */
  75652. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75653. /** X */
  75654. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75655. /** Y */
  75656. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75657. /** Start */
  75658. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75659. /** Back */
  75660. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75661. /** Left button */
  75662. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75663. /** Right button */
  75664. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75665. /** Left stick */
  75666. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75667. /** Right stick */
  75668. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75669. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75670. /** Defines values for XBox360 DPad */
  75671. var Xbox360Dpad;
  75672. (function (Xbox360Dpad) {
  75673. /** Up */
  75674. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75675. /** Down */
  75676. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75677. /** Left */
  75678. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75679. /** Right */
  75680. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75681. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75682. /**
  75683. * Defines a XBox360 gamepad
  75684. */
  75685. var Xbox360Pad = /** @class */ (function (_super) {
  75686. __extends(Xbox360Pad, _super);
  75687. /**
  75688. * Creates a new XBox360 gamepad object
  75689. * @param id defines the id of this gamepad
  75690. * @param index defines its index
  75691. * @param gamepad defines the internal HTML gamepad object
  75692. * @param xboxOne defines if it is a XBox One gamepad
  75693. */
  75694. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75695. if (xboxOne === void 0) { xboxOne = false; }
  75696. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75697. _this._leftTrigger = 0;
  75698. _this._rightTrigger = 0;
  75699. /** Observable raised when a button is pressed */
  75700. _this.onButtonDownObservable = new BABYLON.Observable();
  75701. /** Observable raised when a button is released */
  75702. _this.onButtonUpObservable = new BABYLON.Observable();
  75703. /** Observable raised when a pad is pressed */
  75704. _this.onPadDownObservable = new BABYLON.Observable();
  75705. /** Observable raised when a pad is released */
  75706. _this.onPadUpObservable = new BABYLON.Observable();
  75707. _this._buttonA = 0;
  75708. _this._buttonB = 0;
  75709. _this._buttonX = 0;
  75710. _this._buttonY = 0;
  75711. _this._buttonBack = 0;
  75712. _this._buttonStart = 0;
  75713. _this._buttonLB = 0;
  75714. _this._buttonRB = 0;
  75715. _this._buttonLeftStick = 0;
  75716. _this._buttonRightStick = 0;
  75717. _this._dPadUp = 0;
  75718. _this._dPadDown = 0;
  75719. _this._dPadLeft = 0;
  75720. _this._dPadRight = 0;
  75721. _this._isXboxOnePad = false;
  75722. _this.type = BABYLON.Gamepad.XBOX;
  75723. _this._isXboxOnePad = xboxOne;
  75724. return _this;
  75725. }
  75726. /**
  75727. * Defines the callback to call when left trigger is pressed
  75728. * @param callback defines the callback to use
  75729. */
  75730. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75731. this._onlefttriggerchanged = callback;
  75732. };
  75733. /**
  75734. * Defines the callback to call when right trigger is pressed
  75735. * @param callback defines the callback to use
  75736. */
  75737. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75738. this._onrighttriggerchanged = callback;
  75739. };
  75740. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75741. /**
  75742. * Gets or sets left trigger value
  75743. */
  75744. get: function () {
  75745. return this._leftTrigger;
  75746. },
  75747. set: function (newValue) {
  75748. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75749. this._onlefttriggerchanged(newValue);
  75750. }
  75751. this._leftTrigger = newValue;
  75752. },
  75753. enumerable: true,
  75754. configurable: true
  75755. });
  75756. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75757. /**
  75758. * Gets or sets right trigger value
  75759. */
  75760. get: function () {
  75761. return this._rightTrigger;
  75762. },
  75763. set: function (newValue) {
  75764. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75765. this._onrighttriggerchanged(newValue);
  75766. }
  75767. this._rightTrigger = newValue;
  75768. },
  75769. enumerable: true,
  75770. configurable: true
  75771. });
  75772. /**
  75773. * Defines the callback to call when a button is pressed
  75774. * @param callback defines the callback to use
  75775. */
  75776. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75777. this._onbuttondown = callback;
  75778. };
  75779. /**
  75780. * Defines the callback to call when a button is released
  75781. * @param callback defines the callback to use
  75782. */
  75783. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75784. this._onbuttonup = callback;
  75785. };
  75786. /**
  75787. * Defines the callback to call when a pad is pressed
  75788. * @param callback defines the callback to use
  75789. */
  75790. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75791. this._ondpaddown = callback;
  75792. };
  75793. /**
  75794. * Defines the callback to call when a pad is released
  75795. * @param callback defines the callback to use
  75796. */
  75797. Xbox360Pad.prototype.ondpadup = function (callback) {
  75798. this._ondpadup = callback;
  75799. };
  75800. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75801. if (newValue !== currentValue) {
  75802. if (newValue === 1) {
  75803. if (this._onbuttondown) {
  75804. this._onbuttondown(buttonType);
  75805. }
  75806. this.onButtonDownObservable.notifyObservers(buttonType);
  75807. }
  75808. if (newValue === 0) {
  75809. if (this._onbuttonup) {
  75810. this._onbuttonup(buttonType);
  75811. }
  75812. this.onButtonUpObservable.notifyObservers(buttonType);
  75813. }
  75814. }
  75815. return newValue;
  75816. };
  75817. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75818. if (newValue !== currentValue) {
  75819. if (newValue === 1) {
  75820. if (this._ondpaddown) {
  75821. this._ondpaddown(buttonType);
  75822. }
  75823. this.onPadDownObservable.notifyObservers(buttonType);
  75824. }
  75825. if (newValue === 0) {
  75826. if (this._ondpadup) {
  75827. this._ondpadup(buttonType);
  75828. }
  75829. this.onPadUpObservable.notifyObservers(buttonType);
  75830. }
  75831. }
  75832. return newValue;
  75833. };
  75834. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75835. /** Gets or sets value of A button */
  75836. get: function () {
  75837. return this._buttonA;
  75838. },
  75839. set: function (value) {
  75840. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75841. },
  75842. enumerable: true,
  75843. configurable: true
  75844. });
  75845. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75846. /** Gets or sets value of B button */
  75847. get: function () {
  75848. return this._buttonB;
  75849. },
  75850. set: function (value) {
  75851. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75852. },
  75853. enumerable: true,
  75854. configurable: true
  75855. });
  75856. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75857. /** Gets or sets value of X button */
  75858. get: function () {
  75859. return this._buttonX;
  75860. },
  75861. set: function (value) {
  75862. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75863. },
  75864. enumerable: true,
  75865. configurable: true
  75866. });
  75867. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75868. /** Gets or sets value of Y button */
  75869. get: function () {
  75870. return this._buttonY;
  75871. },
  75872. set: function (value) {
  75873. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75879. /** Gets or sets value of Start button */
  75880. get: function () {
  75881. return this._buttonStart;
  75882. },
  75883. set: function (value) {
  75884. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75890. /** Gets or sets value of Back button */
  75891. get: function () {
  75892. return this._buttonBack;
  75893. },
  75894. set: function (value) {
  75895. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75896. },
  75897. enumerable: true,
  75898. configurable: true
  75899. });
  75900. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75901. /** Gets or sets value of Left button */
  75902. get: function () {
  75903. return this._buttonLB;
  75904. },
  75905. set: function (value) {
  75906. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75907. },
  75908. enumerable: true,
  75909. configurable: true
  75910. });
  75911. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75912. /** Gets or sets value of Right button */
  75913. get: function () {
  75914. return this._buttonRB;
  75915. },
  75916. set: function (value) {
  75917. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75918. },
  75919. enumerable: true,
  75920. configurable: true
  75921. });
  75922. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75923. /** Gets or sets value of left stick */
  75924. get: function () {
  75925. return this._buttonLeftStick;
  75926. },
  75927. set: function (value) {
  75928. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75929. },
  75930. enumerable: true,
  75931. configurable: true
  75932. });
  75933. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75934. /** Gets or sets value of right stick */
  75935. get: function () {
  75936. return this._buttonRightStick;
  75937. },
  75938. set: function (value) {
  75939. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75940. },
  75941. enumerable: true,
  75942. configurable: true
  75943. });
  75944. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75945. /** Gets or sets value of DPad up */
  75946. get: function () {
  75947. return this._dPadUp;
  75948. },
  75949. set: function (value) {
  75950. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75951. },
  75952. enumerable: true,
  75953. configurable: true
  75954. });
  75955. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75956. /** Gets or sets value of DPad down */
  75957. get: function () {
  75958. return this._dPadDown;
  75959. },
  75960. set: function (value) {
  75961. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75962. },
  75963. enumerable: true,
  75964. configurable: true
  75965. });
  75966. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75967. /** Gets or sets value of DPad left */
  75968. get: function () {
  75969. return this._dPadLeft;
  75970. },
  75971. set: function (value) {
  75972. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75973. },
  75974. enumerable: true,
  75975. configurable: true
  75976. });
  75977. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75978. /** Gets or sets value of DPad right */
  75979. get: function () {
  75980. return this._dPadRight;
  75981. },
  75982. set: function (value) {
  75983. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75984. },
  75985. enumerable: true,
  75986. configurable: true
  75987. });
  75988. /**
  75989. * Force the gamepad to synchronize with device values
  75990. */
  75991. Xbox360Pad.prototype.update = function () {
  75992. _super.prototype.update.call(this);
  75993. if (this._isXboxOnePad) {
  75994. this.buttonA = this.browserGamepad.buttons[0].value;
  75995. this.buttonB = this.browserGamepad.buttons[1].value;
  75996. this.buttonX = this.browserGamepad.buttons[2].value;
  75997. this.buttonY = this.browserGamepad.buttons[3].value;
  75998. this.buttonLB = this.browserGamepad.buttons[4].value;
  75999. this.buttonRB = this.browserGamepad.buttons[5].value;
  76000. this.leftTrigger = this.browserGamepad.axes[2];
  76001. this.rightTrigger = this.browserGamepad.axes[5];
  76002. this.buttonBack = this.browserGamepad.buttons[9].value;
  76003. this.buttonStart = this.browserGamepad.buttons[8].value;
  76004. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  76005. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  76006. this.dPadUp = this.browserGamepad.buttons[11].value;
  76007. this.dPadDown = this.browserGamepad.buttons[12].value;
  76008. this.dPadLeft = this.browserGamepad.buttons[13].value;
  76009. this.dPadRight = this.browserGamepad.buttons[14].value;
  76010. }
  76011. else {
  76012. this.buttonA = this.browserGamepad.buttons[0].value;
  76013. this.buttonB = this.browserGamepad.buttons[1].value;
  76014. this.buttonX = this.browserGamepad.buttons[2].value;
  76015. this.buttonY = this.browserGamepad.buttons[3].value;
  76016. this.buttonLB = this.browserGamepad.buttons[4].value;
  76017. this.buttonRB = this.browserGamepad.buttons[5].value;
  76018. this.leftTrigger = this.browserGamepad.buttons[6].value;
  76019. this.rightTrigger = this.browserGamepad.buttons[7].value;
  76020. this.buttonBack = this.browserGamepad.buttons[8].value;
  76021. this.buttonStart = this.browserGamepad.buttons[9].value;
  76022. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  76023. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  76024. this.dPadUp = this.browserGamepad.buttons[12].value;
  76025. this.dPadDown = this.browserGamepad.buttons[13].value;
  76026. this.dPadLeft = this.browserGamepad.buttons[14].value;
  76027. this.dPadRight = this.browserGamepad.buttons[15].value;
  76028. }
  76029. };
  76030. Xbox360Pad.prototype.dispose = function () {
  76031. _super.prototype.dispose.call(this);
  76032. this.onButtonDownObservable.clear();
  76033. this.onButtonUpObservable.clear();
  76034. this.onPadDownObservable.clear();
  76035. this.onPadUpObservable.clear();
  76036. };
  76037. return Xbox360Pad;
  76038. }(BABYLON.Gamepad));
  76039. BABYLON.Xbox360Pad = Xbox360Pad;
  76040. })(BABYLON || (BABYLON = {}));
  76041. //# sourceMappingURL=babylon.xboxGamepad.js.map
  76042. var BABYLON;
  76043. (function (BABYLON) {
  76044. /**
  76045. * Defines the types of pose enabled controllers that are supported
  76046. */
  76047. var PoseEnabledControllerType;
  76048. (function (PoseEnabledControllerType) {
  76049. /**
  76050. * HTC Vive
  76051. */
  76052. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  76053. /**
  76054. * Oculus Rift
  76055. */
  76056. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  76057. /**
  76058. * Windows mixed reality
  76059. */
  76060. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  76061. /**
  76062. * Samsung gear VR
  76063. */
  76064. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  76065. /**
  76066. * Google Daydream
  76067. */
  76068. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  76069. /**
  76070. * Generic
  76071. */
  76072. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  76073. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  76074. /**
  76075. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  76076. */
  76077. var PoseEnabledControllerHelper = /** @class */ (function () {
  76078. function PoseEnabledControllerHelper() {
  76079. }
  76080. /**
  76081. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  76082. * @param vrGamepad the gamepad to initialized
  76083. * @returns a vr controller of the type the gamepad identified as
  76084. */
  76085. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  76086. // Oculus Touch
  76087. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  76088. return new BABYLON.OculusTouchController(vrGamepad);
  76089. }
  76090. // Windows Mixed Reality controllers
  76091. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  76092. return new BABYLON.WindowsMotionController(vrGamepad);
  76093. }
  76094. // HTC Vive
  76095. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  76096. return new BABYLON.ViveController(vrGamepad);
  76097. }
  76098. // Samsung/Oculus Gear VR or Oculus Go
  76099. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  76100. return new BABYLON.GearVRController(vrGamepad);
  76101. }
  76102. // Google Daydream
  76103. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  76104. return new BABYLON.DaydreamController(vrGamepad);
  76105. }
  76106. // Generic
  76107. else {
  76108. return new BABYLON.GenericController(vrGamepad);
  76109. }
  76110. };
  76111. return PoseEnabledControllerHelper;
  76112. }());
  76113. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  76114. /**
  76115. * Defines the PoseEnabledController object that contains state of a vr capable controller
  76116. */
  76117. var PoseEnabledController = /** @class */ (function (_super) {
  76118. __extends(PoseEnabledController, _super);
  76119. /**
  76120. * Creates a new PoseEnabledController from a gamepad
  76121. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  76122. */
  76123. function PoseEnabledController(browserGamepad) {
  76124. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  76125. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  76126. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  76127. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  76128. /**
  76129. * The device position in babylon space
  76130. */
  76131. _this.devicePosition = BABYLON.Vector3.Zero();
  76132. /**
  76133. * The device rotation in babylon space
  76134. */
  76135. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  76136. /**
  76137. * The scale factor of the device in babylon space
  76138. */
  76139. _this.deviceScaleFactor = 1;
  76140. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  76141. /**
  76142. * Internal, matrix used to convert room space to babylon space
  76143. * @hidden
  76144. */
  76145. _this._deviceToWorld = BABYLON.Matrix.Identity();
  76146. /**
  76147. * Node to be used when casting a ray from the controller
  76148. * @hidden
  76149. */
  76150. _this._pointingPoseNode = null;
  76151. _this._workingMatrix = BABYLON.Matrix.Identity();
  76152. /**
  76153. * @hidden
  76154. */
  76155. _this._meshAttachedObservable = new BABYLON.Observable();
  76156. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  76157. _this.controllerType = PoseEnabledControllerType.GENERIC;
  76158. _this.position = BABYLON.Vector3.Zero();
  76159. _this.rotationQuaternion = new BABYLON.Quaternion();
  76160. _this._calculatedPosition = BABYLON.Vector3.Zero();
  76161. _this._calculatedRotation = new BABYLON.Quaternion();
  76162. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  76163. return _this;
  76164. }
  76165. /**
  76166. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  76167. */
  76168. PoseEnabledController.prototype.update = function () {
  76169. _super.prototype.update.call(this);
  76170. this._updatePoseAndMesh();
  76171. };
  76172. /**
  76173. * Updates only the pose device and mesh without doing any button event checking
  76174. */
  76175. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  76176. var pose = this.browserGamepad.pose;
  76177. this.updateFromDevice(pose);
  76178. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  76179. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  76180. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  76181. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  76182. if (this._mesh) {
  76183. this._mesh.position.copyFrom(this.devicePosition);
  76184. if (this._mesh.rotationQuaternion) {
  76185. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  76186. }
  76187. }
  76188. };
  76189. /**
  76190. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76191. * @param poseData raw pose fromthe device
  76192. */
  76193. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  76194. if (poseData) {
  76195. this.rawPose = poseData;
  76196. if (poseData.position) {
  76197. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  76198. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  76199. this._deviceRoomPosition.z *= -1;
  76200. }
  76201. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  76202. this._calculatedPosition.addInPlace(this.position);
  76203. }
  76204. var pose = this.rawPose;
  76205. if (poseData.orientation && pose.orientation) {
  76206. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  76207. if (this._mesh) {
  76208. if (this._mesh.getScene().useRightHandedSystem) {
  76209. this._deviceRoomRotationQuaternion.z *= -1;
  76210. this._deviceRoomRotationQuaternion.w *= -1;
  76211. }
  76212. else {
  76213. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  76214. }
  76215. }
  76216. // if the camera is set, rotate to the camera's rotation
  76217. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  76218. }
  76219. }
  76220. };
  76221. /**
  76222. * Attaches a mesh to the controller
  76223. * @param mesh the mesh to be attached
  76224. */
  76225. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  76226. if (this._mesh) {
  76227. this._mesh.parent = null;
  76228. }
  76229. this._mesh = mesh;
  76230. if (this._poseControlledCamera) {
  76231. this._mesh.parent = this._poseControlledCamera;
  76232. }
  76233. if (!this._mesh.rotationQuaternion) {
  76234. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  76235. }
  76236. // 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
  76237. this._updatePoseAndMesh();
  76238. if (this._pointingPoseNode) {
  76239. var parents = [];
  76240. var obj = this._pointingPoseNode;
  76241. while (obj.parent) {
  76242. parents.push(obj.parent);
  76243. obj = obj.parent;
  76244. }
  76245. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  76246. }
  76247. this._meshAttachedObservable.notifyObservers(mesh);
  76248. };
  76249. /**
  76250. * Attaches the controllers mesh to a camera
  76251. * @param camera the camera the mesh should be attached to
  76252. */
  76253. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  76254. this._poseControlledCamera = camera;
  76255. if (this._mesh) {
  76256. this._mesh.parent = this._poseControlledCamera;
  76257. }
  76258. };
  76259. /**
  76260. * Disposes of the controller
  76261. */
  76262. PoseEnabledController.prototype.dispose = function () {
  76263. if (this._mesh) {
  76264. this._mesh.dispose();
  76265. }
  76266. this._mesh = null;
  76267. _super.prototype.dispose.call(this);
  76268. };
  76269. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  76270. /**
  76271. * The mesh that is attached to the controller
  76272. */
  76273. get: function () {
  76274. return this._mesh;
  76275. },
  76276. enumerable: true,
  76277. configurable: true
  76278. });
  76279. /**
  76280. * Gets the ray of the controller in the direction the controller is pointing
  76281. * @param length the length the resulting ray should be
  76282. * @returns a ray in the direction the controller is pointing
  76283. */
  76284. PoseEnabledController.prototype.getForwardRay = function (length) {
  76285. if (length === void 0) { length = 100; }
  76286. if (!this.mesh) {
  76287. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  76288. }
  76289. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  76290. var origin = m.getTranslation();
  76291. var forward = new BABYLON.Vector3(0, 0, -1);
  76292. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76293. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76294. return new BABYLON.Ray(origin, direction, length);
  76295. };
  76296. /**
  76297. * Name of the child mesh that can be used to cast a ray from the controller
  76298. */
  76299. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  76300. return PoseEnabledController;
  76301. }(BABYLON.Gamepad));
  76302. BABYLON.PoseEnabledController = PoseEnabledController;
  76303. })(BABYLON || (BABYLON = {}));
  76304. //# sourceMappingURL=babylon.poseEnabledController.js.map
  76305. var BABYLON;
  76306. (function (BABYLON) {
  76307. /**
  76308. * Defines the WebVRController object that represents controllers tracked in 3D space
  76309. */
  76310. var WebVRController = /** @class */ (function (_super) {
  76311. __extends(WebVRController, _super);
  76312. /**
  76313. * Creates a new WebVRController from a gamepad
  76314. * @param vrGamepad the gamepad that the WebVRController should be created from
  76315. */
  76316. function WebVRController(vrGamepad) {
  76317. var _this = _super.call(this, vrGamepad) || this;
  76318. // Observables
  76319. /**
  76320. * Fired when the trigger state has changed
  76321. */
  76322. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  76323. /**
  76324. * Fired when the main button state has changed
  76325. */
  76326. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  76327. /**
  76328. * Fired when the secondary button state has changed
  76329. */
  76330. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  76331. /**
  76332. * Fired when the pad state has changed
  76333. */
  76334. _this.onPadStateChangedObservable = new BABYLON.Observable();
  76335. /**
  76336. * Fired when controllers stick values have changed
  76337. */
  76338. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  76339. /**
  76340. * X and Y axis corrisponding to the controllers joystick
  76341. */
  76342. _this.pad = { x: 0, y: 0 };
  76343. // avoid GC, store state in a tmp object
  76344. _this._changes = {
  76345. pressChanged: false,
  76346. touchChanged: false,
  76347. valueChanged: false,
  76348. changed: false
  76349. };
  76350. _this._buttons = new Array(vrGamepad.buttons.length);
  76351. _this.hand = vrGamepad.hand;
  76352. return _this;
  76353. }
  76354. /**
  76355. * Fired when a controller button's state has changed
  76356. * @param callback the callback containing the button that was modified
  76357. */
  76358. WebVRController.prototype.onButtonStateChange = function (callback) {
  76359. this._onButtonStateChange = callback;
  76360. };
  76361. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  76362. /**
  76363. * The default controller model for the controller
  76364. */
  76365. get: function () {
  76366. return this._defaultModel;
  76367. },
  76368. enumerable: true,
  76369. configurable: true
  76370. });
  76371. /**
  76372. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  76373. */
  76374. WebVRController.prototype.update = function () {
  76375. _super.prototype.update.call(this);
  76376. for (var index = 0; index < this._buttons.length; index++) {
  76377. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  76378. }
  76379. ;
  76380. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  76381. this.pad.x = this.leftStick.x;
  76382. this.pad.y = this.leftStick.y;
  76383. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  76384. }
  76385. };
  76386. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  76387. if (!newState) {
  76388. newState = {
  76389. pressed: false,
  76390. touched: false,
  76391. value: 0
  76392. };
  76393. }
  76394. if (!currentState) {
  76395. this._buttons[buttonIndex] = {
  76396. pressed: newState.pressed,
  76397. touched: newState.touched,
  76398. value: newState.value
  76399. };
  76400. return;
  76401. }
  76402. this._checkChanges(newState, currentState);
  76403. if (this._changes.changed) {
  76404. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  76405. this._handleButtonChange(buttonIndex, newState, this._changes);
  76406. }
  76407. this._buttons[buttonIndex].pressed = newState.pressed;
  76408. this._buttons[buttonIndex].touched = newState.touched;
  76409. // oculus triggers are never 0, thou not touched.
  76410. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  76411. };
  76412. WebVRController.prototype._checkChanges = function (newState, currentState) {
  76413. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  76414. this._changes.touchChanged = newState.touched !== currentState.touched;
  76415. this._changes.valueChanged = newState.value !== currentState.value;
  76416. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  76417. return this._changes;
  76418. };
  76419. /**
  76420. * Disposes of th webVRCOntroller
  76421. */
  76422. WebVRController.prototype.dispose = function () {
  76423. _super.prototype.dispose.call(this);
  76424. this.onTriggerStateChangedObservable.clear();
  76425. this.onMainButtonStateChangedObservable.clear();
  76426. this.onSecondaryButtonStateChangedObservable.clear();
  76427. this.onPadStateChangedObservable.clear();
  76428. this.onPadValuesChangedObservable.clear();
  76429. };
  76430. return WebVRController;
  76431. }(BABYLON.PoseEnabledController));
  76432. BABYLON.WebVRController = WebVRController;
  76433. })(BABYLON || (BABYLON = {}));
  76434. //# sourceMappingURL=babylon.webVRController.js.map
  76435. var BABYLON;
  76436. (function (BABYLON) {
  76437. /**
  76438. * Oculus Touch Controller
  76439. */
  76440. var OculusTouchController = /** @class */ (function (_super) {
  76441. __extends(OculusTouchController, _super);
  76442. /**
  76443. * Creates a new OculusTouchController from a gamepad
  76444. * @param vrGamepad the gamepad that the controller should be created from
  76445. */
  76446. function OculusTouchController(vrGamepad) {
  76447. var _this = _super.call(this, vrGamepad) || this;
  76448. /**
  76449. * Fired when the secondary trigger on this controller is modified
  76450. */
  76451. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  76452. /**
  76453. * Fired when the thumb rest on this controller is modified
  76454. */
  76455. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  76456. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  76457. return _this;
  76458. }
  76459. /**
  76460. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76461. * @param scene scene in which to add meshes
  76462. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76463. */
  76464. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76465. var _this = this;
  76466. var meshName;
  76467. // Hand
  76468. if (this.hand === 'left') {
  76469. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  76470. }
  76471. else { // Right is the default if no hand is specified
  76472. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  76473. }
  76474. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  76475. /*
  76476. Parent Mesh name: oculus_touch_left
  76477. - body
  76478. - trigger
  76479. - thumbstick
  76480. - grip
  76481. - button_y
  76482. - button_x
  76483. - button_enter
  76484. */
  76485. _this._defaultModel = newMeshes[1];
  76486. _this.attachToMesh(_this._defaultModel);
  76487. if (meshLoaded) {
  76488. meshLoaded(_this._defaultModel);
  76489. }
  76490. });
  76491. };
  76492. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  76493. /**
  76494. * Fired when the A button on this controller is modified
  76495. */
  76496. get: function () {
  76497. if (this.hand === 'right') {
  76498. return this.onMainButtonStateChangedObservable;
  76499. }
  76500. else {
  76501. throw new Error('No A button on left hand');
  76502. }
  76503. },
  76504. enumerable: true,
  76505. configurable: true
  76506. });
  76507. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  76508. /**
  76509. * Fired when the B button on this controller is modified
  76510. */
  76511. get: function () {
  76512. if (this.hand === 'right') {
  76513. return this.onSecondaryButtonStateChangedObservable;
  76514. }
  76515. else {
  76516. throw new Error('No B button on left hand');
  76517. }
  76518. },
  76519. enumerable: true,
  76520. configurable: true
  76521. });
  76522. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76523. /**
  76524. * Fired when the X button on this controller is modified
  76525. */
  76526. get: function () {
  76527. if (this.hand === 'left') {
  76528. return this.onMainButtonStateChangedObservable;
  76529. }
  76530. else {
  76531. throw new Error('No X button on right hand');
  76532. }
  76533. },
  76534. enumerable: true,
  76535. configurable: true
  76536. });
  76537. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76538. /**
  76539. * Fired when the Y button on this controller is modified
  76540. */
  76541. get: function () {
  76542. if (this.hand === 'left') {
  76543. return this.onSecondaryButtonStateChangedObservable;
  76544. }
  76545. else {
  76546. throw new Error('No Y button on right hand');
  76547. }
  76548. },
  76549. enumerable: true,
  76550. configurable: true
  76551. });
  76552. /**
  76553. * Called once for each button that changed state since the last frame
  76554. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76555. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76556. * 2) secondary trigger (same)
  76557. * 3) A (right) X (left), touch, pressed = value
  76558. * 4) B / Y
  76559. * 5) thumb rest
  76560. * @param buttonIdx Which button index changed
  76561. * @param state New state of the button
  76562. * @param changes Which properties on the state changed since last frame
  76563. */
  76564. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76565. var notifyObject = state; //{ state: state, changes: changes };
  76566. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76567. switch (buttonIdx) {
  76568. case 0:
  76569. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76570. return;
  76571. case 1: // index trigger
  76572. if (this._defaultModel) {
  76573. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76574. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76575. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76576. }
  76577. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76578. return;
  76579. case 2: // secondary trigger
  76580. if (this._defaultModel) {
  76581. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76582. }
  76583. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76584. return;
  76585. case 3:
  76586. if (this._defaultModel) {
  76587. if (notifyObject.pressed) {
  76588. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76589. }
  76590. else {
  76591. (this._defaultModel.getChildren()[1]).position.y = 0;
  76592. }
  76593. }
  76594. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76595. return;
  76596. case 4:
  76597. if (this._defaultModel) {
  76598. if (notifyObject.pressed) {
  76599. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76600. }
  76601. else {
  76602. (this._defaultModel.getChildren()[2]).position.y = 0;
  76603. }
  76604. }
  76605. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76606. return;
  76607. case 5:
  76608. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76609. return;
  76610. }
  76611. };
  76612. /**
  76613. * Base Url for the controller model.
  76614. */
  76615. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76616. /**
  76617. * File name for the left controller model.
  76618. */
  76619. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76620. /**
  76621. * File name for the right controller model.
  76622. */
  76623. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76624. return OculusTouchController;
  76625. }(BABYLON.WebVRController));
  76626. BABYLON.OculusTouchController = OculusTouchController;
  76627. })(BABYLON || (BABYLON = {}));
  76628. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76629. var BABYLON;
  76630. (function (BABYLON) {
  76631. /**
  76632. * Vive Controller
  76633. */
  76634. var ViveController = /** @class */ (function (_super) {
  76635. __extends(ViveController, _super);
  76636. /**
  76637. * Creates a new ViveController from a gamepad
  76638. * @param vrGamepad the gamepad that the controller should be created from
  76639. */
  76640. function ViveController(vrGamepad) {
  76641. var _this = _super.call(this, vrGamepad) || this;
  76642. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76643. _this._invertLeftStickY = true;
  76644. return _this;
  76645. }
  76646. /**
  76647. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76648. * @param scene scene in which to add meshes
  76649. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76650. */
  76651. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76652. var _this = this;
  76653. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76654. /*
  76655. Parent Mesh name: ViveWand
  76656. - body
  76657. - r_gripper
  76658. - l_gripper
  76659. - menu_button
  76660. - system_button
  76661. - trackpad
  76662. - trigger
  76663. - LED
  76664. */
  76665. _this._defaultModel = newMeshes[1];
  76666. _this.attachToMesh(_this._defaultModel);
  76667. if (meshLoaded) {
  76668. meshLoaded(_this._defaultModel);
  76669. }
  76670. });
  76671. };
  76672. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76673. /**
  76674. * Fired when the left button on this controller is modified
  76675. */
  76676. get: function () {
  76677. return this.onMainButtonStateChangedObservable;
  76678. },
  76679. enumerable: true,
  76680. configurable: true
  76681. });
  76682. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76683. /**
  76684. * Fired when the right button on this controller is modified
  76685. */
  76686. get: function () {
  76687. return this.onMainButtonStateChangedObservable;
  76688. },
  76689. enumerable: true,
  76690. configurable: true
  76691. });
  76692. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76693. /**
  76694. * Fired when the menu button on this controller is modified
  76695. */
  76696. get: function () {
  76697. return this.onSecondaryButtonStateChangedObservable;
  76698. },
  76699. enumerable: true,
  76700. configurable: true
  76701. });
  76702. /**
  76703. * Called once for each button that changed state since the last frame
  76704. * Vive mapping:
  76705. * 0: touchpad
  76706. * 1: trigger
  76707. * 2: left AND right buttons
  76708. * 3: menu button
  76709. * @param buttonIdx Which button index changed
  76710. * @param state New state of the button
  76711. * @param changes Which properties on the state changed since last frame
  76712. */
  76713. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76714. var notifyObject = state; //{ state: state, changes: changes };
  76715. switch (buttonIdx) {
  76716. case 0:
  76717. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76718. return;
  76719. case 1: // index trigger
  76720. if (this._defaultModel) {
  76721. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76722. }
  76723. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76724. return;
  76725. case 2: // left AND right button
  76726. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76727. return;
  76728. case 3:
  76729. if (this._defaultModel) {
  76730. if (notifyObject.pressed) {
  76731. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76732. }
  76733. else {
  76734. (this._defaultModel.getChildren()[2]).position.y = 0;
  76735. }
  76736. }
  76737. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76738. return;
  76739. }
  76740. };
  76741. /**
  76742. * Base Url for the controller model.
  76743. */
  76744. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76745. /**
  76746. * File name for the controller model.
  76747. */
  76748. ViveController.MODEL_FILENAME = 'wand.babylon';
  76749. return ViveController;
  76750. }(BABYLON.WebVRController));
  76751. BABYLON.ViveController = ViveController;
  76752. })(BABYLON || (BABYLON = {}));
  76753. //# sourceMappingURL=babylon.viveController.js.map
  76754. var BABYLON;
  76755. (function (BABYLON) {
  76756. /**
  76757. * Generic Controller
  76758. */
  76759. var GenericController = /** @class */ (function (_super) {
  76760. __extends(GenericController, _super);
  76761. /**
  76762. * Creates a new GenericController from a gamepad
  76763. * @param vrGamepad the gamepad that the controller should be created from
  76764. */
  76765. function GenericController(vrGamepad) {
  76766. return _super.call(this, vrGamepad) || this;
  76767. }
  76768. /**
  76769. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76770. * @param scene scene in which to add meshes
  76771. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76772. */
  76773. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76774. var _this = this;
  76775. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76776. _this._defaultModel = newMeshes[1];
  76777. _this.attachToMesh(_this._defaultModel);
  76778. if (meshLoaded) {
  76779. meshLoaded(_this._defaultModel);
  76780. }
  76781. });
  76782. };
  76783. /**
  76784. * Called once for each button that changed state since the last frame
  76785. * @param buttonIdx Which button index changed
  76786. * @param state New state of the button
  76787. * @param changes Which properties on the state changed since last frame
  76788. */
  76789. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76790. console.log("Button id: " + buttonIdx + "state: ");
  76791. console.dir(state);
  76792. };
  76793. /**
  76794. * Base Url for the controller model.
  76795. */
  76796. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76797. /**
  76798. * File name for the controller model.
  76799. */
  76800. GenericController.MODEL_FILENAME = 'generic.babylon';
  76801. return GenericController;
  76802. }(BABYLON.WebVRController));
  76803. BABYLON.GenericController = GenericController;
  76804. })(BABYLON || (BABYLON = {}));
  76805. //# sourceMappingURL=babylon.genericController.js.map
  76806. var BABYLON;
  76807. (function (BABYLON) {
  76808. /**
  76809. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76810. */
  76811. var LoadedMeshInfo = /** @class */ (function () {
  76812. function LoadedMeshInfo() {
  76813. /**
  76814. * Map of the button meshes contained in the controller
  76815. */
  76816. this.buttonMeshes = {};
  76817. /**
  76818. * Map of the axis meshes contained in the controller
  76819. */
  76820. this.axisMeshes = {};
  76821. }
  76822. return LoadedMeshInfo;
  76823. }());
  76824. /**
  76825. * Defines the WindowsMotionController object that the state of the windows motion controller
  76826. */
  76827. var WindowsMotionController = /** @class */ (function (_super) {
  76828. __extends(WindowsMotionController, _super);
  76829. /**
  76830. * Creates a new WindowsMotionController from a gamepad
  76831. * @param vrGamepad the gamepad that the controller should be created from
  76832. */
  76833. function WindowsMotionController(vrGamepad) {
  76834. var _this = _super.call(this, vrGamepad) || this;
  76835. _this._mapping = {
  76836. // Semantic button names
  76837. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76838. // A mapping of the button name to glTF model node name
  76839. // that should be transformed by button value.
  76840. buttonMeshNames: {
  76841. 'trigger': 'SELECT',
  76842. 'menu': 'MENU',
  76843. 'grip': 'GRASP',
  76844. 'thumbstick': 'THUMBSTICK_PRESS',
  76845. 'trackpad': 'TOUCHPAD_PRESS'
  76846. },
  76847. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76848. buttonObservableNames: {
  76849. 'trigger': 'onTriggerStateChangedObservable',
  76850. 'menu': 'onSecondaryButtonStateChangedObservable',
  76851. 'grip': 'onMainButtonStateChangedObservable',
  76852. 'thumbstick': 'onPadStateChangedObservable',
  76853. 'trackpad': 'onTrackpadChangedObservable'
  76854. },
  76855. // A mapping of the axis name to glTF model node name
  76856. // that should be transformed by axis value.
  76857. // This array mirrors the browserGamepad.axes array, such that
  76858. // the mesh corresponding to axis 0 is in this array index 0.
  76859. axisMeshNames: [
  76860. 'THUMBSTICK_X',
  76861. 'THUMBSTICK_Y',
  76862. 'TOUCHPAD_TOUCH_X',
  76863. 'TOUCHPAD_TOUCH_Y'
  76864. ],
  76865. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76866. };
  76867. /**
  76868. * Fired when the trackpad on this controller is clicked
  76869. */
  76870. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76871. /**
  76872. * Fired when the trackpad on this controller is modified
  76873. */
  76874. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76875. /**
  76876. * The current x and y values of this controller's trackpad
  76877. */
  76878. _this.trackpad = { x: 0, y: 0 };
  76879. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76880. _this._loadedMeshInfo = null;
  76881. return _this;
  76882. }
  76883. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76884. /**
  76885. * Fired when the trigger on this controller is modified
  76886. */
  76887. get: function () {
  76888. return this.onTriggerStateChangedObservable;
  76889. },
  76890. enumerable: true,
  76891. configurable: true
  76892. });
  76893. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76894. /**
  76895. * Fired when the menu button on this controller is modified
  76896. */
  76897. get: function () {
  76898. return this.onSecondaryButtonStateChangedObservable;
  76899. },
  76900. enumerable: true,
  76901. configurable: true
  76902. });
  76903. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76904. /**
  76905. * Fired when the grip button on this controller is modified
  76906. */
  76907. get: function () {
  76908. return this.onMainButtonStateChangedObservable;
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76914. /**
  76915. * Fired when the thumbstick button on this controller is modified
  76916. */
  76917. get: function () {
  76918. return this.onPadStateChangedObservable;
  76919. },
  76920. enumerable: true,
  76921. configurable: true
  76922. });
  76923. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76924. /**
  76925. * Fired when the touchpad button on this controller is modified
  76926. */
  76927. get: function () {
  76928. return this.onTrackpadChangedObservable;
  76929. },
  76930. enumerable: true,
  76931. configurable: true
  76932. });
  76933. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76934. /**
  76935. * Fired when the touchpad values on this controller are modified
  76936. */
  76937. get: function () {
  76938. return this.onTrackpadValuesChangedObservable;
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. WindowsMotionController.prototype._updateTrackpad = function () {
  76944. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76945. this.trackpad.x = this.browserGamepad["axes"][2];
  76946. this.trackpad.y = this.browserGamepad["axes"][3];
  76947. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76948. }
  76949. };
  76950. /**
  76951. * Called once per frame by the engine.
  76952. */
  76953. WindowsMotionController.prototype.update = function () {
  76954. _super.prototype.update.call(this);
  76955. if (this.browserGamepad.axes) {
  76956. this._updateTrackpad();
  76957. // Only need to animate axes if there is a loaded mesh
  76958. if (this._loadedMeshInfo) {
  76959. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76960. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76961. }
  76962. }
  76963. }
  76964. };
  76965. /**
  76966. * Called once for each button that changed state since the last frame
  76967. * @param buttonIdx Which button index changed
  76968. * @param state New state of the button
  76969. * @param changes Which properties on the state changed since last frame
  76970. */
  76971. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76972. var buttonName = this._mapping.buttons[buttonIdx];
  76973. if (!buttonName) {
  76974. return;
  76975. }
  76976. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76977. this._updateTrackpad();
  76978. // Only emit events for buttons that we know how to map from index to name
  76979. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76980. if (observable) {
  76981. observable.notifyObservers(state);
  76982. }
  76983. this._lerpButtonTransform(buttonName, state.value);
  76984. };
  76985. /**
  76986. * Moves the buttons on the controller mesh based on their current state
  76987. * @param buttonName the name of the button to move
  76988. * @param buttonValue the value of the button which determines the buttons new position
  76989. */
  76990. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76991. // If there is no loaded mesh, there is nothing to transform.
  76992. if (!this._loadedMeshInfo) {
  76993. return;
  76994. }
  76995. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76996. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76997. return;
  76998. }
  76999. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  77000. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  77001. };
  77002. /**
  77003. * Moves the axis on the controller mesh based on its current state
  77004. * @param axis the index of the axis
  77005. * @param axisValue the value of the axis which determines the meshes new position
  77006. * @hidden
  77007. */
  77008. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  77009. if (!this._loadedMeshInfo) {
  77010. return;
  77011. }
  77012. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  77013. if (!meshInfo) {
  77014. return;
  77015. }
  77016. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  77017. return;
  77018. }
  77019. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  77020. var lerpValue = axisValue * 0.5 + 0.5;
  77021. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  77022. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  77023. };
  77024. /**
  77025. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77026. * @param scene scene in which to add meshes
  77027. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77028. */
  77029. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  77030. var _this = this;
  77031. if (forceDefault === void 0) { forceDefault = false; }
  77032. var path;
  77033. var filename;
  77034. // Checking if GLB loader is present
  77035. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  77036. // Determine the device specific folder based on the ID suffix
  77037. var device = 'default';
  77038. if (this.id && !forceDefault) {
  77039. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  77040. device = ((match && match[0]) || device);
  77041. }
  77042. // Hand
  77043. if (this.hand === 'left') {
  77044. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  77045. }
  77046. else { // Right is the default if no hand is specified
  77047. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  77048. }
  77049. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  77050. }
  77051. else {
  77052. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  77053. path = BABYLON.GenericController.MODEL_BASE_URL;
  77054. filename = BABYLON.GenericController.MODEL_FILENAME;
  77055. }
  77056. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  77057. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  77058. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  77059. if (!_this._loadedMeshInfo) {
  77060. return;
  77061. }
  77062. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  77063. _this.attachToMesh(_this._defaultModel);
  77064. if (meshLoaded) {
  77065. meshLoaded(_this._defaultModel);
  77066. }
  77067. }, null, function (scene, message) {
  77068. BABYLON.Tools.Log(message);
  77069. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  77070. if (!forceDefault) {
  77071. _this.initControllerMesh(scene, meshLoaded, true);
  77072. }
  77073. });
  77074. };
  77075. /**
  77076. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  77077. * can be transformed by button presses and axes values, based on this._mapping.
  77078. *
  77079. * @param scene scene in which the meshes exist
  77080. * @param meshes list of meshes that make up the controller model to process
  77081. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  77082. */
  77083. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  77084. var loadedMeshInfo = null;
  77085. // Create a new mesh to contain the glTF hierarchy
  77086. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  77087. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  77088. var childMesh = null;
  77089. for (var i = 0; i < meshes.length; i++) {
  77090. var mesh = meshes[i];
  77091. if (!mesh.parent) {
  77092. // Exclude controller meshes from picking results
  77093. mesh.isPickable = false;
  77094. // Handle root node, attach to the new parentMesh
  77095. childMesh = mesh;
  77096. break;
  77097. }
  77098. }
  77099. if (childMesh) {
  77100. childMesh.setParent(parentMesh);
  77101. // Create our mesh info. Note that this method will always return non-null.
  77102. loadedMeshInfo = this.createMeshInfo(parentMesh);
  77103. }
  77104. else {
  77105. BABYLON.Tools.Warn('Could not find root node in model file.');
  77106. }
  77107. return loadedMeshInfo;
  77108. };
  77109. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  77110. var loadedMeshInfo = new LoadedMeshInfo();
  77111. var i;
  77112. loadedMeshInfo.rootNode = rootNode;
  77113. // Reset the caches
  77114. loadedMeshInfo.buttonMeshes = {};
  77115. loadedMeshInfo.axisMeshes = {};
  77116. // Button Meshes
  77117. for (i = 0; i < this._mapping.buttons.length; i++) {
  77118. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  77119. if (!buttonMeshName) {
  77120. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  77121. continue;
  77122. }
  77123. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  77124. if (!buttonMesh) {
  77125. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  77126. continue;
  77127. }
  77128. var buttonMeshInfo = {
  77129. index: i,
  77130. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  77131. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  77132. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  77133. };
  77134. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  77135. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  77136. }
  77137. else {
  77138. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  77139. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  77140. '(VALUE: ' + !!buttonMeshInfo.value +
  77141. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  77142. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  77143. ')');
  77144. }
  77145. }
  77146. // Axis Meshes
  77147. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  77148. var axisMeshName = this._mapping.axisMeshNames[i];
  77149. if (!axisMeshName) {
  77150. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  77151. continue;
  77152. }
  77153. var axisMesh = getChildByName(rootNode, axisMeshName);
  77154. if (!axisMesh) {
  77155. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  77156. continue;
  77157. }
  77158. var axisMeshInfo = {
  77159. index: i,
  77160. value: getImmediateChildByName(axisMesh, 'VALUE'),
  77161. min: getImmediateChildByName(axisMesh, 'MIN'),
  77162. max: getImmediateChildByName(axisMesh, 'MAX')
  77163. };
  77164. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  77165. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  77166. }
  77167. else {
  77168. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  77169. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  77170. '(VALUE: ' + !!axisMeshInfo.value +
  77171. ', MIN: ' + !!axisMeshInfo.min +
  77172. ', MAX:' + !!axisMeshInfo.max +
  77173. ')');
  77174. }
  77175. }
  77176. // Pointing Ray
  77177. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  77178. if (!loadedMeshInfo.pointingPoseNode) {
  77179. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  77180. }
  77181. else {
  77182. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  77183. }
  77184. return loadedMeshInfo;
  77185. // Look through all children recursively. This will return null if no mesh exists with the given name.
  77186. function getChildByName(node, name) {
  77187. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  77188. }
  77189. // Look through only immediate children. This will return null if no mesh exists with the given name.
  77190. function getImmediateChildByName(node, name) {
  77191. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  77192. }
  77193. };
  77194. /**
  77195. * Gets the ray of the controller in the direction the controller is pointing
  77196. * @param length the length the resulting ray should be
  77197. * @returns a ray in the direction the controller is pointing
  77198. */
  77199. WindowsMotionController.prototype.getForwardRay = function (length) {
  77200. if (length === void 0) { length = 100; }
  77201. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  77202. return _super.prototype.getForwardRay.call(this, length);
  77203. }
  77204. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  77205. var origin = m.getTranslation();
  77206. var forward = new BABYLON.Vector3(0, 0, -1);
  77207. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77208. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77209. return new BABYLON.Ray(origin, direction, length);
  77210. };
  77211. /**
  77212. * Disposes of the controller
  77213. */
  77214. WindowsMotionController.prototype.dispose = function () {
  77215. _super.prototype.dispose.call(this);
  77216. this.onTrackpadChangedObservable.clear();
  77217. };
  77218. /**
  77219. * The base url used to load the left and right controller models
  77220. */
  77221. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  77222. /**
  77223. * The name of the left controller model file
  77224. */
  77225. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  77226. /**
  77227. * The name of the right controller model file
  77228. */
  77229. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  77230. /**
  77231. * The controller name prefix for this controller type
  77232. */
  77233. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  77234. /**
  77235. * The controller id pattern for this controller type
  77236. */
  77237. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  77238. return WindowsMotionController;
  77239. }(BABYLON.WebVRController));
  77240. BABYLON.WindowsMotionController = WindowsMotionController;
  77241. })(BABYLON || (BABYLON = {}));
  77242. //# sourceMappingURL=babylon.windowsMotionController.js.map
  77243. var BABYLON;
  77244. (function (BABYLON) {
  77245. /**
  77246. * Gear VR Controller
  77247. */
  77248. var GearVRController = /** @class */ (function (_super) {
  77249. __extends(GearVRController, _super);
  77250. /**
  77251. * Creates a new GearVRController from a gamepad
  77252. * @param vrGamepad the gamepad that the controller should be created from
  77253. */
  77254. function GearVRController(vrGamepad) {
  77255. var _this = _super.call(this, vrGamepad) || this;
  77256. _this._maxRotationDistFromHeadset = Math.PI / 5;
  77257. _this._draggedRoomRotation = 0;
  77258. _this._tmpVector = new BABYLON.Vector3();
  77259. _this._buttonIndexToObservableNameMap = [
  77260. 'onTrackpadChangedObservable',
  77261. 'onTriggerStateChangedObservable' // Trigger
  77262. ];
  77263. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  77264. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  77265. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  77266. return _this;
  77267. }
  77268. /**
  77269. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77270. * @param poseData raw pose fromthe device
  77271. */
  77272. GearVRController.prototype.updateFromDevice = function (poseData) {
  77273. _super.prototype.updateFromDevice.call(this, poseData);
  77274. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  77275. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  77276. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  77277. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  77278. // Find the radian distance away that the headset is from the controllers rotation
  77279. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  77280. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  77281. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  77282. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  77283. this._draggedRoomRotation += rotationAmount;
  77284. // Rotate controller around headset
  77285. var sin = Math.sin(-rotationAmount);
  77286. var cos = Math.cos(-rotationAmount);
  77287. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77288. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77289. }
  77290. }
  77291. }
  77292. };
  77293. /**
  77294. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77295. * @param scene scene in which to add meshes
  77296. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77297. */
  77298. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77299. var _this = this;
  77300. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  77301. // Offset the controller so it will rotate around the users wrist
  77302. var mesh = new BABYLON.Mesh("", scene);
  77303. newMeshes[1].parent = mesh;
  77304. newMeshes[1].position.z = -0.15;
  77305. _this._defaultModel = mesh;
  77306. _this.attachToMesh(_this._defaultModel);
  77307. if (meshLoaded) {
  77308. meshLoaded(_this._defaultModel);
  77309. }
  77310. });
  77311. };
  77312. /**
  77313. * Called once for each button that changed state since the last frame
  77314. * @param buttonIdx Which button index changed
  77315. * @param state New state of the button
  77316. * @param changes Which properties on the state changed since last frame
  77317. */
  77318. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77319. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  77320. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  77321. // Only emit events for buttons that we know how to map from index to observable
  77322. var observable = this[observableName];
  77323. if (observable) {
  77324. observable.notifyObservers(state);
  77325. }
  77326. }
  77327. };
  77328. /**
  77329. * Base Url for the controller model.
  77330. */
  77331. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77332. /**
  77333. * File name for the controller model.
  77334. */
  77335. GearVRController.MODEL_FILENAME = 'generic.babylon';
  77336. /**
  77337. * Gamepad Id prefix used to identify this controller.
  77338. */
  77339. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  77340. return GearVRController;
  77341. }(BABYLON.WebVRController));
  77342. BABYLON.GearVRController = GearVRController;
  77343. })(BABYLON || (BABYLON = {}));
  77344. //# sourceMappingURL=babylon.gearVRController.js.map
  77345. var BABYLON;
  77346. (function (BABYLON) {
  77347. /**
  77348. * Google Daydream controller
  77349. */
  77350. var DaydreamController = /** @class */ (function (_super) {
  77351. __extends(DaydreamController, _super);
  77352. /**
  77353. * Creates a new DaydreamController from a gamepad
  77354. * @param vrGamepad the gamepad that the controller should be created from
  77355. */
  77356. function DaydreamController(vrGamepad) {
  77357. var _this = _super.call(this, vrGamepad) || this;
  77358. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  77359. return _this;
  77360. }
  77361. /**
  77362. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77363. * @param scene scene in which to add meshes
  77364. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77365. */
  77366. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77367. var _this = this;
  77368. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  77369. _this._defaultModel = newMeshes[1];
  77370. _this.attachToMesh(_this._defaultModel);
  77371. if (meshLoaded) {
  77372. meshLoaded(_this._defaultModel);
  77373. }
  77374. });
  77375. };
  77376. /**
  77377. * Called once for each button that changed state since the last frame
  77378. * @param buttonIdx Which button index changed
  77379. * @param state New state of the button
  77380. * @param changes Which properties on the state changed since last frame
  77381. */
  77382. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77383. // Daydream controller only has 1 GamepadButton (on the trackpad).
  77384. if (buttonIdx === 0) {
  77385. var observable = this.onTriggerStateChangedObservable;
  77386. if (observable) {
  77387. observable.notifyObservers(state);
  77388. }
  77389. }
  77390. else {
  77391. // If the app or home buttons are ever made available
  77392. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  77393. }
  77394. };
  77395. /**
  77396. * Base Url for the controller model.
  77397. */
  77398. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77399. /**
  77400. * File name for the controller model.
  77401. */
  77402. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  77403. /**
  77404. * Gamepad Id prefix used to identify Daydream Controller.
  77405. */
  77406. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  77407. return DaydreamController;
  77408. }(BABYLON.WebVRController));
  77409. BABYLON.DaydreamController = DaydreamController;
  77410. })(BABYLON || (BABYLON = {}));
  77411. //# sourceMappingURL=babylon.daydreamController.js.map
  77412. var BABYLON;
  77413. (function (BABYLON) {
  77414. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  77415. get: function () {
  77416. if (!this._gamepadManager) {
  77417. this._gamepadManager = new BABYLON.GamepadManager(this);
  77418. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  77419. if (!component) {
  77420. component = new GamepadSystemSceneComponent(this);
  77421. this._addComponent(component);
  77422. }
  77423. }
  77424. return this._gamepadManager;
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  77430. this.add(new BABYLON.FreeCameraGamepadInput());
  77431. return this;
  77432. };
  77433. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  77434. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  77435. return this;
  77436. };
  77437. /**
  77438. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  77439. */
  77440. var GamepadSystemSceneComponent = /** @class */ (function () {
  77441. /**
  77442. * Creates a new instance of the component for the given scene
  77443. * @param scene Defines the scene to register the component in
  77444. */
  77445. function GamepadSystemSceneComponent(scene) {
  77446. /**
  77447. * The component name helpfull to identify the component in the list of scene components.
  77448. */
  77449. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  77450. this.scene = scene;
  77451. }
  77452. /**
  77453. * Registers the component in a given scene
  77454. */
  77455. GamepadSystemSceneComponent.prototype.register = function () {
  77456. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  77457. };
  77458. /**
  77459. * Rebuilds the elements related to this component in case of
  77460. * context lost for instance.
  77461. */
  77462. GamepadSystemSceneComponent.prototype.rebuild = function () {
  77463. // Nothing to do for gamepads
  77464. };
  77465. /**
  77466. * Disposes the component and the associated ressources
  77467. */
  77468. GamepadSystemSceneComponent.prototype.dispose = function () {
  77469. var gamepadManager = this.scene._gamepadManager;
  77470. if (gamepadManager) {
  77471. gamepadManager.dispose();
  77472. this.scene._gamepadManager = null;
  77473. }
  77474. };
  77475. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  77476. var gamepadManager = this.scene._gamepadManager;
  77477. if (gamepadManager && gamepadManager._isMonitoring) {
  77478. gamepadManager._checkGamepadsStatus();
  77479. }
  77480. };
  77481. return GamepadSystemSceneComponent;
  77482. }());
  77483. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  77484. })(BABYLON || (BABYLON = {}));
  77485. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  77486. var BABYLON;
  77487. (function (BABYLON) {
  77488. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  77489. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  77490. });
  77491. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  77492. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  77493. });
  77494. var FollowCamera = /** @class */ (function (_super) {
  77495. __extends(FollowCamera, _super);
  77496. function FollowCamera(name, position, scene, lockedTarget) {
  77497. if (lockedTarget === void 0) { lockedTarget = null; }
  77498. var _this = _super.call(this, name, position, scene) || this;
  77499. _this.radius = 12;
  77500. _this.rotationOffset = 0;
  77501. _this.heightOffset = 4;
  77502. _this.cameraAcceleration = 0.05;
  77503. _this.maxCameraSpeed = 20;
  77504. _this.lockedTarget = lockedTarget;
  77505. return _this;
  77506. }
  77507. FollowCamera.prototype.getRadians = function (degrees) {
  77508. return degrees * Math.PI / 180;
  77509. };
  77510. FollowCamera.prototype.follow = function (cameraTarget) {
  77511. if (!cameraTarget)
  77512. return;
  77513. var yRotation;
  77514. if (cameraTarget.rotationQuaternion) {
  77515. var rotMatrix = new BABYLON.Matrix();
  77516. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  77517. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  77518. }
  77519. else {
  77520. yRotation = cameraTarget.rotation.y;
  77521. }
  77522. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77523. var targetPosition = cameraTarget.getAbsolutePosition();
  77524. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77525. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77526. var dx = targetX - this.position.x;
  77527. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77528. var dz = (targetZ) - this.position.z;
  77529. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77530. var vy = dy * this.cameraAcceleration;
  77531. var vz = dz * this.cameraAcceleration * 2;
  77532. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77533. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77534. }
  77535. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77536. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77537. }
  77538. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77539. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77540. }
  77541. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77542. this.setTarget(targetPosition);
  77543. };
  77544. /** @hidden */
  77545. FollowCamera.prototype._checkInputs = function () {
  77546. _super.prototype._checkInputs.call(this);
  77547. if (this.lockedTarget) {
  77548. this.follow(this.lockedTarget);
  77549. }
  77550. };
  77551. FollowCamera.prototype.getClassName = function () {
  77552. return "FollowCamera";
  77553. };
  77554. __decorate([
  77555. BABYLON.serialize()
  77556. ], FollowCamera.prototype, "radius", void 0);
  77557. __decorate([
  77558. BABYLON.serialize()
  77559. ], FollowCamera.prototype, "rotationOffset", void 0);
  77560. __decorate([
  77561. BABYLON.serialize()
  77562. ], FollowCamera.prototype, "heightOffset", void 0);
  77563. __decorate([
  77564. BABYLON.serialize()
  77565. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77566. __decorate([
  77567. BABYLON.serialize()
  77568. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77569. __decorate([
  77570. BABYLON.serializeAsMeshReference("lockedTargetId")
  77571. ], FollowCamera.prototype, "lockedTarget", void 0);
  77572. return FollowCamera;
  77573. }(BABYLON.TargetCamera));
  77574. BABYLON.FollowCamera = FollowCamera;
  77575. /**
  77576. * Arc Rotate version of the follow camera.
  77577. * It still follows a defined mesh but in an Arc Rotate Camera fashion.
  77578. */
  77579. var ArcFollowCamera = /** @class */ (function (_super) {
  77580. __extends(ArcFollowCamera, _super);
  77581. /**
  77582. * Instantiates a new ArcFollowCamera
  77583. * @param name Defines the name of the camera
  77584. * @param alpha Defines the rotation angle of the camera around the logitudinal axis
  77585. * @param beta Defines the rotation angle of the camera around the elevation axis
  77586. * @param radius Defines the radius of the camera from its target point
  77587. * @param target Defines the target of the camera
  77588. * @param scene Defines the scene the camera belongs to
  77589. */
  77590. function ArcFollowCamera(name,
  77591. /** The longitudinal angle of the camera */
  77592. alpha,
  77593. /** The latitudinal angle of the camera */
  77594. beta,
  77595. /** The radius of the camera from its target */
  77596. radius,
  77597. /** Defines the camera target (the messh it should follow) */
  77598. target, scene) {
  77599. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77600. _this.alpha = alpha;
  77601. _this.beta = beta;
  77602. _this.radius = radius;
  77603. _this.target = target;
  77604. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77605. _this.follow();
  77606. return _this;
  77607. }
  77608. ArcFollowCamera.prototype.follow = function () {
  77609. if (!this.target) {
  77610. return;
  77611. }
  77612. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77613. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77614. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77615. var targetPosition = this.target.getAbsolutePosition();
  77616. this.position = targetPosition.add(this._cartesianCoordinates);
  77617. this.setTarget(targetPosition);
  77618. };
  77619. /** @hidden */
  77620. ArcFollowCamera.prototype._checkInputs = function () {
  77621. _super.prototype._checkInputs.call(this);
  77622. this.follow();
  77623. };
  77624. /**
  77625. * Returns the class name of the object.
  77626. * It is mostly used internally for serialization purposes.
  77627. */
  77628. ArcFollowCamera.prototype.getClassName = function () {
  77629. return "ArcFollowCamera";
  77630. };
  77631. return ArcFollowCamera;
  77632. }(BABYLON.TargetCamera));
  77633. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77634. })(BABYLON || (BABYLON = {}));
  77635. //# sourceMappingURL=babylon.followCamera.js.map
  77636. var BABYLON;
  77637. (function (BABYLON) {
  77638. // We're mainly based on the logic defined into the FreeCamera code
  77639. var UniversalCamera = /** @class */ (function (_super) {
  77640. __extends(UniversalCamera, _super);
  77641. //-- end properties for backward compatibility for inputs
  77642. function UniversalCamera(name, position, scene) {
  77643. var _this = _super.call(this, name, position, scene) || this;
  77644. _this.inputs.addGamepad();
  77645. return _this;
  77646. }
  77647. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77648. //-- Begin properties for backward compatibility for inputs
  77649. get: function () {
  77650. var gamepad = this.inputs.attached["gamepad"];
  77651. if (gamepad)
  77652. return gamepad.gamepadAngularSensibility;
  77653. return 0;
  77654. },
  77655. set: function (value) {
  77656. var gamepad = this.inputs.attached["gamepad"];
  77657. if (gamepad)
  77658. gamepad.gamepadAngularSensibility = value;
  77659. },
  77660. enumerable: true,
  77661. configurable: true
  77662. });
  77663. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77664. get: function () {
  77665. var gamepad = this.inputs.attached["gamepad"];
  77666. if (gamepad)
  77667. return gamepad.gamepadMoveSensibility;
  77668. return 0;
  77669. },
  77670. set: function (value) {
  77671. var gamepad = this.inputs.attached["gamepad"];
  77672. if (gamepad)
  77673. gamepad.gamepadMoveSensibility = value;
  77674. },
  77675. enumerable: true,
  77676. configurable: true
  77677. });
  77678. UniversalCamera.prototype.getClassName = function () {
  77679. return "UniversalCamera";
  77680. };
  77681. return UniversalCamera;
  77682. }(BABYLON.TouchCamera));
  77683. BABYLON.UniversalCamera = UniversalCamera;
  77684. })(BABYLON || (BABYLON = {}));
  77685. //# sourceMappingURL=babylon.universalCamera.js.map
  77686. var BABYLON;
  77687. (function (BABYLON) {
  77688. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77689. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77690. });
  77691. // We're mainly based on the logic defined into the FreeCamera code
  77692. var GamepadCamera = /** @class */ (function (_super) {
  77693. __extends(GamepadCamera, _super);
  77694. //-- end properties for backward compatibility for inputs
  77695. function GamepadCamera(name, position, scene) {
  77696. return _super.call(this, name, position, scene) || this;
  77697. }
  77698. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77699. //-- Begin properties for backward compatibility for inputs
  77700. get: function () {
  77701. var gamepad = this.inputs.attached["gamepad"];
  77702. if (gamepad)
  77703. return gamepad.gamepadAngularSensibility;
  77704. return 0;
  77705. },
  77706. set: function (value) {
  77707. var gamepad = this.inputs.attached["gamepad"];
  77708. if (gamepad)
  77709. gamepad.gamepadAngularSensibility = value;
  77710. },
  77711. enumerable: true,
  77712. configurable: true
  77713. });
  77714. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77715. get: function () {
  77716. var gamepad = this.inputs.attached["gamepad"];
  77717. if (gamepad)
  77718. return gamepad.gamepadMoveSensibility;
  77719. return 0;
  77720. },
  77721. set: function (value) {
  77722. var gamepad = this.inputs.attached["gamepad"];
  77723. if (gamepad)
  77724. gamepad.gamepadMoveSensibility = value;
  77725. },
  77726. enumerable: true,
  77727. configurable: true
  77728. });
  77729. GamepadCamera.prototype.getClassName = function () {
  77730. return "GamepadCamera";
  77731. };
  77732. return GamepadCamera;
  77733. }(BABYLON.UniversalCamera));
  77734. BABYLON.GamepadCamera = GamepadCamera;
  77735. })(BABYLON || (BABYLON = {}));
  77736. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77737. var BABYLON;
  77738. (function (BABYLON) {
  77739. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77740. function PostProcessRenderPipelineManager() {
  77741. this._renderPipelines = {};
  77742. }
  77743. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77744. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77745. };
  77746. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77747. if (unique === void 0) { unique = false; }
  77748. var renderPipeline = this._renderPipelines[renderPipelineName];
  77749. if (!renderPipeline) {
  77750. return;
  77751. }
  77752. renderPipeline._attachCameras(cameras, unique);
  77753. };
  77754. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77755. var renderPipeline = this._renderPipelines[renderPipelineName];
  77756. if (!renderPipeline) {
  77757. return;
  77758. }
  77759. renderPipeline._detachCameras(cameras);
  77760. };
  77761. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77762. var renderPipeline = this._renderPipelines[renderPipelineName];
  77763. if (!renderPipeline) {
  77764. return;
  77765. }
  77766. renderPipeline._enableEffect(renderEffectName, cameras);
  77767. };
  77768. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77769. var renderPipeline = this._renderPipelines[renderPipelineName];
  77770. if (!renderPipeline) {
  77771. return;
  77772. }
  77773. renderPipeline._disableEffect(renderEffectName, cameras);
  77774. };
  77775. PostProcessRenderPipelineManager.prototype.update = function () {
  77776. for (var renderPipelineName in this._renderPipelines) {
  77777. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77778. var pipeline = this._renderPipelines[renderPipelineName];
  77779. if (!pipeline.isSupported) {
  77780. pipeline.dispose();
  77781. delete this._renderPipelines[renderPipelineName];
  77782. }
  77783. else {
  77784. pipeline._update();
  77785. }
  77786. }
  77787. }
  77788. };
  77789. /** @hidden */
  77790. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77791. for (var renderPipelineName in this._renderPipelines) {
  77792. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77793. var pipeline = this._renderPipelines[renderPipelineName];
  77794. pipeline._rebuild();
  77795. }
  77796. }
  77797. };
  77798. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77799. for (var renderPipelineName in this._renderPipelines) {
  77800. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77801. var pipeline = this._renderPipelines[renderPipelineName];
  77802. pipeline.dispose();
  77803. }
  77804. }
  77805. };
  77806. return PostProcessRenderPipelineManager;
  77807. }());
  77808. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77809. })(BABYLON || (BABYLON = {}));
  77810. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77811. var BABYLON;
  77812. (function (BABYLON) {
  77813. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77814. get: function () {
  77815. if (!this._postProcessRenderPipelineManager) {
  77816. // Register the G Buffer component to the scene.
  77817. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77818. if (!component) {
  77819. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77820. this._addComponent(component);
  77821. }
  77822. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77823. }
  77824. return this._postProcessRenderPipelineManager;
  77825. },
  77826. enumerable: true,
  77827. configurable: true
  77828. });
  77829. /**
  77830. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77831. */
  77832. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77833. /**
  77834. * Creates a new instance of the component for the given scene
  77835. * @param scene Defines the scene to register the component in
  77836. */
  77837. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77838. /**
  77839. * The component name helpfull to identify the component in the list of scene components.
  77840. */
  77841. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77842. this.scene = scene;
  77843. }
  77844. /**
  77845. * Registers the component in a given scene
  77846. */
  77847. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77848. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77849. };
  77850. /**
  77851. * Rebuilds the elements related to this component in case of
  77852. * context lost for instance.
  77853. */
  77854. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77855. if (this.scene._postProcessRenderPipelineManager) {
  77856. this.scene._postProcessRenderPipelineManager._rebuild();
  77857. }
  77858. };
  77859. /**
  77860. * Disposes the component and the associated ressources
  77861. */
  77862. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77863. if (this.scene._postProcessRenderPipelineManager) {
  77864. this.scene._postProcessRenderPipelineManager.dispose();
  77865. }
  77866. };
  77867. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77868. if (this.scene._postProcessRenderPipelineManager) {
  77869. this.scene._postProcessRenderPipelineManager.update();
  77870. }
  77871. };
  77872. return PostProcessRenderPipelineManagerSceneComponent;
  77873. }());
  77874. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77875. })(BABYLON || (BABYLON = {}));
  77876. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77877. var BABYLON;
  77878. (function (BABYLON) {
  77879. /**
  77880. * This represents a set of one or more post processes in Babylon.
  77881. * A post process can be used to apply a shader to a texture after it is rendered.
  77882. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77883. */
  77884. var PostProcessRenderEffect = /** @class */ (function () {
  77885. /**
  77886. * Instantiates a post process render effect.
  77887. * A post process can be used to apply a shader to a texture after it is rendered.
  77888. * @param engine The engine the effect is tied to
  77889. * @param name The name of the effect
  77890. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77891. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77892. */
  77893. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77894. this._name = name;
  77895. this._singleInstance = singleInstance || true;
  77896. this._getPostProcesses = getPostProcesses;
  77897. this._cameras = {};
  77898. this._indicesForCamera = {};
  77899. this._postProcesses = {};
  77900. }
  77901. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77902. /**
  77903. * Checks if all the post processes in the effect are supported.
  77904. */
  77905. get: function () {
  77906. for (var index in this._postProcesses) {
  77907. if (this._postProcesses.hasOwnProperty(index)) {
  77908. var pps = this._postProcesses[index];
  77909. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77910. if (!pps[ppIndex].isSupported) {
  77911. return false;
  77912. }
  77913. }
  77914. }
  77915. }
  77916. return true;
  77917. },
  77918. enumerable: true,
  77919. configurable: true
  77920. });
  77921. /**
  77922. * Updates the current state of the effect
  77923. * @hidden
  77924. */
  77925. PostProcessRenderEffect.prototype._update = function () {
  77926. };
  77927. /**
  77928. * Attaches the effect on cameras
  77929. * @param cameras The camera to attach to.
  77930. * @hidden
  77931. */
  77932. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77933. var _this = this;
  77934. var cameraKey;
  77935. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77936. if (!cams) {
  77937. return;
  77938. }
  77939. for (var i = 0; i < cams.length; i++) {
  77940. var camera = cams[i];
  77941. var cameraName = camera.name;
  77942. if (this._singleInstance) {
  77943. cameraKey = 0;
  77944. }
  77945. else {
  77946. cameraKey = cameraName;
  77947. }
  77948. if (!this._postProcesses[cameraKey]) {
  77949. var postProcess = this._getPostProcesses();
  77950. if (postProcess) {
  77951. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77952. }
  77953. }
  77954. if (!this._indicesForCamera[cameraName]) {
  77955. this._indicesForCamera[cameraName] = [];
  77956. }
  77957. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77958. var index = camera.attachPostProcess(postProcess);
  77959. _this._indicesForCamera[cameraName].push(index);
  77960. });
  77961. if (!this._cameras[cameraName]) {
  77962. this._cameras[cameraName] = camera;
  77963. }
  77964. }
  77965. };
  77966. /**
  77967. * Detatches the effect on cameras
  77968. * @param cameras The camera to detatch from.
  77969. * @hidden
  77970. */
  77971. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77972. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77973. if (!cams) {
  77974. return;
  77975. }
  77976. for (var i = 0; i < cams.length; i++) {
  77977. var camera = cams[i];
  77978. var cameraName = camera.name;
  77979. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77980. camera.detachPostProcess(postProcess);
  77981. });
  77982. if (this._cameras[cameraName]) {
  77983. //this._indicesForCamera.splice(index, 1);
  77984. this._cameras[cameraName] = null;
  77985. }
  77986. }
  77987. };
  77988. /**
  77989. * Enables the effect on given cameras
  77990. * @param cameras The camera to enable.
  77991. * @hidden
  77992. */
  77993. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77994. var _this = this;
  77995. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77996. if (!cams) {
  77997. return;
  77998. }
  77999. for (var i = 0; i < cams.length; i++) {
  78000. var camera = cams[i];
  78001. var cameraName = camera.name;
  78002. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  78003. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  78004. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  78005. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  78006. });
  78007. }
  78008. }
  78009. }
  78010. };
  78011. /**
  78012. * Disables the effect on the given cameras
  78013. * @param cameras The camera to disable.
  78014. * @hidden
  78015. */
  78016. PostProcessRenderEffect.prototype._disable = function (cameras) {
  78017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  78018. if (!cams) {
  78019. return;
  78020. }
  78021. for (var i = 0; i < cams.length; i++) {
  78022. var camera = cams[i];
  78023. var cameraName = camera.name;
  78024. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  78025. camera.detachPostProcess(postProcess);
  78026. });
  78027. }
  78028. };
  78029. /**
  78030. * Gets a list of the post processes contained in the effect.
  78031. * @param camera The camera to get the post processes on.
  78032. * @returns The list of the post processes in the effect.
  78033. */
  78034. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  78035. if (this._singleInstance) {
  78036. return this._postProcesses[0];
  78037. }
  78038. else {
  78039. if (!camera) {
  78040. return null;
  78041. }
  78042. return this._postProcesses[camera.name];
  78043. }
  78044. };
  78045. return PostProcessRenderEffect;
  78046. }());
  78047. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  78048. })(BABYLON || (BABYLON = {}));
  78049. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  78050. var BABYLON;
  78051. (function (BABYLON) {
  78052. var PostProcessRenderPipeline = /** @class */ (function () {
  78053. function PostProcessRenderPipeline(engine, name) {
  78054. this.engine = engine;
  78055. this._name = name;
  78056. this._renderEffects = {};
  78057. this._renderEffectsForIsolatedPass = new Array();
  78058. this._cameras = [];
  78059. }
  78060. PostProcessRenderPipeline.prototype.getClassName = function () {
  78061. return "PostProcessRenderPipeline";
  78062. };
  78063. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  78064. get: function () {
  78065. for (var renderEffectName in this._renderEffects) {
  78066. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78067. if (!this._renderEffects[renderEffectName].isSupported) {
  78068. return false;
  78069. }
  78070. }
  78071. }
  78072. return true;
  78073. },
  78074. enumerable: true,
  78075. configurable: true
  78076. });
  78077. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  78078. this._renderEffects[renderEffect._name] = renderEffect;
  78079. };
  78080. // private
  78081. /** @hidden */
  78082. PostProcessRenderPipeline.prototype._rebuild = function () {
  78083. };
  78084. /** @hidden */
  78085. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  78086. var renderEffects = this._renderEffects[renderEffectName];
  78087. if (!renderEffects) {
  78088. return;
  78089. }
  78090. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  78091. };
  78092. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  78093. var renderEffects = this._renderEffects[renderEffectName];
  78094. if (!renderEffects) {
  78095. return;
  78096. }
  78097. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  78098. };
  78099. /** @hidden */
  78100. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  78101. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  78102. if (!cams) {
  78103. return;
  78104. }
  78105. var indicesToDelete = [];
  78106. var i;
  78107. for (i = 0; i < cams.length; i++) {
  78108. var camera = cams[i];
  78109. var cameraName = camera.name;
  78110. if (this._cameras.indexOf(camera) === -1) {
  78111. this._cameras[cameraName] = camera;
  78112. }
  78113. else if (unique) {
  78114. indicesToDelete.push(i);
  78115. }
  78116. }
  78117. for (i = 0; i < indicesToDelete.length; i++) {
  78118. cameras.splice(indicesToDelete[i], 1);
  78119. }
  78120. for (var renderEffectName in this._renderEffects) {
  78121. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78122. this._renderEffects[renderEffectName]._attachCameras(cams);
  78123. }
  78124. }
  78125. };
  78126. /** @hidden */
  78127. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  78128. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  78129. if (!cams) {
  78130. return;
  78131. }
  78132. for (var renderEffectName in this._renderEffects) {
  78133. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78134. this._renderEffects[renderEffectName]._detachCameras(cams);
  78135. }
  78136. }
  78137. for (var i = 0; i < cams.length; i++) {
  78138. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  78139. }
  78140. };
  78141. /** @hidden */
  78142. PostProcessRenderPipeline.prototype._update = function () {
  78143. for (var renderEffectName in this._renderEffects) {
  78144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  78145. this._renderEffects[renderEffectName]._update();
  78146. }
  78147. }
  78148. for (var i = 0; i < this._cameras.length; i++) {
  78149. var cameraName = this._cameras[i].name;
  78150. if (this._renderEffectsForIsolatedPass[cameraName]) {
  78151. this._renderEffectsForIsolatedPass[cameraName]._update();
  78152. }
  78153. }
  78154. };
  78155. /** @hidden */
  78156. PostProcessRenderPipeline.prototype._reset = function () {
  78157. this._renderEffects = {};
  78158. this._renderEffectsForIsolatedPass = new Array();
  78159. };
  78160. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  78161. // 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)
  78162. var effectKeys = Object.keys(this._renderEffects);
  78163. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  78164. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  78165. if (postProcesses) {
  78166. postProcesses[0].samples = sampleCount;
  78167. return true;
  78168. }
  78169. }
  78170. return false;
  78171. };
  78172. PostProcessRenderPipeline.prototype.dispose = function () {
  78173. // Must be implemented by children
  78174. };
  78175. __decorate([
  78176. BABYLON.serialize()
  78177. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  78178. return PostProcessRenderPipeline;
  78179. }());
  78180. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  78181. })(BABYLON || (BABYLON = {}));
  78182. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  78183. var BABYLON;
  78184. (function (BABYLON) {
  78185. /**
  78186. * This represents a depth renderer in Babylon.
  78187. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  78188. */
  78189. var DepthRenderer = /** @class */ (function () {
  78190. /**
  78191. * Instantiates a depth renderer
  78192. * @param scene The scene the renderer belongs to
  78193. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  78194. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  78195. */
  78196. function DepthRenderer(scene, type, camera) {
  78197. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  78198. if (camera === void 0) { camera = null; }
  78199. var _this = this;
  78200. /**
  78201. * Specifiess that the depth renderer will only be used within
  78202. * the camera it is created for.
  78203. * This can help forcing its rendering during the camera processing.
  78204. */
  78205. this.useOnlyInActiveCamera = false;
  78206. this._scene = scene;
  78207. // Register the G Buffer component to the scene.
  78208. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  78209. if (!component) {
  78210. component = new BABYLON.DepthRendererSceneComponent(scene);
  78211. scene._addComponent(component);
  78212. }
  78213. this._camera = camera;
  78214. var engine = scene.getEngine();
  78215. // Render target
  78216. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  78217. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78218. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78219. this._depthMap.refreshRate = 1;
  78220. this._depthMap.renderParticles = false;
  78221. this._depthMap.renderList = null;
  78222. // Camera to get depth map from to support multiple concurrent cameras
  78223. this._depthMap.activeCamera = this._camera;
  78224. this._depthMap.ignoreCameraViewport = true;
  78225. this._depthMap.useCameraPostProcesses = false;
  78226. // set default depth value to 1.0 (far away)
  78227. this._depthMap.onClearObservable.add(function (engine) {
  78228. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  78229. });
  78230. // Custom render function
  78231. var renderSubMesh = function (subMesh) {
  78232. var mesh = subMesh.getRenderingMesh();
  78233. var scene = _this._scene;
  78234. var engine = scene.getEngine();
  78235. var material = subMesh.getMaterial();
  78236. if (!material) {
  78237. return;
  78238. }
  78239. // Culling and reverse (right handed system)
  78240. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78241. // Managing instances
  78242. var batch = mesh._getInstancesRenderList(subMesh._id);
  78243. if (batch.mustReturn) {
  78244. return;
  78245. }
  78246. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78247. var camera = _this._camera || scene.activeCamera;
  78248. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  78249. engine.enableEffect(_this._effect);
  78250. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78251. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78252. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  78253. // Alpha test
  78254. if (material && material.needAlphaTesting()) {
  78255. var alphaTexture = material.getAlphaTestTexture();
  78256. if (alphaTexture) {
  78257. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78258. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78259. }
  78260. }
  78261. // Bones
  78262. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78263. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78264. }
  78265. // Draw
  78266. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78267. }
  78268. };
  78269. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78270. var index;
  78271. if (depthOnlySubMeshes.length) {
  78272. engine.setColorWrite(false);
  78273. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78274. renderSubMesh(depthOnlySubMeshes.data[index]);
  78275. }
  78276. engine.setColorWrite(true);
  78277. }
  78278. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78279. renderSubMesh(opaqueSubMeshes.data[index]);
  78280. }
  78281. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78282. renderSubMesh(alphaTestSubMeshes.data[index]);
  78283. }
  78284. };
  78285. }
  78286. /**
  78287. * Creates the depth rendering effect and checks if the effect is ready.
  78288. * @param subMesh The submesh to be used to render the depth map of
  78289. * @param useInstances If multiple world instances should be used
  78290. * @returns if the depth renderer is ready to render the depth map
  78291. */
  78292. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  78293. var material = subMesh.getMaterial();
  78294. if (material.disableDepthWrite) {
  78295. return false;
  78296. }
  78297. var defines = [];
  78298. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78299. var mesh = subMesh.getMesh();
  78300. // Alpha test
  78301. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  78302. defines.push("#define ALPHATEST");
  78303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78304. attribs.push(BABYLON.VertexBuffer.UVKind);
  78305. defines.push("#define UV1");
  78306. }
  78307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78309. defines.push("#define UV2");
  78310. }
  78311. }
  78312. // Bones
  78313. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78314. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78315. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78316. if (mesh.numBoneInfluencers > 4) {
  78317. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78318. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78319. }
  78320. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78321. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78322. }
  78323. else {
  78324. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78325. }
  78326. // Instances
  78327. if (useInstances) {
  78328. defines.push("#define INSTANCES");
  78329. attribs.push("world0");
  78330. attribs.push("world1");
  78331. attribs.push("world2");
  78332. attribs.push("world3");
  78333. }
  78334. // Get correct effect
  78335. var join = defines.join("\n");
  78336. if (this._cachedDefines !== join) {
  78337. this._cachedDefines = join;
  78338. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  78339. }
  78340. return this._effect.isReady();
  78341. };
  78342. /**
  78343. * Gets the texture which the depth map will be written to.
  78344. * @returns The depth map texture
  78345. */
  78346. DepthRenderer.prototype.getDepthMap = function () {
  78347. return this._depthMap;
  78348. };
  78349. /**
  78350. * Disposes of the depth renderer.
  78351. */
  78352. DepthRenderer.prototype.dispose = function () {
  78353. this._depthMap.dispose();
  78354. };
  78355. return DepthRenderer;
  78356. }());
  78357. BABYLON.DepthRenderer = DepthRenderer;
  78358. })(BABYLON || (BABYLON = {}));
  78359. //# sourceMappingURL=babylon.depthRenderer.js.map
  78360. var BABYLON;
  78361. (function (BABYLON) {
  78362. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  78363. camera = camera || this.activeCamera;
  78364. if (!camera) {
  78365. throw "No camera available to enable depth renderer";
  78366. }
  78367. if (!this._depthRenderer) {
  78368. this._depthRenderer = {};
  78369. }
  78370. if (!this._depthRenderer[camera.id]) {
  78371. var textureType = 0;
  78372. if (this.getEngine().getCaps().textureHalfFloatRender) {
  78373. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78374. }
  78375. else if (this.getEngine().getCaps().textureFloatRender) {
  78376. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78377. }
  78378. else {
  78379. throw "Depth renderer does not support int texture type";
  78380. }
  78381. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  78382. }
  78383. return this._depthRenderer[camera.id];
  78384. };
  78385. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  78386. camera = camera || this.activeCamera;
  78387. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  78388. return;
  78389. }
  78390. this._depthRenderer[camera.id].dispose();
  78391. delete this._depthRenderer[camera.id];
  78392. };
  78393. /**
  78394. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  78395. * in several rendering techniques.
  78396. */
  78397. var DepthRendererSceneComponent = /** @class */ (function () {
  78398. /**
  78399. * Creates a new instance of the component for the given scene
  78400. * @param scene Defines the scene to register the component in
  78401. */
  78402. function DepthRendererSceneComponent(scene) {
  78403. /**
  78404. * The component name helpfull to identify the component in the list of scene components.
  78405. */
  78406. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  78407. this.scene = scene;
  78408. }
  78409. /**
  78410. * Registers the component in a given scene
  78411. */
  78412. DepthRendererSceneComponent.prototype.register = function () {
  78413. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  78414. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  78415. };
  78416. /**
  78417. * Rebuilds the elements related to this component in case of
  78418. * context lost for instance.
  78419. */
  78420. DepthRendererSceneComponent.prototype.rebuild = function () {
  78421. // Nothing to do for this component
  78422. };
  78423. /**
  78424. * Disposes the component and the associated ressources
  78425. */
  78426. DepthRendererSceneComponent.prototype.dispose = function () {
  78427. for (var key in this.scene._depthRenderer) {
  78428. this.scene._depthRenderer[key].dispose();
  78429. }
  78430. };
  78431. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78432. if (this.scene._depthRenderer) {
  78433. for (var key in this.scene._depthRenderer) {
  78434. var depthRenderer = this.scene._depthRenderer[key];
  78435. if (!depthRenderer.useOnlyInActiveCamera) {
  78436. renderTargets.push(depthRenderer.getDepthMap());
  78437. }
  78438. }
  78439. }
  78440. };
  78441. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  78442. if (this.scene._depthRenderer) {
  78443. for (var key in this.scene._depthRenderer) {
  78444. var depthRenderer = this.scene._depthRenderer[key];
  78445. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  78446. renderTargets.push(depthRenderer.getDepthMap());
  78447. }
  78448. }
  78449. }
  78450. };
  78451. return DepthRendererSceneComponent;
  78452. }());
  78453. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  78454. })(BABYLON || (BABYLON = {}));
  78455. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  78456. var BABYLON;
  78457. (function (BABYLON) {
  78458. /**
  78459. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78460. */
  78461. var GeometryBufferRenderer = /** @class */ (function () {
  78462. /**
  78463. * Creates a new G Buffer for the scene
  78464. * @param scene The scene the buffer belongs to
  78465. * @param ratio How big is the buffer related to the main canvas.
  78466. */
  78467. function GeometryBufferRenderer(scene, ratio) {
  78468. if (ratio === void 0) { ratio = 1; }
  78469. this._enablePosition = false;
  78470. this._scene = scene;
  78471. this._ratio = ratio;
  78472. // Register the G Buffer component to the scene.
  78473. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  78474. if (!component) {
  78475. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  78476. scene._addComponent(component);
  78477. }
  78478. // Render target
  78479. this._createRenderTargets();
  78480. }
  78481. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78482. /**
  78483. * Set the render list (meshes to be rendered) used in the G buffer.
  78484. */
  78485. set: function (meshes) {
  78486. this._multiRenderTarget.renderList = meshes;
  78487. },
  78488. enumerable: true,
  78489. configurable: true
  78490. });
  78491. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78492. /**
  78493. * Gets wether or not G buffer are supported by the running hardware.
  78494. * This requires draw buffer supports
  78495. */
  78496. get: function () {
  78497. return this._multiRenderTarget.isSupported;
  78498. },
  78499. enumerable: true,
  78500. configurable: true
  78501. });
  78502. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78503. /**
  78504. * Gets wether or not position are enabled for the G buffer.
  78505. */
  78506. get: function () {
  78507. return this._enablePosition;
  78508. },
  78509. /**
  78510. * Sets wether or not position are enabled for the G buffer.
  78511. */
  78512. set: function (enable) {
  78513. this._enablePosition = enable;
  78514. this.dispose();
  78515. this._createRenderTargets();
  78516. },
  78517. enumerable: true,
  78518. configurable: true
  78519. });
  78520. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78521. /**
  78522. * Gets the scene associated with the buffer.
  78523. */
  78524. get: function () {
  78525. return this._scene;
  78526. },
  78527. enumerable: true,
  78528. configurable: true
  78529. });
  78530. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78531. /**
  78532. * Gets the ratio used by the buffer during its creation.
  78533. * How big is the buffer related to the main canvas.
  78534. */
  78535. get: function () {
  78536. return this._ratio;
  78537. },
  78538. enumerable: true,
  78539. configurable: true
  78540. });
  78541. /**
  78542. * Checks wether everything is ready to render a submesh to the G buffer.
  78543. * @param subMesh the submesh to check readiness for
  78544. * @param useInstances is the mesh drawn using instance or not
  78545. * @returns true if ready otherwise false
  78546. */
  78547. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78548. var material = subMesh.getMaterial();
  78549. if (material && material.disableDepthWrite) {
  78550. return false;
  78551. }
  78552. var defines = [];
  78553. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78554. var mesh = subMesh.getMesh();
  78555. // Alpha test
  78556. if (material && material.needAlphaTesting()) {
  78557. defines.push("#define ALPHATEST");
  78558. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78559. attribs.push(BABYLON.VertexBuffer.UVKind);
  78560. defines.push("#define UV1");
  78561. }
  78562. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78563. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78564. defines.push("#define UV2");
  78565. }
  78566. }
  78567. // Buffers
  78568. if (this._enablePosition) {
  78569. defines.push("#define POSITION");
  78570. }
  78571. // Bones
  78572. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78573. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78574. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78575. if (mesh.numBoneInfluencers > 4) {
  78576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78578. }
  78579. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78580. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78581. }
  78582. else {
  78583. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78584. }
  78585. // Instances
  78586. if (useInstances) {
  78587. defines.push("#define INSTANCES");
  78588. attribs.push("world0");
  78589. attribs.push("world1");
  78590. attribs.push("world2");
  78591. attribs.push("world3");
  78592. }
  78593. // Get correct effect
  78594. var join = defines.join("\n");
  78595. if (this._cachedDefines !== join) {
  78596. this._cachedDefines = join;
  78597. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78598. }
  78599. return this._effect.isReady();
  78600. };
  78601. /**
  78602. * Gets the current underlying G Buffer.
  78603. * @returns the buffer
  78604. */
  78605. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78606. return this._multiRenderTarget;
  78607. };
  78608. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78609. /**
  78610. * Gets the number of samples used to render the buffer (anti aliasing).
  78611. */
  78612. get: function () {
  78613. return this._multiRenderTarget.samples;
  78614. },
  78615. /**
  78616. * Sets the number of samples used to render the buffer (anti aliasing).
  78617. */
  78618. set: function (value) {
  78619. this._multiRenderTarget.samples = value;
  78620. },
  78621. enumerable: true,
  78622. configurable: true
  78623. });
  78624. /**
  78625. * Disposes the renderer and frees up associated resources.
  78626. */
  78627. GeometryBufferRenderer.prototype.dispose = function () {
  78628. this.getGBuffer().dispose();
  78629. };
  78630. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78631. var _this = this;
  78632. var engine = this._scene.getEngine();
  78633. var count = this._enablePosition ? 3 : 2;
  78634. 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 });
  78635. if (!this.isSupported) {
  78636. return;
  78637. }
  78638. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78639. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78640. this._multiRenderTarget.refreshRate = 1;
  78641. this._multiRenderTarget.renderParticles = false;
  78642. this._multiRenderTarget.renderList = null;
  78643. // set default depth value to 1.0 (far away)
  78644. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78645. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78646. });
  78647. // Custom render function
  78648. var renderSubMesh = function (subMesh) {
  78649. var mesh = subMesh.getRenderingMesh();
  78650. var scene = _this._scene;
  78651. var engine = scene.getEngine();
  78652. var material = subMesh.getMaterial();
  78653. if (!material) {
  78654. return;
  78655. }
  78656. // Culling
  78657. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78658. // Managing instances
  78659. var batch = mesh._getInstancesRenderList(subMesh._id);
  78660. if (batch.mustReturn) {
  78661. return;
  78662. }
  78663. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78664. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78665. engine.enableEffect(_this._effect);
  78666. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78667. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78668. _this._effect.setMatrix("view", scene.getViewMatrix());
  78669. // Alpha test
  78670. if (material && material.needAlphaTesting()) {
  78671. var alphaTexture = material.getAlphaTestTexture();
  78672. if (alphaTexture) {
  78673. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78674. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78675. }
  78676. }
  78677. // Bones
  78678. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78679. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78680. }
  78681. // Draw
  78682. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78683. }
  78684. };
  78685. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78686. var index;
  78687. if (depthOnlySubMeshes.length) {
  78688. engine.setColorWrite(false);
  78689. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78690. renderSubMesh(depthOnlySubMeshes.data[index]);
  78691. }
  78692. engine.setColorWrite(true);
  78693. }
  78694. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78695. renderSubMesh(opaqueSubMeshes.data[index]);
  78696. }
  78697. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78698. renderSubMesh(alphaTestSubMeshes.data[index]);
  78699. }
  78700. };
  78701. };
  78702. return GeometryBufferRenderer;
  78703. }());
  78704. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78705. })(BABYLON || (BABYLON = {}));
  78706. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78707. var BABYLON;
  78708. (function (BABYLON) {
  78709. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78710. get: function () {
  78711. this._geometryBufferRenderer;
  78712. },
  78713. set: function (value) {
  78714. if (value && value.isSupported) {
  78715. this._geometryBufferRenderer = value;
  78716. }
  78717. ;
  78718. },
  78719. enumerable: true,
  78720. configurable: true
  78721. });
  78722. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78723. if (ratio === void 0) { ratio = 1; }
  78724. if (this._geometryBufferRenderer) {
  78725. return this._geometryBufferRenderer;
  78726. }
  78727. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78728. if (!this._geometryBufferRenderer.isSupported) {
  78729. this._geometryBufferRenderer = null;
  78730. }
  78731. return this._geometryBufferRenderer;
  78732. };
  78733. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78734. if (!this._geometryBufferRenderer) {
  78735. return;
  78736. }
  78737. this._geometryBufferRenderer.dispose();
  78738. this._geometryBufferRenderer = null;
  78739. };
  78740. /**
  78741. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  78742. * in several rendering techniques.
  78743. */
  78744. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78745. /**
  78746. * Creates a new instance of the component for the given scene
  78747. * @param scene Defines the scene to register the component in
  78748. */
  78749. function GeometryBufferRendererSceneComponent(scene) {
  78750. /**
  78751. * The component name helpful to identify the component in the list of scene components.
  78752. */
  78753. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78754. this.scene = scene;
  78755. }
  78756. /**
  78757. * Registers the component in a given scene
  78758. */
  78759. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78760. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78761. };
  78762. /**
  78763. * Rebuilds the elements related to this component in case of
  78764. * context lost for instance.
  78765. */
  78766. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78767. // Nothing to do for this component
  78768. };
  78769. /**
  78770. * Disposes the component and the associated ressources
  78771. */
  78772. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78773. // Nothing to do for this component
  78774. };
  78775. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78776. if (this.scene._geometryBufferRenderer) {
  78777. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78778. }
  78779. };
  78780. return GeometryBufferRendererSceneComponent;
  78781. }());
  78782. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78783. })(BABYLON || (BABYLON = {}));
  78784. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78785. var BABYLON;
  78786. (function (BABYLON) {
  78787. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78788. __extends(SSAORenderingPipeline, _super);
  78789. /**
  78790. * @constructor
  78791. * @param {string} name - The rendering pipeline name
  78792. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78793. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  78794. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78795. */
  78796. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78797. var _this = _super.call(this, scene.getEngine(), name) || this;
  78798. // Members
  78799. /**
  78800. * The PassPostProcess id in the pipeline that contains the original scene color
  78801. */
  78802. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78803. /**
  78804. * The SSAO PostProcess id in the pipeline
  78805. */
  78806. _this.SSAORenderEffect = "SSAORenderEffect";
  78807. /**
  78808. * The horizontal blur PostProcess id in the pipeline
  78809. */
  78810. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78811. /**
  78812. * The vertical blur PostProcess id in the pipeline
  78813. */
  78814. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78815. /**
  78816. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78817. */
  78818. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78819. /**
  78820. * The output strength of the SSAO post-process. Default value is 1.0.
  78821. */
  78822. _this.totalStrength = 1.0;
  78823. /**
  78824. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78825. */
  78826. _this.radius = 0.0001;
  78827. /**
  78828. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78829. * Must not be equal to fallOff and superior to fallOff.
  78830. * Default value is 0.975
  78831. */
  78832. _this.area = 0.0075;
  78833. /**
  78834. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78835. * Must not be equal to area and inferior to area.
  78836. * Default value is 0.0
  78837. */
  78838. _this.fallOff = 0.000001;
  78839. /**
  78840. * The base color of the SSAO post-process
  78841. * The final result is "base + ssao" between [0, 1]
  78842. */
  78843. _this.base = 0.5;
  78844. _this._firstUpdate = true;
  78845. _this._scene = scene;
  78846. // Set up assets
  78847. _this._createRandomTexture();
  78848. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78849. var ssaoRatio = ratio.ssaoRatio || ratio;
  78850. var combineRatio = ratio.combineRatio || ratio;
  78851. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78852. _this._createSSAOPostProcess(ssaoRatio);
  78853. _this._createBlurPostProcess(ssaoRatio);
  78854. _this._createSSAOCombinePostProcess(combineRatio);
  78855. // Set up pipeline
  78856. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78857. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78858. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78859. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78860. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78861. // Finish
  78862. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78863. if (cameras)
  78864. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78865. return _this;
  78866. }
  78867. // Public Methods
  78868. /**
  78869. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78870. */
  78871. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78872. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78873. for (var i = 0; i < this._scene.cameras.length; i++) {
  78874. var camera = this._scene.cameras[i];
  78875. this._originalColorPostProcess.dispose(camera);
  78876. this._ssaoPostProcess.dispose(camera);
  78877. this._blurHPostProcess.dispose(camera);
  78878. this._blurVPostProcess.dispose(camera);
  78879. this._ssaoCombinePostProcess.dispose(camera);
  78880. }
  78881. this._randomTexture.dispose();
  78882. if (disableDepthRender)
  78883. this._scene.disableDepthRenderer();
  78884. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78885. _super.prototype.dispose.call(this);
  78886. };
  78887. // Private Methods
  78888. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78889. var _this = this;
  78890. var size = 16;
  78891. 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);
  78892. 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);
  78893. this._blurHPostProcess.onActivateObservable.add(function () {
  78894. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78895. _this._blurHPostProcess.kernel = size * dw;
  78896. });
  78897. this._blurVPostProcess.onActivateObservable.add(function () {
  78898. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78899. _this._blurVPostProcess.kernel = size * dw;
  78900. });
  78901. };
  78902. /** @hidden */
  78903. SSAORenderingPipeline.prototype._rebuild = function () {
  78904. this._firstUpdate = true;
  78905. _super.prototype._rebuild.call(this);
  78906. };
  78907. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78908. var _this = this;
  78909. var numSamples = 16;
  78910. var sampleSphere = [
  78911. 0.5381, 0.1856, -0.4319,
  78912. 0.1379, 0.2486, 0.4430,
  78913. 0.3371, 0.5679, -0.0057,
  78914. -0.6999, -0.0451, -0.0019,
  78915. 0.0689, -0.1598, -0.8547,
  78916. 0.0560, 0.0069, -0.1843,
  78917. -0.0146, 0.1402, 0.0762,
  78918. 0.0100, -0.1924, -0.0344,
  78919. -0.3577, -0.5301, -0.4358,
  78920. -0.3169, 0.1063, 0.0158,
  78921. 0.0103, -0.5869, 0.0046,
  78922. -0.0897, -0.4940, 0.3287,
  78923. 0.7119, -0.0154, -0.0918,
  78924. -0.0533, 0.0596, -0.5411,
  78925. 0.0352, -0.0631, 0.5460,
  78926. -0.4776, 0.2847, -0.0271
  78927. ];
  78928. var samplesFactor = 1.0 / numSamples;
  78929. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78930. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78931. "area", "fallOff", "base", "range", "viewport"
  78932. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78933. this._ssaoPostProcess.onApply = function (effect) {
  78934. if (_this._firstUpdate) {
  78935. effect.setArray3("sampleSphere", sampleSphere);
  78936. effect.setFloat("samplesFactor", samplesFactor);
  78937. effect.setFloat("randTextureTiles", 4.0);
  78938. }
  78939. effect.setFloat("totalStrength", _this.totalStrength);
  78940. effect.setFloat("radius", _this.radius);
  78941. effect.setFloat("area", _this.area);
  78942. effect.setFloat("fallOff", _this.fallOff);
  78943. effect.setFloat("base", _this.base);
  78944. effect.setTexture("textureSampler", _this._depthTexture);
  78945. effect.setTexture("randomSampler", _this._randomTexture);
  78946. };
  78947. };
  78948. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78949. var _this = this;
  78950. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78951. this._ssaoCombinePostProcess.onApply = function (effect) {
  78952. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78953. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78954. };
  78955. };
  78956. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78957. var size = 512;
  78958. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78959. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78960. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78961. var context = this._randomTexture.getContext();
  78962. var rand = function (min, max) {
  78963. return Math.random() * (max - min) + min;
  78964. };
  78965. var randVector = BABYLON.Vector3.Zero();
  78966. for (var x = 0; x < size; x++) {
  78967. for (var y = 0; y < size; y++) {
  78968. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78969. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78970. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78971. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78972. context.fillRect(x, y, 1, 1);
  78973. }
  78974. }
  78975. this._randomTexture.update(false);
  78976. };
  78977. __decorate([
  78978. BABYLON.serialize()
  78979. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78980. __decorate([
  78981. BABYLON.serialize()
  78982. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78983. __decorate([
  78984. BABYLON.serialize()
  78985. ], SSAORenderingPipeline.prototype, "area", void 0);
  78986. __decorate([
  78987. BABYLON.serialize()
  78988. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78989. __decorate([
  78990. BABYLON.serialize()
  78991. ], SSAORenderingPipeline.prototype, "base", void 0);
  78992. return SSAORenderingPipeline;
  78993. }(BABYLON.PostProcessRenderPipeline));
  78994. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78995. })(BABYLON || (BABYLON = {}));
  78996. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78997. var BABYLON;
  78998. (function (BABYLON) {
  78999. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  79000. __extends(SSAO2RenderingPipeline, _super);
  79001. /**
  79002. * @constructor
  79003. * @param {string} name - The rendering pipeline name
  79004. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79005. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  79006. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79007. */
  79008. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  79009. var _this = _super.call(this, scene.getEngine(), name) || this;
  79010. // Members
  79011. /**
  79012. * The PassPostProcess id in the pipeline that contains the original scene color
  79013. */
  79014. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  79015. /**
  79016. * The SSAO PostProcess id in the pipeline
  79017. */
  79018. _this.SSAORenderEffect = "SSAORenderEffect";
  79019. /**
  79020. * The horizontal blur PostProcess id in the pipeline
  79021. */
  79022. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  79023. /**
  79024. * The vertical blur PostProcess id in the pipeline
  79025. */
  79026. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  79027. /**
  79028. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  79029. */
  79030. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  79031. /**
  79032. * The output strength of the SSAO post-process. Default value is 1.0.
  79033. */
  79034. _this.totalStrength = 1.0;
  79035. /**
  79036. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  79037. */
  79038. _this.maxZ = 100.0;
  79039. /**
  79040. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  79041. */
  79042. _this.minZAspect = 0.2;
  79043. _this._samples = 8;
  79044. _this._textureSamples = 1;
  79045. /**
  79046. * Are we using bilateral blur ?
  79047. */
  79048. _this._expensiveBlur = true;
  79049. /**
  79050. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  79051. */
  79052. _this.radius = 2.0;
  79053. /**
  79054. * The base color of the SSAO post-process
  79055. * The final result is "base + ssao" between [0, 1]
  79056. */
  79057. _this.base = 0;
  79058. _this._firstUpdate = true;
  79059. _this._bits = new Uint32Array(1);
  79060. _this._scene = scene;
  79061. _this._ratio = ratio;
  79062. if (!_this.isSupported) {
  79063. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  79064. return _this;
  79065. }
  79066. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  79067. var blurRatio = _this._ratio.blurRatio || ratio;
  79068. // Set up assets
  79069. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  79070. _this._createRandomTexture();
  79071. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  79072. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  79073. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  79074. _this._originalColorPostProcess.samples = _this.textureSamples;
  79075. _this._createSSAOPostProcess(1.0);
  79076. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  79077. _this._createSSAOCombinePostProcess(blurRatio);
  79078. // Set up pipeline
  79079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  79080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  79081. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  79082. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  79083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  79084. // Finish
  79085. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79086. if (cameras)
  79087. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79088. return _this;
  79089. }
  79090. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  79091. get: function () {
  79092. return this._samples;
  79093. },
  79094. /**
  79095. * Number of samples used for the SSAO calculations. Default value is 8
  79096. */
  79097. set: function (n) {
  79098. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  79099. this._samples = n;
  79100. this._sampleSphere = this._generateHemisphere();
  79101. this._firstUpdate = true;
  79102. },
  79103. enumerable: true,
  79104. configurable: true
  79105. });
  79106. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  79107. get: function () {
  79108. return this._textureSamples;
  79109. },
  79110. /**
  79111. * Number of samples to use for antialiasing
  79112. */
  79113. set: function (n) {
  79114. this._textureSamples = n;
  79115. this._originalColorPostProcess.samples = n;
  79116. this._blurHPostProcess.samples = n;
  79117. this._blurVPostProcess.samples = n;
  79118. this._ssaoPostProcess.samples = n;
  79119. this._ssaoCombinePostProcess.samples = n;
  79120. },
  79121. enumerable: true,
  79122. configurable: true
  79123. });
  79124. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  79125. get: function () {
  79126. return this._expensiveBlur;
  79127. },
  79128. set: function (b) {
  79129. 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"]);
  79130. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  79131. this._expensiveBlur = b;
  79132. this._firstUpdate = true;
  79133. },
  79134. enumerable: true,
  79135. configurable: true
  79136. });
  79137. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  79138. /**
  79139. * Support test.
  79140. */
  79141. get: function () {
  79142. var engine = BABYLON.Engine.LastCreatedEngine;
  79143. if (!engine) {
  79144. return false;
  79145. }
  79146. return engine.getCaps().drawBuffersExtension;
  79147. },
  79148. enumerable: true,
  79149. configurable: true
  79150. });
  79151. // Public Methods
  79152. /**
  79153. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  79154. */
  79155. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  79156. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  79157. for (var i = 0; i < this._scene.cameras.length; i++) {
  79158. var camera = this._scene.cameras[i];
  79159. this._originalColorPostProcess.dispose(camera);
  79160. this._ssaoPostProcess.dispose(camera);
  79161. this._blurHPostProcess.dispose(camera);
  79162. this._blurVPostProcess.dispose(camera);
  79163. this._ssaoCombinePostProcess.dispose(camera);
  79164. }
  79165. this._randomTexture.dispose();
  79166. if (disableGeometryBufferRenderer)
  79167. this._scene.disableGeometryBufferRenderer();
  79168. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79169. _super.prototype.dispose.call(this);
  79170. };
  79171. // Private Methods
  79172. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  79173. var _this = this;
  79174. this._samplerOffsets = [];
  79175. var expensive = this.expensiveBlur;
  79176. for (var i = -8; i < 8; i++) {
  79177. this._samplerOffsets.push(i * 2 + 0.5);
  79178. }
  79179. 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");
  79180. this._blurHPostProcess.onApply = function (effect) {
  79181. if (!_this._scene.activeCamera) {
  79182. return;
  79183. }
  79184. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  79185. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79186. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79187. effect.setFloat("radius", _this.radius);
  79188. effect.setTexture("depthSampler", _this._depthTexture);
  79189. if (_this._firstUpdate) {
  79190. effect.setArray("samplerOffsets", _this._samplerOffsets);
  79191. }
  79192. };
  79193. 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");
  79194. this._blurVPostProcess.onApply = function (effect) {
  79195. if (!_this._scene.activeCamera) {
  79196. return;
  79197. }
  79198. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  79199. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79200. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79201. effect.setFloat("radius", _this.radius);
  79202. effect.setTexture("depthSampler", _this._depthTexture);
  79203. if (_this._firstUpdate) {
  79204. effect.setArray("samplerOffsets", _this._samplerOffsets);
  79205. _this._firstUpdate = false;
  79206. }
  79207. };
  79208. this._blurHPostProcess.samples = this.textureSamples;
  79209. this._blurVPostProcess.samples = this.textureSamples;
  79210. };
  79211. /** @hidden */
  79212. SSAO2RenderingPipeline.prototype._rebuild = function () {
  79213. this._firstUpdate = true;
  79214. _super.prototype._rebuild.call(this);
  79215. };
  79216. //Van der Corput radical inverse
  79217. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  79218. this._bits[0] = i;
  79219. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  79220. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  79221. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  79222. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  79223. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  79224. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  79225. };
  79226. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  79227. return [i / n, this._radicalInverse_VdC(i)];
  79228. };
  79229. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  79230. var phi = v * 2.0 * Math.PI;
  79231. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  79232. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  79233. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  79234. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  79235. };
  79236. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  79237. var numSamples = this.samples;
  79238. var result = [];
  79239. var vector;
  79240. var i = 0;
  79241. while (i < numSamples) {
  79242. if (numSamples < 16) {
  79243. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  79244. }
  79245. else {
  79246. var rand = this._hammersley(i, numSamples);
  79247. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  79248. }
  79249. result.push(vector.x, vector.y, vector.z);
  79250. i++;
  79251. }
  79252. return result;
  79253. };
  79254. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  79255. var _this = this;
  79256. var numSamples = this.samples;
  79257. this._sampleSphere = this._generateHemisphere();
  79258. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  79259. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  79260. "base", "range", "projection", "near", "far", "texelSize",
  79261. "xViewport", "yViewport", "maxZ", "minZAspect"
  79262. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  79263. this._ssaoPostProcess.onApply = function (effect) {
  79264. if (_this._firstUpdate) {
  79265. effect.setArray3("sampleSphere", _this._sampleSphere);
  79266. effect.setFloat("randTextureTiles", 32.0);
  79267. }
  79268. if (!_this._scene.activeCamera) {
  79269. return;
  79270. }
  79271. effect.setFloat("samplesFactor", 1 / _this.samples);
  79272. effect.setFloat("totalStrength", _this.totalStrength);
  79273. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  79274. effect.setFloat("radius", _this.radius);
  79275. effect.setFloat("maxZ", _this.maxZ);
  79276. effect.setFloat("minZAspect", _this.minZAspect);
  79277. effect.setFloat("base", _this.base);
  79278. effect.setFloat("near", _this._scene.activeCamera.minZ);
  79279. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  79280. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  79281. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  79282. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  79283. effect.setTexture("textureSampler", _this._depthTexture);
  79284. effect.setTexture("normalSampler", _this._normalTexture);
  79285. effect.setTexture("randomSampler", _this._randomTexture);
  79286. };
  79287. this._ssaoPostProcess.samples = this.textureSamples;
  79288. };
  79289. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  79290. var _this = this;
  79291. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79292. this._ssaoCombinePostProcess.onApply = function (effect) {
  79293. var viewport = _this._scene.activeCamera.viewport;
  79294. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  79295. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  79296. };
  79297. this._ssaoCombinePostProcess.samples = this.textureSamples;
  79298. };
  79299. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  79300. var size = 128;
  79301. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79302. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79303. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79304. var context = this._randomTexture.getContext();
  79305. var rand = function (min, max) {
  79306. return Math.random() * (max - min) + min;
  79307. };
  79308. var randVector = BABYLON.Vector3.Zero();
  79309. for (var x = 0; x < size; x++) {
  79310. for (var y = 0; y < size; y++) {
  79311. randVector.x = rand(0.0, 1.0);
  79312. randVector.y = rand(0.0, 1.0);
  79313. randVector.z = 0.0;
  79314. randVector.normalize();
  79315. randVector.scaleInPlace(255);
  79316. randVector.x = Math.floor(randVector.x);
  79317. randVector.y = Math.floor(randVector.y);
  79318. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  79319. context.fillRect(x, y, 1, 1);
  79320. }
  79321. }
  79322. this._randomTexture.update(false);
  79323. };
  79324. /**
  79325. * Serialize the rendering pipeline (Used when exporting)
  79326. * @returns the serialized object
  79327. */
  79328. SSAO2RenderingPipeline.prototype.serialize = function () {
  79329. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79330. serializationObject.customType = "SSAO2RenderingPipeline";
  79331. return serializationObject;
  79332. };
  79333. /**
  79334. * Parse the serialized pipeline
  79335. * @param source Source pipeline.
  79336. * @param scene The scene to load the pipeline to.
  79337. * @param rootUrl The URL of the serialized pipeline.
  79338. * @returns An instantiated pipeline from the serialized object.
  79339. */
  79340. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  79341. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79342. };
  79343. __decorate([
  79344. BABYLON.serialize()
  79345. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  79346. __decorate([
  79347. BABYLON.serialize()
  79348. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  79349. __decorate([
  79350. BABYLON.serialize()
  79351. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  79352. __decorate([
  79353. BABYLON.serialize("samples")
  79354. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  79355. __decorate([
  79356. BABYLON.serialize("textureSamples")
  79357. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  79358. __decorate([
  79359. BABYLON.serialize()
  79360. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  79361. __decorate([
  79362. BABYLON.serialize("expensiveBlur")
  79363. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  79364. __decorate([
  79365. BABYLON.serialize()
  79366. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  79367. __decorate([
  79368. BABYLON.serialize()
  79369. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  79370. return SSAO2RenderingPipeline;
  79371. }(BABYLON.PostProcessRenderPipeline));
  79372. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  79373. })(BABYLON || (BABYLON = {}));
  79374. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  79375. // BABYLON.JS Chromatic Aberration GLSL Shader
  79376. // Author: Olivier Guyot
  79377. // Separates very slightly R, G and B colors on the edges of the screen
  79378. // Inspired by Francois Tarlier & Martins Upitis
  79379. var BABYLON;
  79380. (function (BABYLON) {
  79381. var LensRenderingPipeline = /** @class */ (function (_super) {
  79382. __extends(LensRenderingPipeline, _super);
  79383. /**
  79384. * @constructor
  79385. *
  79386. * Effect parameters are as follow:
  79387. * {
  79388. * chromatic_aberration: number; // from 0 to x (1 for realism)
  79389. * edge_blur: number; // from 0 to x (1 for realism)
  79390. * distortion: number; // from 0 to x (1 for realism)
  79391. * grain_amount: number; // from 0 to 1
  79392. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  79393. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  79394. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  79395. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  79396. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  79397. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  79398. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  79399. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  79400. * }
  79401. * Note: if an effect parameter is unset, effect is disabled
  79402. *
  79403. * @param {string} name - The rendering pipeline name
  79404. * @param {object} parameters - An object containing all parameters (see above)
  79405. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79406. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  79407. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79408. */
  79409. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  79410. if (ratio === void 0) { ratio = 1.0; }
  79411. var _this = _super.call(this, scene.getEngine(), name) || this;
  79412. // Lens effects can be of the following:
  79413. // - chromatic aberration (slight shift of RGB colors)
  79414. // - blur on the edge of the lens
  79415. // - lens distortion
  79416. // - depth-of-field blur & highlights enhancing
  79417. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  79418. // - grain effect (noise or custom texture)
  79419. // Two additional texture samplers are needed:
  79420. // - depth map (for depth-of-field)
  79421. // - grain texture
  79422. /**
  79423. * The chromatic aberration PostProcess id in the pipeline
  79424. */
  79425. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  79426. /**
  79427. * The highlights enhancing PostProcess id in the pipeline
  79428. */
  79429. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  79430. /**
  79431. * The depth-of-field PostProcess id in the pipeline
  79432. */
  79433. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  79434. _this._scene = scene;
  79435. // Fetch texture samplers
  79436. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  79437. if (parameters.grain_texture) {
  79438. _this._grainTexture = parameters.grain_texture;
  79439. }
  79440. else {
  79441. _this._createGrainTexture();
  79442. }
  79443. // save parameters
  79444. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  79445. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  79446. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  79447. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  79448. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  79449. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  79450. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  79451. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  79452. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  79453. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  79454. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  79455. // Create effects
  79456. _this._createChromaticAberrationPostProcess(ratio);
  79457. _this._createHighlightsPostProcess(ratio);
  79458. _this._createDepthOfFieldPostProcess(ratio / 4);
  79459. // Set up pipeline
  79460. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  79461. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  79462. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  79463. if (_this._highlightsGain === -1) {
  79464. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  79465. }
  79466. // Finish
  79467. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79468. if (cameras) {
  79469. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79470. }
  79471. return _this;
  79472. }
  79473. // public methods (self explanatory)
  79474. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  79475. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  79476. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  79477. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  79478. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  79479. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  79480. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  79481. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  79482. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  79483. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  79484. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  79485. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  79486. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  79487. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  79488. };
  79489. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  79490. this._highlightsPostProcess.updateEffect();
  79491. };
  79492. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  79493. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  79494. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  79495. this._highlightsGain = amount;
  79496. };
  79497. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  79498. if (this._highlightsGain === -1) {
  79499. this._highlightsGain = 1.0;
  79500. }
  79501. this._highlightsThreshold = amount;
  79502. };
  79503. LensRenderingPipeline.prototype.disableHighlights = function () {
  79504. this._highlightsGain = -1;
  79505. };
  79506. /**
  79507. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  79508. */
  79509. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  79510. if (disableDepthRender === void 0) { disableDepthRender = false; }
  79511. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79512. this._chromaticAberrationPostProcess = null;
  79513. this._highlightsPostProcess = null;
  79514. this._depthOfFieldPostProcess = null;
  79515. this._grainTexture.dispose();
  79516. if (disableDepthRender)
  79517. this._scene.disableDepthRenderer();
  79518. };
  79519. // colors shifting and distortion
  79520. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  79521. var _this = this;
  79522. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  79523. [], // samplers
  79524. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79525. this._chromaticAberrationPostProcess.onApply = function (effect) {
  79526. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  79527. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79528. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79529. effect.setFloat('radialIntensity', 1);
  79530. effect.setFloat2('direction', 17, 17);
  79531. effect.setFloat2('centerPosition', 0.5, 0.5);
  79532. };
  79533. };
  79534. // highlights enhancing
  79535. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  79536. var _this = this;
  79537. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  79538. [], // samplers
  79539. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  79540. this._highlightsPostProcess.onApply = function (effect) {
  79541. effect.setFloat('gain', _this._highlightsGain);
  79542. effect.setFloat('threshold', _this._highlightsThreshold);
  79543. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  79544. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79545. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79546. };
  79547. };
  79548. // colors shifting and distortion
  79549. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79550. var _this = this;
  79551. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79552. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79553. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79554. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79555. this._depthOfFieldPostProcess.onApply = function (effect) {
  79556. effect.setTexture("depthSampler", _this._depthTexture);
  79557. effect.setTexture("grainSampler", _this._grainTexture);
  79558. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79559. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79560. effect.setFloat('grain_amount', _this._grainAmount);
  79561. effect.setBool('blur_noise', _this._blurNoise);
  79562. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79563. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79564. effect.setFloat('distortion', _this._distortion);
  79565. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79566. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79567. effect.setFloat('aperture', _this._dofAperture);
  79568. effect.setFloat('darken', _this._dofDarken);
  79569. effect.setFloat('edge_blur', _this._edgeBlur);
  79570. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79571. if (_this._scene.activeCamera) {
  79572. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79573. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79574. }
  79575. };
  79576. };
  79577. // creates a black and white random noise texture, 512x512
  79578. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79579. var size = 512;
  79580. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79581. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79582. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79583. var context = this._grainTexture.getContext();
  79584. var rand = function (min, max) {
  79585. return Math.random() * (max - min) + min;
  79586. };
  79587. var value;
  79588. for (var x = 0; x < size; x++) {
  79589. for (var y = 0; y < size; y++) {
  79590. value = Math.floor(rand(0.42, 0.58) * 255);
  79591. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79592. context.fillRect(x, y, 1, 1);
  79593. }
  79594. }
  79595. this._grainTexture.update(false);
  79596. };
  79597. return LensRenderingPipeline;
  79598. }(BABYLON.PostProcessRenderPipeline));
  79599. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79600. })(BABYLON || (BABYLON = {}));
  79601. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79602. var BABYLON;
  79603. (function (BABYLON) {
  79604. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79605. __extends(StandardRenderingPipeline, _super);
  79606. /**
  79607. * @constructor
  79608. * @param {string} name - The rendering pipeline name
  79609. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79610. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  79611. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79612. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79613. */
  79614. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79615. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79616. var _this = _super.call(this, scene.getEngine(), name) || this;
  79617. /**
  79618. * Post-process used to down scale an image x4
  79619. */
  79620. _this.downSampleX4PostProcess = null;
  79621. /**
  79622. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79623. */
  79624. _this.brightPassPostProcess = null;
  79625. /**
  79626. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79627. */
  79628. _this.blurHPostProcesses = [];
  79629. /**
  79630. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79631. */
  79632. _this.blurVPostProcesses = [];
  79633. /**
  79634. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79635. */
  79636. _this.textureAdderPostProcess = null;
  79637. /**
  79638. * Post-process used to create volumetric lighting effect
  79639. */
  79640. _this.volumetricLightPostProcess = null;
  79641. /**
  79642. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79643. */
  79644. _this.volumetricLightSmoothXPostProcess = null;
  79645. /**
  79646. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79647. */
  79648. _this.volumetricLightSmoothYPostProcess = null;
  79649. /**
  79650. * Post-process used to merge the volumetric light effect and the real scene color
  79651. */
  79652. _this.volumetricLightMergePostProces = null;
  79653. /**
  79654. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79655. */
  79656. _this.volumetricLightFinalPostProcess = null;
  79657. /**
  79658. * Base post-process used to calculate the average luminance of the final image for HDR
  79659. */
  79660. _this.luminancePostProcess = null;
  79661. /**
  79662. * Post-processes used to create down sample post-processes in order to get
  79663. * the average luminance of the final image for HDR
  79664. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79665. */
  79666. _this.luminanceDownSamplePostProcesses = [];
  79667. /**
  79668. * Post-process used to create a HDR effect (light adaptation)
  79669. */
  79670. _this.hdrPostProcess = null;
  79671. /**
  79672. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79673. */
  79674. _this.textureAdderFinalPostProcess = null;
  79675. /**
  79676. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79677. */
  79678. _this.lensFlareFinalPostProcess = null;
  79679. /**
  79680. * Post-process used to merge the final HDR post-process and the real scene color
  79681. */
  79682. _this.hdrFinalPostProcess = null;
  79683. /**
  79684. * Post-process used to create a lens flare effect
  79685. */
  79686. _this.lensFlarePostProcess = null;
  79687. /**
  79688. * Post-process that merges the result of the lens flare post-process and the real scene color
  79689. */
  79690. _this.lensFlareComposePostProcess = null;
  79691. /**
  79692. * Post-process used to create a motion blur effect
  79693. */
  79694. _this.motionBlurPostProcess = null;
  79695. /**
  79696. * Post-process used to create a depth of field effect
  79697. */
  79698. _this.depthOfFieldPostProcess = null;
  79699. /**
  79700. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79701. */
  79702. _this.fxaaPostProcess = null;
  79703. // Values
  79704. /**
  79705. * Represents the brightness threshold in order to configure the illuminated surfaces
  79706. */
  79707. _this.brightThreshold = 1.0;
  79708. /**
  79709. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79710. */
  79711. _this.blurWidth = 512.0;
  79712. /**
  79713. * Sets if the blur for highlighted surfaces must be only horizontal
  79714. */
  79715. _this.horizontalBlur = false;
  79716. /**
  79717. * Sets the overall exposure used by the pipeline
  79718. */
  79719. _this.exposure = 1.0;
  79720. /**
  79721. * Texture used typically to simulate "dirty" on camera lens
  79722. */
  79723. _this.lensTexture = null;
  79724. /**
  79725. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79726. */
  79727. _this.volumetricLightCoefficient = 0.2;
  79728. /**
  79729. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79730. */
  79731. _this.volumetricLightPower = 4.0;
  79732. /**
  79733. * Used the set the blur intensity to smooth the volumetric lights
  79734. */
  79735. _this.volumetricLightBlurScale = 64.0;
  79736. /**
  79737. * Light (spot or directional) used to generate the volumetric lights rays
  79738. * The source light must have a shadow generate so the pipeline can get its
  79739. * depth map
  79740. */
  79741. _this.sourceLight = null;
  79742. /**
  79743. * For eye adaptation, represents the minimum luminance the eye can see
  79744. */
  79745. _this.hdrMinimumLuminance = 1.0;
  79746. /**
  79747. * For eye adaptation, represents the decrease luminance speed
  79748. */
  79749. _this.hdrDecreaseRate = 0.5;
  79750. /**
  79751. * For eye adaptation, represents the increase luminance speed
  79752. */
  79753. _this.hdrIncreaseRate = 0.5;
  79754. /**
  79755. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79756. */
  79757. _this.lensColorTexture = null;
  79758. /**
  79759. * The overall strengh for the lens flare effect
  79760. */
  79761. _this.lensFlareStrength = 20.0;
  79762. /**
  79763. * Dispersion coefficient for lens flare ghosts
  79764. */
  79765. _this.lensFlareGhostDispersal = 1.4;
  79766. /**
  79767. * Main lens flare halo width
  79768. */
  79769. _this.lensFlareHaloWidth = 0.7;
  79770. /**
  79771. * Based on the lens distortion effect, defines how much the lens flare result
  79772. * is distorted
  79773. */
  79774. _this.lensFlareDistortionStrength = 16.0;
  79775. /**
  79776. * Lens star texture must be used to simulate rays on the flares and is available
  79777. * in the documentation
  79778. */
  79779. _this.lensStarTexture = null;
  79780. /**
  79781. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79782. * flare effect by taking account of the dirt texture
  79783. */
  79784. _this.lensFlareDirtTexture = null;
  79785. /**
  79786. * Represents the focal length for the depth of field effect
  79787. */
  79788. _this.depthOfFieldDistance = 10.0;
  79789. /**
  79790. * Represents the blur intensity for the blurred part of the depth of field effect
  79791. */
  79792. _this.depthOfFieldBlurWidth = 64.0;
  79793. /**
  79794. * For motion blur, defines how much the image is blurred by the movement
  79795. */
  79796. _this.motionStrength = 1.0;
  79797. /**
  79798. * List of animations for the pipeline (IAnimatable implementation)
  79799. */
  79800. _this.animations = [];
  79801. _this._currentDepthOfFieldSource = null;
  79802. _this._hdrCurrentLuminance = 1.0;
  79803. // Getters and setters
  79804. _this._bloomEnabled = false;
  79805. _this._depthOfFieldEnabled = false;
  79806. _this._vlsEnabled = false;
  79807. _this._lensFlareEnabled = false;
  79808. _this._hdrEnabled = false;
  79809. _this._motionBlurEnabled = false;
  79810. _this._fxaaEnabled = false;
  79811. _this._motionBlurSamples = 64.0;
  79812. _this._volumetricLightStepsCount = 50.0;
  79813. _this._samples = 1;
  79814. _this._cameras = cameras || [];
  79815. // Initialize
  79816. _this._scene = scene;
  79817. _this._basePostProcess = originalPostProcess;
  79818. _this._ratio = ratio;
  79819. // Misc
  79820. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79821. // Finish
  79822. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79823. _this._buildPipeline();
  79824. return _this;
  79825. }
  79826. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79827. /**
  79828. * Specifies if the bloom pipeline is enabled
  79829. */
  79830. get: function () {
  79831. return this._bloomEnabled;
  79832. },
  79833. set: function (enabled) {
  79834. if (this._bloomEnabled === enabled) {
  79835. return;
  79836. }
  79837. this._bloomEnabled = enabled;
  79838. this._buildPipeline();
  79839. },
  79840. enumerable: true,
  79841. configurable: true
  79842. });
  79843. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79844. /**
  79845. * Specifies if the depth of field pipeline is enabed
  79846. */
  79847. get: function () {
  79848. return this._depthOfFieldEnabled;
  79849. },
  79850. set: function (enabled) {
  79851. if (this._depthOfFieldEnabled === enabled) {
  79852. return;
  79853. }
  79854. this._depthOfFieldEnabled = enabled;
  79855. this._buildPipeline();
  79856. },
  79857. enumerable: true,
  79858. configurable: true
  79859. });
  79860. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79861. /**
  79862. * Specifies if the lens flare pipeline is enabed
  79863. */
  79864. get: function () {
  79865. return this._lensFlareEnabled;
  79866. },
  79867. set: function (enabled) {
  79868. if (this._lensFlareEnabled === enabled) {
  79869. return;
  79870. }
  79871. this._lensFlareEnabled = enabled;
  79872. this._buildPipeline();
  79873. },
  79874. enumerable: true,
  79875. configurable: true
  79876. });
  79877. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79878. /**
  79879. * Specifies if the HDR pipeline is enabled
  79880. */
  79881. get: function () {
  79882. return this._hdrEnabled;
  79883. },
  79884. set: function (enabled) {
  79885. if (this._hdrEnabled === enabled) {
  79886. return;
  79887. }
  79888. this._hdrEnabled = enabled;
  79889. this._buildPipeline();
  79890. },
  79891. enumerable: true,
  79892. configurable: true
  79893. });
  79894. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79895. /**
  79896. * Specifies if the volumetric lights scattering effect is enabled
  79897. */
  79898. get: function () {
  79899. return this._vlsEnabled;
  79900. },
  79901. set: function (enabled) {
  79902. if (this._vlsEnabled === enabled) {
  79903. return;
  79904. }
  79905. if (enabled) {
  79906. var geometry = this._scene.enableGeometryBufferRenderer();
  79907. if (!geometry) {
  79908. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79909. return;
  79910. }
  79911. }
  79912. this._vlsEnabled = enabled;
  79913. this._buildPipeline();
  79914. },
  79915. enumerable: true,
  79916. configurable: true
  79917. });
  79918. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79919. /**
  79920. * Specifies if the motion blur effect is enabled
  79921. */
  79922. get: function () {
  79923. return this._motionBlurEnabled;
  79924. },
  79925. set: function (enabled) {
  79926. if (this._motionBlurEnabled === enabled) {
  79927. return;
  79928. }
  79929. this._motionBlurEnabled = enabled;
  79930. this._buildPipeline();
  79931. },
  79932. enumerable: true,
  79933. configurable: true
  79934. });
  79935. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79936. /**
  79937. * Specifies if anti-aliasing is enabled
  79938. */
  79939. get: function () {
  79940. return this._fxaaEnabled;
  79941. },
  79942. set: function (enabled) {
  79943. if (this._fxaaEnabled === enabled) {
  79944. return;
  79945. }
  79946. this._fxaaEnabled = enabled;
  79947. this._buildPipeline();
  79948. },
  79949. enumerable: true,
  79950. configurable: true
  79951. });
  79952. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79953. /**
  79954. * Specifies the number of steps used to calculate the volumetric lights
  79955. * Typically in interval [50, 200]
  79956. */
  79957. get: function () {
  79958. return this._volumetricLightStepsCount;
  79959. },
  79960. set: function (count) {
  79961. if (this.volumetricLightPostProcess) {
  79962. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79963. }
  79964. this._volumetricLightStepsCount = count;
  79965. },
  79966. enumerable: true,
  79967. configurable: true
  79968. });
  79969. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79970. /**
  79971. * Specifies the number of samples used for the motion blur effect
  79972. * Typically in interval [16, 64]
  79973. */
  79974. get: function () {
  79975. return this._motionBlurSamples;
  79976. },
  79977. set: function (samples) {
  79978. if (this.motionBlurPostProcess) {
  79979. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79980. }
  79981. this._motionBlurSamples = samples;
  79982. },
  79983. enumerable: true,
  79984. configurable: true
  79985. });
  79986. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79987. /**
  79988. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79989. */
  79990. get: function () {
  79991. return this._samples;
  79992. },
  79993. set: function (sampleCount) {
  79994. if (this._samples === sampleCount) {
  79995. return;
  79996. }
  79997. this._samples = sampleCount;
  79998. this._buildPipeline();
  79999. },
  80000. enumerable: true,
  80001. configurable: true
  80002. });
  80003. StandardRenderingPipeline.prototype._buildPipeline = function () {
  80004. var _this = this;
  80005. var ratio = this._ratio;
  80006. var scene = this._scene;
  80007. this._disposePostProcesses();
  80008. this._reset();
  80009. // Create pass post-process
  80010. if (!this._basePostProcess) {
  80011. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  80012. this.originalPostProcess.onApply = function (effect) {
  80013. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  80014. };
  80015. }
  80016. else {
  80017. this.originalPostProcess = this._basePostProcess;
  80018. }
  80019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  80020. this._currentDepthOfFieldSource = this.originalPostProcess;
  80021. if (this._bloomEnabled) {
  80022. // Create down sample X4 post-process
  80023. this._createDownSampleX4PostProcess(scene, ratio / 2);
  80024. // Create bright pass post-process
  80025. this._createBrightPassPostProcess(scene, ratio / 2);
  80026. // Create gaussian blur post-processes (down sampling blurs)
  80027. this._createBlurPostProcesses(scene, ratio / 4, 1);
  80028. // Create texture adder post-process
  80029. this._createTextureAdderPostProcess(scene, ratio);
  80030. // Create depth-of-field source post-process
  80031. 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);
  80032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  80033. }
  80034. if (this._vlsEnabled) {
  80035. // Create volumetric light
  80036. this._createVolumetricLightPostProcess(scene, ratio);
  80037. // Create volumetric light final post-process
  80038. 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);
  80039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  80040. }
  80041. if (this._lensFlareEnabled) {
  80042. // Create lens flare post-process
  80043. this._createLensFlarePostProcess(scene, ratio);
  80044. // Create depth-of-field source post-process post lens-flare and disable it now
  80045. 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);
  80046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  80047. }
  80048. if (this._hdrEnabled) {
  80049. // Create luminance
  80050. this._createLuminancePostProcesses(scene, this._floatTextureType);
  80051. // Create HDR
  80052. this._createHdrPostProcess(scene, ratio);
  80053. // Create depth-of-field source post-process post hdr and disable it now
  80054. 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);
  80055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  80056. }
  80057. if (this._depthOfFieldEnabled) {
  80058. // Create gaussian blur used by depth-of-field
  80059. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  80060. // Create depth-of-field post-process
  80061. this._createDepthOfFieldPostProcess(scene, ratio);
  80062. }
  80063. if (this._motionBlurEnabled) {
  80064. // Create motion blur post-process
  80065. this._createMotionBlurPostProcess(scene, ratio);
  80066. }
  80067. if (this._fxaaEnabled) {
  80068. // Create fxaa post-process
  80069. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80070. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  80071. }
  80072. if (this._cameras !== null) {
  80073. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80074. }
  80075. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  80076. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80077. }
  80078. };
  80079. // Down Sample X4 Post-Processs
  80080. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  80081. var _this = this;
  80082. var downSampleX4Offsets = new Array(32);
  80083. 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);
  80084. this.downSampleX4PostProcess.onApply = function (effect) {
  80085. var id = 0;
  80086. var width = _this.downSampleX4PostProcess.width;
  80087. var height = _this.downSampleX4PostProcess.height;
  80088. for (var i = -2; i < 2; i++) {
  80089. for (var j = -2; j < 2; j++) {
  80090. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  80091. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  80092. id += 2;
  80093. }
  80094. }
  80095. effect.setArray2("dsOffsets", downSampleX4Offsets);
  80096. };
  80097. // Add to pipeline
  80098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  80099. };
  80100. // Brightpass Post-Process
  80101. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  80102. var _this = this;
  80103. var brightOffsets = new Array(8);
  80104. 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);
  80105. this.brightPassPostProcess.onApply = function (effect) {
  80106. var sU = (1.0 / _this.brightPassPostProcess.width);
  80107. var sV = (1.0 / _this.brightPassPostProcess.height);
  80108. brightOffsets[0] = -0.5 * sU;
  80109. brightOffsets[1] = 0.5 * sV;
  80110. brightOffsets[2] = 0.5 * sU;
  80111. brightOffsets[3] = 0.5 * sV;
  80112. brightOffsets[4] = -0.5 * sU;
  80113. brightOffsets[5] = -0.5 * sV;
  80114. brightOffsets[6] = 0.5 * sU;
  80115. brightOffsets[7] = -0.5 * sV;
  80116. effect.setArray2("dsOffsets", brightOffsets);
  80117. effect.setFloat("brightThreshold", _this.brightThreshold);
  80118. };
  80119. // Add to pipeline
  80120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  80121. };
  80122. // Create blur H&V post-processes
  80123. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  80124. var _this = this;
  80125. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  80126. var engine = scene.getEngine();
  80127. 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);
  80128. 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);
  80129. blurX.onActivateObservable.add(function () {
  80130. var dw = blurX.width / engine.getRenderWidth();
  80131. blurX.kernel = _this[blurWidthKey] * dw;
  80132. });
  80133. blurY.onActivateObservable.add(function () {
  80134. var dw = blurY.height / engine.getRenderHeight();
  80135. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  80136. });
  80137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  80138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  80139. this.blurHPostProcesses.push(blurX);
  80140. this.blurVPostProcesses.push(blurY);
  80141. };
  80142. // Create texture adder post-process
  80143. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  80144. var _this = this;
  80145. 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);
  80146. this.textureAdderPostProcess.onApply = function (effect) {
  80147. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  80148. effect.setTexture("lensSampler", _this.lensTexture);
  80149. effect.setFloat("exposure", _this.exposure);
  80150. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  80151. };
  80152. // Add to pipeline
  80153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  80154. };
  80155. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  80156. var _this = this;
  80157. var geometryRenderer = scene.enableGeometryBufferRenderer();
  80158. geometryRenderer.enablePosition = true;
  80159. var geometry = geometryRenderer.getGBuffer();
  80160. // Base post-process
  80161. 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));
  80162. var depthValues = BABYLON.Vector2.Zero();
  80163. this.volumetricLightPostProcess.onApply = function (effect) {
  80164. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  80165. var generator = _this.sourceLight.getShadowGenerator();
  80166. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  80167. effect.setTexture("positionSampler", geometry.textures[2]);
  80168. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  80169. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  80170. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  80171. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  80172. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  80173. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  80174. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  80175. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  80176. effect.setVector2("depthValues", depthValues);
  80177. }
  80178. };
  80179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  80180. // Smooth
  80181. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  80182. // Merge
  80183. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  80184. this.volumetricLightMergePostProces.onApply = function (effect) {
  80185. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  80186. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  80187. };
  80188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  80189. };
  80190. // Create luminance
  80191. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  80192. var _this = this;
  80193. // Create luminance
  80194. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  80195. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  80196. var offsets = [];
  80197. this.luminancePostProcess.onApply = function (effect) {
  80198. var sU = (1.0 / _this.luminancePostProcess.width);
  80199. var sV = (1.0 / _this.luminancePostProcess.height);
  80200. offsets[0] = -0.5 * sU;
  80201. offsets[1] = 0.5 * sV;
  80202. offsets[2] = 0.5 * sU;
  80203. offsets[3] = 0.5 * sV;
  80204. offsets[4] = -0.5 * sU;
  80205. offsets[5] = -0.5 * sV;
  80206. offsets[6] = 0.5 * sU;
  80207. offsets[7] = -0.5 * sV;
  80208. effect.setArray2("lumOffsets", offsets);
  80209. };
  80210. // Add to pipeline
  80211. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  80212. // Create down sample luminance
  80213. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  80214. var size = Math.pow(3, i);
  80215. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  80216. if (i === 0) {
  80217. defines += "#define FINAL_DOWN_SAMPLER";
  80218. }
  80219. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  80220. this.luminanceDownSamplePostProcesses.push(postProcess);
  80221. }
  80222. // Create callbacks and add effects
  80223. var lastLuminance = this.luminancePostProcess;
  80224. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  80225. var downSampleOffsets = new Array(18);
  80226. pp.onApply = function (effect) {
  80227. if (!lastLuminance) {
  80228. return;
  80229. }
  80230. var id = 0;
  80231. for (var x = -1; x < 2; x++) {
  80232. for (var y = -1; y < 2; y++) {
  80233. downSampleOffsets[id] = x / lastLuminance.width;
  80234. downSampleOffsets[id + 1] = y / lastLuminance.height;
  80235. id += 2;
  80236. }
  80237. }
  80238. effect.setArray2("dsOffsets", downSampleOffsets);
  80239. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  80240. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  80241. lastLuminance = _this.luminancePostProcess;
  80242. }
  80243. else {
  80244. lastLuminance = pp;
  80245. }
  80246. };
  80247. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  80248. pp.onAfterRender = function (effect) {
  80249. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  80250. 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);
  80251. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  80252. };
  80253. }
  80254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  80255. });
  80256. };
  80257. // Create HDR post-process
  80258. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  80259. var _this = this;
  80260. 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);
  80261. var outputLiminance = 1;
  80262. var time = 0;
  80263. var lastTime = 0;
  80264. this.hdrPostProcess.onApply = function (effect) {
  80265. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  80266. time += scene.getEngine().getDeltaTime();
  80267. if (outputLiminance < 0) {
  80268. outputLiminance = _this._hdrCurrentLuminance;
  80269. }
  80270. else {
  80271. var dt = (lastTime - time) / 1000.0;
  80272. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  80273. outputLiminance += _this.hdrDecreaseRate * dt;
  80274. }
  80275. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  80276. outputLiminance -= _this.hdrIncreaseRate * dt;
  80277. }
  80278. else {
  80279. outputLiminance = _this._hdrCurrentLuminance;
  80280. }
  80281. }
  80282. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  80283. effect.setFloat("averageLuminance", outputLiminance);
  80284. lastTime = time;
  80285. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  80286. };
  80287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  80288. };
  80289. // Create lens flare post-process
  80290. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  80291. var _this = this;
  80292. 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);
  80293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  80294. this._createBlurPostProcesses(scene, ratio / 4, 2);
  80295. 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);
  80296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  80297. var resolution = new BABYLON.Vector2(0, 0);
  80298. // Lens flare
  80299. this.lensFlarePostProcess.onApply = function (effect) {
  80300. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  80301. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  80302. effect.setFloat("strength", _this.lensFlareStrength);
  80303. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  80304. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  80305. // Shift
  80306. resolution.x = _this.lensFlarePostProcess.width;
  80307. resolution.y = _this.lensFlarePostProcess.height;
  80308. effect.setVector2("resolution", resolution);
  80309. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  80310. };
  80311. // Compose
  80312. 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);
  80313. 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);
  80314. this.lensFlareComposePostProcess.onApply = function (effect) {
  80315. if (!_this._scene.activeCamera) {
  80316. return;
  80317. }
  80318. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80319. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  80320. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  80321. // Lens start rotation matrix
  80322. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  80323. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  80324. 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));
  80325. camRot *= 4.0;
  80326. 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);
  80327. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  80328. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  80329. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  80330. };
  80331. };
  80332. // Create depth-of-field post-process
  80333. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  80334. var _this = this;
  80335. 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);
  80336. this.depthOfFieldPostProcess.onApply = function (effect) {
  80337. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80338. effect.setTexture("depthSampler", _this._getDepthTexture());
  80339. effect.setFloat("distance", _this.depthOfFieldDistance);
  80340. };
  80341. // Add to pipeline
  80342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  80343. };
  80344. // Create motion blur post-process
  80345. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  80346. var _this = this;
  80347. 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);
  80348. var motionScale = 0;
  80349. var prevViewProjection = BABYLON.Matrix.Identity();
  80350. var invViewProjection = BABYLON.Matrix.Identity();
  80351. var viewProjection = BABYLON.Matrix.Identity();
  80352. var screenSize = BABYLON.Vector2.Zero();
  80353. this.motionBlurPostProcess.onApply = function (effect) {
  80354. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  80355. viewProjection.invertToRef(invViewProjection);
  80356. effect.setMatrix("inverseViewProjection", invViewProjection);
  80357. effect.setMatrix("prevViewProjection", prevViewProjection);
  80358. prevViewProjection = viewProjection;
  80359. screenSize.x = _this.motionBlurPostProcess.width;
  80360. screenSize.y = _this.motionBlurPostProcess.height;
  80361. effect.setVector2("screenSize", screenSize);
  80362. motionScale = scene.getEngine().getFps() / 60.0;
  80363. effect.setFloat("motionScale", motionScale);
  80364. effect.setFloat("motionStrength", _this.motionStrength);
  80365. effect.setTexture("depthSampler", _this._getDepthTexture());
  80366. };
  80367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  80368. };
  80369. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  80370. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  80371. var renderer = this._scene.enableGeometryBufferRenderer();
  80372. return renderer.getGBuffer().textures[0];
  80373. }
  80374. return this._scene.enableDepthRenderer().getDepthMap();
  80375. };
  80376. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  80377. for (var i = 0; i < this._cameras.length; i++) {
  80378. var camera = this._cameras[i];
  80379. if (this.originalPostProcess) {
  80380. this.originalPostProcess.dispose(camera);
  80381. }
  80382. if (this.downSampleX4PostProcess) {
  80383. this.downSampleX4PostProcess.dispose(camera);
  80384. }
  80385. if (this.brightPassPostProcess) {
  80386. this.brightPassPostProcess.dispose(camera);
  80387. }
  80388. if (this.textureAdderPostProcess) {
  80389. this.textureAdderPostProcess.dispose(camera);
  80390. }
  80391. if (this.textureAdderFinalPostProcess) {
  80392. this.textureAdderFinalPostProcess.dispose(camera);
  80393. }
  80394. if (this.volumetricLightPostProcess) {
  80395. this.volumetricLightPostProcess.dispose(camera);
  80396. }
  80397. if (this.volumetricLightSmoothXPostProcess) {
  80398. this.volumetricLightSmoothXPostProcess.dispose(camera);
  80399. }
  80400. if (this.volumetricLightSmoothYPostProcess) {
  80401. this.volumetricLightSmoothYPostProcess.dispose(camera);
  80402. }
  80403. if (this.volumetricLightMergePostProces) {
  80404. this.volumetricLightMergePostProces.dispose(camera);
  80405. }
  80406. if (this.volumetricLightFinalPostProcess) {
  80407. this.volumetricLightFinalPostProcess.dispose(camera);
  80408. }
  80409. if (this.lensFlarePostProcess) {
  80410. this.lensFlarePostProcess.dispose(camera);
  80411. }
  80412. if (this.lensFlareComposePostProcess) {
  80413. this.lensFlareComposePostProcess.dispose(camera);
  80414. }
  80415. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  80416. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  80417. }
  80418. if (this.luminancePostProcess) {
  80419. this.luminancePostProcess.dispose(camera);
  80420. }
  80421. if (this.hdrPostProcess) {
  80422. this.hdrPostProcess.dispose(camera);
  80423. }
  80424. if (this.hdrFinalPostProcess) {
  80425. this.hdrFinalPostProcess.dispose(camera);
  80426. }
  80427. if (this.depthOfFieldPostProcess) {
  80428. this.depthOfFieldPostProcess.dispose(camera);
  80429. }
  80430. if (this.motionBlurPostProcess) {
  80431. this.motionBlurPostProcess.dispose(camera);
  80432. }
  80433. if (this.fxaaPostProcess) {
  80434. this.fxaaPostProcess.dispose(camera);
  80435. }
  80436. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  80437. this.blurHPostProcesses[j].dispose(camera);
  80438. }
  80439. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  80440. this.blurVPostProcesses[j].dispose(camera);
  80441. }
  80442. }
  80443. this.originalPostProcess = null;
  80444. this.downSampleX4PostProcess = null;
  80445. this.brightPassPostProcess = null;
  80446. this.textureAdderPostProcess = null;
  80447. this.textureAdderFinalPostProcess = null;
  80448. this.volumetricLightPostProcess = null;
  80449. this.volumetricLightSmoothXPostProcess = null;
  80450. this.volumetricLightSmoothYPostProcess = null;
  80451. this.volumetricLightMergePostProces = null;
  80452. this.volumetricLightFinalPostProcess = null;
  80453. this.lensFlarePostProcess = null;
  80454. this.lensFlareComposePostProcess = null;
  80455. this.luminancePostProcess = null;
  80456. this.hdrPostProcess = null;
  80457. this.hdrFinalPostProcess = null;
  80458. this.depthOfFieldPostProcess = null;
  80459. this.motionBlurPostProcess = null;
  80460. this.fxaaPostProcess = null;
  80461. this.luminanceDownSamplePostProcesses = [];
  80462. this.blurHPostProcesses = [];
  80463. this.blurVPostProcesses = [];
  80464. };
  80465. /**
  80466. * Dispose of the pipeline and stop all post processes
  80467. */
  80468. StandardRenderingPipeline.prototype.dispose = function () {
  80469. this._disposePostProcesses();
  80470. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80471. _super.prototype.dispose.call(this);
  80472. };
  80473. /**
  80474. * Serialize the rendering pipeline (Used when exporting)
  80475. * @returns the serialized object
  80476. */
  80477. StandardRenderingPipeline.prototype.serialize = function () {
  80478. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80479. if (this.sourceLight) {
  80480. serializationObject.sourceLightId = this.sourceLight.id;
  80481. }
  80482. serializationObject.customType = "StandardRenderingPipeline";
  80483. return serializationObject;
  80484. };
  80485. /**
  80486. * Parse the serialized pipeline
  80487. * @param source Source pipeline.
  80488. * @param scene The scene to load the pipeline to.
  80489. * @param rootUrl The URL of the serialized pipeline.
  80490. * @returns An instantiated pipeline from the serialized object.
  80491. */
  80492. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80493. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80494. if (source.sourceLightId) {
  80495. p.sourceLight = scene.getLightByID(source.sourceLightId);
  80496. }
  80497. return p;
  80498. };
  80499. // Luminance steps
  80500. StandardRenderingPipeline.LuminanceSteps = 6;
  80501. __decorate([
  80502. BABYLON.serialize()
  80503. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  80504. __decorate([
  80505. BABYLON.serialize()
  80506. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  80507. __decorate([
  80508. BABYLON.serialize()
  80509. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  80510. __decorate([
  80511. BABYLON.serialize()
  80512. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  80513. __decorate([
  80514. BABYLON.serializeAsTexture("lensTexture")
  80515. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  80516. __decorate([
  80517. BABYLON.serialize()
  80518. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  80519. __decorate([
  80520. BABYLON.serialize()
  80521. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  80522. __decorate([
  80523. BABYLON.serialize()
  80524. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  80525. __decorate([
  80526. BABYLON.serialize()
  80527. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  80528. __decorate([
  80529. BABYLON.serialize()
  80530. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  80531. __decorate([
  80532. BABYLON.serialize()
  80533. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  80534. __decorate([
  80535. BABYLON.serializeAsTexture("lensColorTexture")
  80536. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  80537. __decorate([
  80538. BABYLON.serialize()
  80539. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  80540. __decorate([
  80541. BABYLON.serialize()
  80542. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  80543. __decorate([
  80544. BABYLON.serialize()
  80545. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  80546. __decorate([
  80547. BABYLON.serialize()
  80548. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80549. __decorate([
  80550. BABYLON.serializeAsTexture("lensStarTexture")
  80551. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80552. __decorate([
  80553. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80554. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80555. __decorate([
  80556. BABYLON.serialize()
  80557. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80558. __decorate([
  80559. BABYLON.serialize()
  80560. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80561. __decorate([
  80562. BABYLON.serialize()
  80563. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80564. __decorate([
  80565. BABYLON.serialize()
  80566. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80567. __decorate([
  80568. BABYLON.serialize()
  80569. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80570. __decorate([
  80571. BABYLON.serialize()
  80572. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80573. __decorate([
  80574. BABYLON.serialize()
  80575. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80576. __decorate([
  80577. BABYLON.serialize()
  80578. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80579. __decorate([
  80580. BABYLON.serialize()
  80581. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80582. __decorate([
  80583. BABYLON.serialize()
  80584. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80585. __decorate([
  80586. BABYLON.serialize()
  80587. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80588. __decorate([
  80589. BABYLON.serialize()
  80590. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80591. __decorate([
  80592. BABYLON.serialize()
  80593. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80594. __decorate([
  80595. BABYLON.serialize()
  80596. ], StandardRenderingPipeline.prototype, "samples", null);
  80597. return StandardRenderingPipeline;
  80598. }(BABYLON.PostProcessRenderPipeline));
  80599. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80600. })(BABYLON || (BABYLON = {}));
  80601. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80602. var BABYLON;
  80603. (function (BABYLON) {
  80604. var FxaaPostProcess = /** @class */ (function (_super) {
  80605. __extends(FxaaPostProcess, _super);
  80606. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80607. if (camera === void 0) { camera = null; }
  80608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80609. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80610. var defines = _this._getDefines();
  80611. _this.updateEffect(defines);
  80612. _this.onApplyObservable.add(function (effect) {
  80613. var texelSize = _this.texelSize;
  80614. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80615. });
  80616. return _this;
  80617. }
  80618. FxaaPostProcess.prototype._getDefines = function () {
  80619. var engine = this.getEngine();
  80620. if (!engine) {
  80621. return null;
  80622. }
  80623. var glInfo = engine.getGlInfo();
  80624. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80625. return "#define MALI 1\n";
  80626. }
  80627. return null;
  80628. };
  80629. return FxaaPostProcess;
  80630. }(BABYLON.PostProcess));
  80631. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80632. })(BABYLON || (BABYLON = {}));
  80633. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80634. var BABYLON;
  80635. (function (BABYLON) {
  80636. /**
  80637. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80638. */
  80639. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80640. __extends(ChromaticAberrationPostProcess, _super);
  80641. /**
  80642. * Creates a new instance ChromaticAberrationPostProcess
  80643. * @param name The name of the effect.
  80644. * @param screenWidth The width of the screen to apply the effect on.
  80645. * @param screenHeight The height of the screen to apply the effect on.
  80646. * @param options The required width/height ratio to downsize to before computing the render pass.
  80647. * @param camera The camera to apply the render pass to.
  80648. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80649. * @param engine The engine which the post process will be applied. (default: current engine)
  80650. * @param reusable If the post process can be reused on the same frame. (default: false)
  80651. * @param textureType Type of textures used when performing the post process. (default: 0)
  80652. * @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)
  80653. */
  80654. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80655. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80656. if (blockCompilation === void 0) { blockCompilation = false; }
  80657. 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;
  80658. /**
  80659. * The amount of seperation of rgb channels (default: 30)
  80660. */
  80661. _this.aberrationAmount = 30;
  80662. /**
  80663. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80664. */
  80665. _this.radialIntensity = 0;
  80666. /**
  80667. * 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))
  80668. */
  80669. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80670. /**
  80671. * 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))
  80672. */
  80673. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80674. _this.onApplyObservable.add(function (effect) {
  80675. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80676. effect.setFloat('screen_width', screenWidth);
  80677. effect.setFloat('screen_height', screenHeight);
  80678. effect.setFloat('radialIntensity', _this.radialIntensity);
  80679. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80680. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80681. });
  80682. return _this;
  80683. }
  80684. return ChromaticAberrationPostProcess;
  80685. }(BABYLON.PostProcess));
  80686. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80687. })(BABYLON || (BABYLON = {}));
  80688. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80689. var BABYLON;
  80690. (function (BABYLON) {
  80691. /**
  80692. * The GrainPostProcess adds noise to the image at mid luminance levels
  80693. */
  80694. var GrainPostProcess = /** @class */ (function (_super) {
  80695. __extends(GrainPostProcess, _super);
  80696. /**
  80697. * Creates a new instance of @see GrainPostProcess
  80698. * @param name The name of the effect.
  80699. * @param options The required width/height ratio to downsize to before computing the render pass.
  80700. * @param camera The camera to apply the render pass to.
  80701. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80702. * @param engine The engine which the post process will be applied. (default: current engine)
  80703. * @param reusable If the post process can be reused on the same frame. (default: false)
  80704. * @param textureType Type of textures used when performing the post process. (default: 0)
  80705. * @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)
  80706. */
  80707. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80709. if (blockCompilation === void 0) { blockCompilation = false; }
  80710. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80711. /**
  80712. * The intensity of the grain added (default: 30)
  80713. */
  80714. _this.intensity = 30;
  80715. /**
  80716. * If the grain should be randomized on every frame
  80717. */
  80718. _this.animated = false;
  80719. _this.onApplyObservable.add(function (effect) {
  80720. effect.setFloat('intensity', _this.intensity);
  80721. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80722. });
  80723. return _this;
  80724. }
  80725. return GrainPostProcess;
  80726. }(BABYLON.PostProcess));
  80727. BABYLON.GrainPostProcess = GrainPostProcess;
  80728. })(BABYLON || (BABYLON = {}));
  80729. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80730. var BABYLON;
  80731. (function (BABYLON) {
  80732. /**
  80733. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80734. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80735. */
  80736. var SharpenPostProcess = /** @class */ (function (_super) {
  80737. __extends(SharpenPostProcess, _super);
  80738. /**
  80739. * Creates a new instance ConvolutionPostProcess
  80740. * @param name The name of the effect.
  80741. * @param options The required width/height ratio to downsize to before computing the render pass.
  80742. * @param camera The camera to apply the render pass to.
  80743. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80744. * @param engine The engine which the post process will be applied. (default: current engine)
  80745. * @param reusable If the post process can be reused on the same frame. (default: false)
  80746. * @param textureType Type of textures used when performing the post process. (default: 0)
  80747. * @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)
  80748. */
  80749. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80751. if (blockCompilation === void 0) { blockCompilation = false; }
  80752. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80753. /**
  80754. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80755. */
  80756. _this.colorAmount = 1.0;
  80757. /**
  80758. * How much sharpness should be applied (default: 0.3)
  80759. */
  80760. _this.edgeAmount = 0.3;
  80761. _this.onApply = function (effect) {
  80762. effect.setFloat2("screenSize", _this.width, _this.height);
  80763. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80764. };
  80765. return _this;
  80766. }
  80767. return SharpenPostProcess;
  80768. }(BABYLON.PostProcess));
  80769. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80770. })(BABYLON || (BABYLON = {}));
  80771. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80772. var BABYLON;
  80773. (function (BABYLON) {
  80774. /**
  80775. * The Blur Post Process which blurs an image based on a kernel and direction.
  80776. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80777. */
  80778. var BlurPostProcess = /** @class */ (function (_super) {
  80779. __extends(BlurPostProcess, _super);
  80780. /**
  80781. * Creates a new instance BlurPostProcess
  80782. * @param name The name of the effect.
  80783. * @param direction The direction in which to blur the image.
  80784. * @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.
  80785. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80786. * @param camera The camera to apply the render pass to.
  80787. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80788. * @param engine The engine which the post process will be applied. (default: current engine)
  80789. * @param reusable If the post process can be reused on the same frame. (default: false)
  80790. * @param textureType Type of textures used when performing the post process. (default: 0)
  80791. * @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)
  80792. */
  80793. function BlurPostProcess(name,
  80794. /** The direction in which to blur the image. */
  80795. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80798. if (defines === void 0) { defines = ""; }
  80799. if (blockCompilation === void 0) { blockCompilation = false; }
  80800. 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;
  80801. _this.direction = direction;
  80802. _this.blockCompilation = blockCompilation;
  80803. _this._packedFloat = false;
  80804. _this._staticDefines = "";
  80805. _this._staticDefines = defines;
  80806. _this.onApplyObservable.add(function (effect) {
  80807. if (_this._outputTexture) {
  80808. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80809. }
  80810. else {
  80811. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80812. }
  80813. });
  80814. _this.kernel = kernel;
  80815. return _this;
  80816. }
  80817. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80818. /**
  80819. * Gets the length in pixels of the blur sample region
  80820. */
  80821. get: function () {
  80822. return this._idealKernel;
  80823. },
  80824. /**
  80825. * Sets the length in pixels of the blur sample region
  80826. */
  80827. set: function (v) {
  80828. if (this._idealKernel === v) {
  80829. return;
  80830. }
  80831. v = Math.max(v, 1);
  80832. this._idealKernel = v;
  80833. this._kernel = this._nearestBestKernel(v);
  80834. if (!this.blockCompilation) {
  80835. this._updateParameters();
  80836. }
  80837. },
  80838. enumerable: true,
  80839. configurable: true
  80840. });
  80841. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80842. /**
  80843. * Gets wether or not the blur is unpacking/repacking floats
  80844. */
  80845. get: function () {
  80846. return this._packedFloat;
  80847. },
  80848. /**
  80849. * Sets wether or not the blur needs to unpack/repack floats
  80850. */
  80851. set: function (v) {
  80852. if (this._packedFloat === v) {
  80853. return;
  80854. }
  80855. this._packedFloat = v;
  80856. if (!this.blockCompilation) {
  80857. this._updateParameters();
  80858. }
  80859. },
  80860. enumerable: true,
  80861. configurable: true
  80862. });
  80863. /**
  80864. * Updates the effect with the current post process compile time values and recompiles the shader.
  80865. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80866. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80867. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80868. * @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
  80869. * @param onCompiled Called when the shader has been compiled.
  80870. * @param onError Called if there is an error when compiling a shader.
  80871. */
  80872. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80873. if (defines === void 0) { defines = null; }
  80874. if (uniforms === void 0) { uniforms = null; }
  80875. if (samplers === void 0) { samplers = null; }
  80876. this._updateParameters(onCompiled, onError);
  80877. };
  80878. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80879. // Generate sampling offsets and weights
  80880. var N = this._kernel;
  80881. var centerIndex = (N - 1) / 2;
  80882. // Generate Gaussian sampling weights over kernel
  80883. var offsets = [];
  80884. var weights = [];
  80885. var totalWeight = 0;
  80886. for (var i = 0; i < N; i++) {
  80887. var u = i / (N - 1);
  80888. var w = this._gaussianWeight(u * 2.0 - 1);
  80889. offsets[i] = (i - centerIndex);
  80890. weights[i] = w;
  80891. totalWeight += w;
  80892. }
  80893. // Normalize weights
  80894. for (var i = 0; i < weights.length; i++) {
  80895. weights[i] /= totalWeight;
  80896. }
  80897. // Optimize: combine samples to take advantage of hardware linear sampling
  80898. // Walk from left to center, combining pairs (symmetrically)
  80899. var linearSamplingWeights = [];
  80900. var linearSamplingOffsets = [];
  80901. var linearSamplingMap = [];
  80902. for (var i = 0; i <= centerIndex; i += 2) {
  80903. var j = Math.min(i + 1, Math.floor(centerIndex));
  80904. var singleCenterSample = i === j;
  80905. if (singleCenterSample) {
  80906. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80907. }
  80908. else {
  80909. var sharedCell = j === centerIndex;
  80910. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80911. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80912. if (offsetLinear === 0) {
  80913. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80914. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80915. }
  80916. else {
  80917. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80918. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80919. }
  80920. }
  80921. }
  80922. for (var i = 0; i < linearSamplingMap.length; i++) {
  80923. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80924. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80925. }
  80926. // Replace with optimized
  80927. offsets = linearSamplingOffsets;
  80928. weights = linearSamplingWeights;
  80929. // Generate shaders
  80930. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80931. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80932. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80933. var defines = "";
  80934. defines += this._staticDefines;
  80935. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80936. if (this._staticDefines.indexOf("DOF") != -1) {
  80937. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80938. varyingCount--;
  80939. }
  80940. for (var i = 0; i < varyingCount; i++) {
  80941. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80942. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80943. }
  80944. var depCount = 0;
  80945. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80946. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80947. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80948. depCount++;
  80949. }
  80950. if (this.packedFloat) {
  80951. defines += "#define PACKEDFLOAT 1";
  80952. }
  80953. this.blockCompilation = false;
  80954. _super.prototype.updateEffect.call(this, defines, null, null, {
  80955. varyingCount: varyingCount,
  80956. depCount: depCount
  80957. }, onCompiled, onError);
  80958. };
  80959. /**
  80960. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80961. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80962. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80963. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80964. * The gaps between physical kernels are compensated for in the weighting of the samples
  80965. * @param idealKernel Ideal blur kernel.
  80966. * @return Nearest best kernel.
  80967. */
  80968. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80969. var v = Math.round(idealKernel);
  80970. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80971. var k = _a[_i];
  80972. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80973. return Math.max(k, 3);
  80974. }
  80975. }
  80976. return Math.max(v, 3);
  80977. };
  80978. /**
  80979. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80980. * @param x The point on the Gaussian distribution to sample.
  80981. * @return the value of the Gaussian function at x.
  80982. */
  80983. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80984. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80985. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80986. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80987. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80988. // truncated at around 1.3% of peak strength.
  80989. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80990. var sigma = (1 / 3);
  80991. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80992. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80993. var weight = (1.0 / denominator) * Math.exp(exponent);
  80994. return weight;
  80995. };
  80996. /**
  80997. * Generates a string that can be used as a floating point number in GLSL.
  80998. * @param x Value to print.
  80999. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  81000. * @return GLSL float string.
  81001. */
  81002. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  81003. if (decimalFigures === void 0) { decimalFigures = 8; }
  81004. return x.toFixed(decimalFigures).replace(/0+$/, '');
  81005. };
  81006. return BlurPostProcess;
  81007. }(BABYLON.PostProcess));
  81008. BABYLON.BlurPostProcess = BlurPostProcess;
  81009. })(BABYLON || (BABYLON = {}));
  81010. //# sourceMappingURL=babylon.blurPostProcess.js.map
  81011. var BABYLON;
  81012. (function (BABYLON) {
  81013. /**
  81014. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  81015. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  81016. * based on samples that have a large difference in distance than the center pixel.
  81017. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  81018. */
  81019. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  81020. __extends(DepthOfFieldBlurPostProcess, _super);
  81021. /**
  81022. * Creates a new instance CircleOfConfusionPostProcess
  81023. * @param name The name of the effect.
  81024. * @param scene The scene the effect belongs to.
  81025. * @param direction The direction the blur should be applied.
  81026. * @param kernel The size of the kernel used to blur.
  81027. * @param options The required width/height ratio to downsize to before computing the render pass.
  81028. * @param camera The camera to apply the render pass to.
  81029. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  81030. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  81031. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81032. * @param engine The engine which the post process will be applied. (default: current engine)
  81033. * @param reusable If the post process can be reused on the same frame. (default: false)
  81034. * @param textureType Type of textures used when performing the post process. (default: 0)
  81035. * @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)
  81036. */
  81037. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  81038. if (imageToBlur === void 0) { imageToBlur = null; }
  81039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81040. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81041. if (blockCompilation === void 0) { blockCompilation = false; }
  81042. 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;
  81043. _this.direction = direction;
  81044. _this.onApplyObservable.add(function (effect) {
  81045. if (imageToBlur != null) {
  81046. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  81047. }
  81048. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  81049. if (scene.activeCamera) {
  81050. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81051. }
  81052. });
  81053. return _this;
  81054. }
  81055. return DepthOfFieldBlurPostProcess;
  81056. }(BABYLON.BlurPostProcess));
  81057. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  81058. })(BABYLON || (BABYLON = {}));
  81059. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  81060. var BABYLON;
  81061. (function (BABYLON) {
  81062. /**
  81063. * Options to be set when merging outputs from the default pipeline.
  81064. */
  81065. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  81066. function DepthOfFieldMergePostProcessOptions() {
  81067. }
  81068. return DepthOfFieldMergePostProcessOptions;
  81069. }());
  81070. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  81071. /**
  81072. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81073. */
  81074. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  81075. __extends(DepthOfFieldMergePostProcess, _super);
  81076. /**
  81077. * Creates a new instance of DepthOfFieldMergePostProcess
  81078. * @param name The name of the effect.
  81079. * @param originalFromInput Post process which's input will be used for the merge.
  81080. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  81081. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  81082. * @param options The required width/height ratio to downsize to before computing the render pass.
  81083. * @param camera The camera to apply the render pass to.
  81084. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81085. * @param engine The engine which the post process will be applied. (default: current engine)
  81086. * @param reusable If the post process can be reused on the same frame. (default: false)
  81087. * @param textureType Type of textures used when performing the post process. (default: 0)
  81088. * @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)
  81089. */
  81090. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81092. if (blockCompilation === void 0) { blockCompilation = false; }
  81093. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81094. _this.blurSteps = blurSteps;
  81095. _this.onApplyObservable.add(function (effect) {
  81096. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81097. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  81098. blurSteps.forEach(function (step, index) {
  81099. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  81100. });
  81101. });
  81102. if (!blockCompilation) {
  81103. _this.updateEffect();
  81104. }
  81105. return _this;
  81106. }
  81107. /**
  81108. * Updates the effect with the current post process compile time values and recompiles the shader.
  81109. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  81110. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  81111. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  81112. * @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
  81113. * @param onCompiled Called when the shader has been compiled.
  81114. * @param onError Called if there is an error when compiling a shader.
  81115. */
  81116. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  81117. if (defines === void 0) { defines = null; }
  81118. if (uniforms === void 0) { uniforms = null; }
  81119. if (samplers === void 0) { samplers = null; }
  81120. if (!defines) {
  81121. defines = "";
  81122. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  81123. }
  81124. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  81125. };
  81126. return DepthOfFieldMergePostProcess;
  81127. }(BABYLON.PostProcess));
  81128. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  81129. })(BABYLON || (BABYLON = {}));
  81130. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  81131. var BABYLON;
  81132. (function (BABYLON) {
  81133. /**
  81134. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  81135. */
  81136. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  81137. __extends(CircleOfConfusionPostProcess, _super);
  81138. /**
  81139. * Creates a new instance CircleOfConfusionPostProcess
  81140. * @param name The name of the effect.
  81141. * @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.
  81142. * @param options The required width/height ratio to downsize to before computing the render pass.
  81143. * @param camera The camera to apply the render pass to.
  81144. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81145. * @param engine The engine which the post process will be applied. (default: current engine)
  81146. * @param reusable If the post process can be reused on the same frame. (default: false)
  81147. * @param textureType Type of textures used when performing the post process. (default: 0)
  81148. * @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)
  81149. */
  81150. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81151. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81152. if (blockCompilation === void 0) { blockCompilation = false; }
  81153. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81154. /**
  81155. * 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.
  81156. */
  81157. _this.lensSize = 50;
  81158. /**
  81159. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81160. */
  81161. _this.fStop = 1.4;
  81162. /**
  81163. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81164. */
  81165. _this.focusDistance = 2000;
  81166. /**
  81167. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  81168. */
  81169. _this.focalLength = 50;
  81170. _this._depthTexture = null;
  81171. _this._depthTexture = depthTexture;
  81172. _this.onApplyObservable.add(function (effect) {
  81173. if (!_this._depthTexture) {
  81174. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  81175. return;
  81176. }
  81177. effect.setTexture("depthSampler", _this._depthTexture);
  81178. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  81179. var aperture = _this.lensSize / _this.fStop;
  81180. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  81181. effect.setFloat('focusDistance', _this.focusDistance);
  81182. effect.setFloat('cocPrecalculation', cocPrecalculation);
  81183. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  81184. });
  81185. return _this;
  81186. }
  81187. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  81188. /**
  81189. * 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.
  81190. */
  81191. set: function (value) {
  81192. this._depthTexture = value;
  81193. },
  81194. enumerable: true,
  81195. configurable: true
  81196. });
  81197. return CircleOfConfusionPostProcess;
  81198. }(BABYLON.PostProcess));
  81199. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  81200. })(BABYLON || (BABYLON = {}));
  81201. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  81202. var BABYLON;
  81203. (function (BABYLON) {
  81204. /**
  81205. * Specifies the level of max blur that should be applied when using the depth of field effect
  81206. */
  81207. var DepthOfFieldEffectBlurLevel;
  81208. (function (DepthOfFieldEffectBlurLevel) {
  81209. /**
  81210. * Subtle blur
  81211. */
  81212. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  81213. /**
  81214. * Medium blur
  81215. */
  81216. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  81217. /**
  81218. * Large blur
  81219. */
  81220. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  81221. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  81222. ;
  81223. /**
  81224. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  81225. */
  81226. var DepthOfFieldEffect = /** @class */ (function (_super) {
  81227. __extends(DepthOfFieldEffect, _super);
  81228. /**
  81229. * Creates a new instance DepthOfFieldEffect
  81230. * @param scene The scene the effect belongs to.
  81231. * @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.
  81232. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81233. * @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)
  81234. */
  81235. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  81236. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  81237. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81238. if (blockCompilation === void 0) { blockCompilation = false; }
  81239. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  81240. return _this._effects;
  81241. }, true) || this;
  81242. /**
  81243. * @hidden Internal post processes in depth of field effect
  81244. */
  81245. _this._effects = [];
  81246. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  81247. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81248. // 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)
  81249. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  81250. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  81251. _this._depthOfFieldBlurY = [];
  81252. _this._depthOfFieldBlurX = [];
  81253. var blurCount = 1;
  81254. var kernelSize = 15;
  81255. switch (blurLevel) {
  81256. case DepthOfFieldEffectBlurLevel.High: {
  81257. blurCount = 3;
  81258. kernelSize = 51;
  81259. break;
  81260. }
  81261. case DepthOfFieldEffectBlurLevel.Medium: {
  81262. blurCount = 2;
  81263. kernelSize = 31;
  81264. break;
  81265. }
  81266. default: {
  81267. kernelSize = 15;
  81268. blurCount = 1;
  81269. break;
  81270. }
  81271. }
  81272. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  81273. var ratio = 1.0;
  81274. for (var i = 0; i < blurCount; i++) {
  81275. 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);
  81276. blurY.autoClear = false;
  81277. ratio = 0.75 / Math.pow(2, i);
  81278. 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);
  81279. blurX.autoClear = false;
  81280. _this._depthOfFieldBlurY.push(blurY);
  81281. _this._depthOfFieldBlurX.push(blurX);
  81282. }
  81283. // Set all post processes on the effect.
  81284. _this._effects = [_this._circleOfConfusion];
  81285. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  81286. _this._effects.push(_this._depthOfFieldBlurY[i]);
  81287. _this._effects.push(_this._depthOfFieldBlurX[i]);
  81288. }
  81289. // Merge blurred images with original image based on circleOfConfusion
  81290. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81291. _this._dofMerge.autoClear = false;
  81292. _this._effects.push(_this._dofMerge);
  81293. return _this;
  81294. }
  81295. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  81296. get: function () {
  81297. return this._circleOfConfusion.focalLength;
  81298. },
  81299. /**
  81300. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  81301. */
  81302. set: function (value) {
  81303. this._circleOfConfusion.focalLength = value;
  81304. },
  81305. enumerable: true,
  81306. configurable: true
  81307. });
  81308. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  81309. get: function () {
  81310. return this._circleOfConfusion.fStop;
  81311. },
  81312. /**
  81313. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81314. */
  81315. set: function (value) {
  81316. this._circleOfConfusion.fStop = value;
  81317. },
  81318. enumerable: true,
  81319. configurable: true
  81320. });
  81321. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  81322. get: function () {
  81323. return this._circleOfConfusion.focusDistance;
  81324. },
  81325. /**
  81326. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81327. */
  81328. set: function (value) {
  81329. this._circleOfConfusion.focusDistance = value;
  81330. },
  81331. enumerable: true,
  81332. configurable: true
  81333. });
  81334. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  81335. get: function () {
  81336. return this._circleOfConfusion.lensSize;
  81337. },
  81338. /**
  81339. * 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.
  81340. */
  81341. set: function (value) {
  81342. this._circleOfConfusion.lensSize = value;
  81343. },
  81344. enumerable: true,
  81345. configurable: true
  81346. });
  81347. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  81348. /**
  81349. * 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.
  81350. */
  81351. set: function (value) {
  81352. this._circleOfConfusion.depthTexture = value;
  81353. },
  81354. enumerable: true,
  81355. configurable: true
  81356. });
  81357. /**
  81358. * Disposes each of the internal effects for a given camera.
  81359. * @param camera The camera to dispose the effect on.
  81360. */
  81361. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  81362. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81363. this._effects[effectIndex].dispose(camera);
  81364. }
  81365. };
  81366. /**
  81367. * @hidden Internal
  81368. */
  81369. DepthOfFieldEffect.prototype._updateEffects = function () {
  81370. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81371. this._effects[effectIndex].updateEffect();
  81372. }
  81373. };
  81374. /**
  81375. * Internal
  81376. * @returns if all the contained post processes are ready.
  81377. * @hidden
  81378. */
  81379. DepthOfFieldEffect.prototype._isReady = function () {
  81380. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81381. if (!this._effects[effectIndex].isReady()) {
  81382. return false;
  81383. }
  81384. }
  81385. return true;
  81386. };
  81387. return DepthOfFieldEffect;
  81388. }(BABYLON.PostProcessRenderEffect));
  81389. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  81390. })(BABYLON || (BABYLON = {}));
  81391. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  81392. var BABYLON;
  81393. (function (BABYLON) {
  81394. /**
  81395. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81396. */
  81397. var BloomMergePostProcess = /** @class */ (function (_super) {
  81398. __extends(BloomMergePostProcess, _super);
  81399. /**
  81400. * Creates a new instance of @see BloomMergePostProcess
  81401. * @param name The name of the effect.
  81402. * @param originalFromInput Post process which's input will be used for the merge.
  81403. * @param blurred Blurred highlights post process which's output will be used.
  81404. * @param weight Weight of the bloom to be added to the original input.
  81405. * @param options The required width/height ratio to downsize to before computing the render pass.
  81406. * @param camera The camera to apply the render pass to.
  81407. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81408. * @param engine The engine which the post process will be applied. (default: current engine)
  81409. * @param reusable If the post process can be reused on the same frame. (default: false)
  81410. * @param textureType Type of textures used when performing the post process. (default: 0)
  81411. * @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)
  81412. */
  81413. function BloomMergePostProcess(name, originalFromInput, blurred,
  81414. /** Weight of the bloom to be added to the original input. */
  81415. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81417. if (blockCompilation === void 0) { blockCompilation = false; }
  81418. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81419. _this.weight = weight;
  81420. _this.onApplyObservable.add(function (effect) {
  81421. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81422. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  81423. effect.setFloat("bloomWeight", _this.weight);
  81424. });
  81425. if (!blockCompilation) {
  81426. _this.updateEffect();
  81427. }
  81428. return _this;
  81429. }
  81430. return BloomMergePostProcess;
  81431. }(BABYLON.PostProcess));
  81432. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  81433. })(BABYLON || (BABYLON = {}));
  81434. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  81435. var BABYLON;
  81436. (function (BABYLON) {
  81437. /**
  81438. * 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.
  81439. */
  81440. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  81441. __extends(ExtractHighlightsPostProcess, _super);
  81442. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81443. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81444. if (blockCompilation === void 0) { blockCompilation = false; }
  81445. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81446. /**
  81447. * The luminance threshold, pixels below this value will be set to black.
  81448. */
  81449. _this.threshold = 0.9;
  81450. /** @hidden */
  81451. _this._exposure = 1;
  81452. /**
  81453. * Post process which has the input texture to be used when performing highlight extraction
  81454. * @hidden
  81455. */
  81456. _this._inputPostProcess = null;
  81457. _this.onApplyObservable.add(function (effect) {
  81458. if (_this._inputPostProcess) {
  81459. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  81460. }
  81461. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  81462. effect.setFloat('exposure', _this._exposure);
  81463. });
  81464. return _this;
  81465. }
  81466. return ExtractHighlightsPostProcess;
  81467. }(BABYLON.PostProcess));
  81468. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  81469. })(BABYLON || (BABYLON = {}));
  81470. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  81471. var BABYLON;
  81472. (function (BABYLON) {
  81473. /**
  81474. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  81475. */
  81476. var BloomEffect = /** @class */ (function (_super) {
  81477. __extends(BloomEffect, _super);
  81478. /**
  81479. * Creates a new instance of @see BloomEffect
  81480. * @param scene The scene the effect belongs to.
  81481. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  81482. * @param bloomKernel The size of the kernel to be used when applying the blur.
  81483. * @param bloomWeight The the strength of bloom.
  81484. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81485. * @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)
  81486. */
  81487. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  81488. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81489. if (blockCompilation === void 0) { blockCompilation = false; }
  81490. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  81491. return _this._effects;
  81492. }, true) || this;
  81493. _this.bloomScale = bloomScale;
  81494. /**
  81495. * @hidden Internal
  81496. */
  81497. _this._effects = [];
  81498. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81499. _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);
  81500. _this._blurX.alwaysForcePOT = true;
  81501. _this._blurX.autoClear = false;
  81502. _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);
  81503. _this._blurY.alwaysForcePOT = true;
  81504. _this._blurY.autoClear = false;
  81505. _this.kernel = bloomKernel;
  81506. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  81507. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81508. _this._merge.autoClear = false;
  81509. _this._effects.push(_this._merge);
  81510. return _this;
  81511. }
  81512. Object.defineProperty(BloomEffect.prototype, "threshold", {
  81513. /**
  81514. * The luminance threshold to find bright areas of the image to bloom.
  81515. */
  81516. get: function () {
  81517. return this._downscale.threshold;
  81518. },
  81519. set: function (value) {
  81520. this._downscale.threshold = value;
  81521. },
  81522. enumerable: true,
  81523. configurable: true
  81524. });
  81525. Object.defineProperty(BloomEffect.prototype, "weight", {
  81526. /**
  81527. * The strength of the bloom.
  81528. */
  81529. get: function () {
  81530. return this._merge.weight;
  81531. },
  81532. set: function (value) {
  81533. this._merge.weight = value;
  81534. },
  81535. enumerable: true,
  81536. configurable: true
  81537. });
  81538. Object.defineProperty(BloomEffect.prototype, "kernel", {
  81539. /**
  81540. * Specifies the size of the bloom blur kernel, relative to the final output size
  81541. */
  81542. get: function () {
  81543. return this._blurX.kernel / this.bloomScale;
  81544. },
  81545. set: function (value) {
  81546. this._blurX.kernel = value * this.bloomScale;
  81547. this._blurY.kernel = value * this.bloomScale;
  81548. },
  81549. enumerable: true,
  81550. configurable: true
  81551. });
  81552. /**
  81553. * Disposes each of the internal effects for a given camera.
  81554. * @param camera The camera to dispose the effect on.
  81555. */
  81556. BloomEffect.prototype.disposeEffects = function (camera) {
  81557. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81558. this._effects[effectIndex].dispose(camera);
  81559. }
  81560. };
  81561. /**
  81562. * @hidden Internal
  81563. */
  81564. BloomEffect.prototype._updateEffects = function () {
  81565. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81566. this._effects[effectIndex].updateEffect();
  81567. }
  81568. };
  81569. /**
  81570. * Internal
  81571. * @returns if all the contained post processes are ready.
  81572. * @hidden
  81573. */
  81574. BloomEffect.prototype._isReady = function () {
  81575. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81576. if (!this._effects[effectIndex].isReady()) {
  81577. return false;
  81578. }
  81579. }
  81580. return true;
  81581. };
  81582. return BloomEffect;
  81583. }(BABYLON.PostProcessRenderEffect));
  81584. BABYLON.BloomEffect = BloomEffect;
  81585. })(BABYLON || (BABYLON = {}));
  81586. //# sourceMappingURL=babylon.bloomEffect.js.map
  81587. var BABYLON;
  81588. (function (BABYLON) {
  81589. /**
  81590. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81591. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81592. */
  81593. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81594. __extends(DefaultRenderingPipeline, _super);
  81595. /**
  81596. * @constructor
  81597. * @param {string} name - The rendering pipeline name (default: "")
  81598. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81599. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81600. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81601. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81602. */
  81603. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81604. if (name === void 0) { name = ""; }
  81605. if (hdr === void 0) { hdr = true; }
  81606. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81607. if (automaticBuild === void 0) { automaticBuild = true; }
  81608. var _this = _super.call(this, scene.getEngine(), name) || this;
  81609. _this._camerasToBeAttached = [];
  81610. /**
  81611. * ID of the sharpen post process,
  81612. */
  81613. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81614. /**
  81615. * ID of the image processing post process;
  81616. */
  81617. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81618. /**
  81619. * ID of the Fast Approximate Anti-Aliasing post process;
  81620. */
  81621. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81622. /**
  81623. * ID of the chromatic aberration post process,
  81624. */
  81625. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81626. /**
  81627. * ID of the grain post process
  81628. */
  81629. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81630. /**
  81631. * Glow post process which adds a glow to emmisive areas of the image
  81632. */
  81633. _this._glowLayer = null;
  81634. /**
  81635. * Animations which can be used to tweak settings over a period of time
  81636. */
  81637. _this.animations = [];
  81638. _this._imageProcessingConfigurationObserver = null;
  81639. // Values
  81640. _this._sharpenEnabled = false;
  81641. _this._bloomEnabled = false;
  81642. _this._depthOfFieldEnabled = false;
  81643. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81644. _this._fxaaEnabled = false;
  81645. _this._imageProcessingEnabled = true;
  81646. _this._bloomScale = 0.5;
  81647. _this._chromaticAberrationEnabled = false;
  81648. _this._grainEnabled = false;
  81649. _this._buildAllowed = true;
  81650. _this._resizeObserver = null;
  81651. _this._hardwareScaleLevel = 1.0;
  81652. _this._bloomKernel = 64;
  81653. /**
  81654. * Specifies the weight of the bloom in the final rendering
  81655. */
  81656. _this._bloomWeight = 0.15;
  81657. /**
  81658. * Specifies the luma threshold for the area that will be blurred by the bloom
  81659. */
  81660. _this._bloomThreshold = 0.9;
  81661. _this._samples = 1;
  81662. _this._hasCleared = false;
  81663. _this._prevPostProcess = null;
  81664. _this._prevPrevPostProcess = null;
  81665. _this._depthOfFieldSceneObserver = null;
  81666. _this._cameras = cameras || scene.cameras;
  81667. _this._cameras = _this._cameras.slice();
  81668. _this._camerasToBeAttached = _this._cameras.slice();
  81669. _this._buildAllowed = automaticBuild;
  81670. // Initialize
  81671. _this._scene = scene;
  81672. var caps = _this._scene.getEngine().getCaps();
  81673. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81674. // Misc
  81675. if (_this._hdr) {
  81676. if (caps.textureHalfFloatRender) {
  81677. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81678. }
  81679. else if (caps.textureFloatRender) {
  81680. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81681. }
  81682. }
  81683. else {
  81684. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81685. }
  81686. // Attach
  81687. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81688. var engine = _this._scene.getEngine();
  81689. // Create post processes before hand so they can be modified before enabled.
  81690. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81691. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81692. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81693. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81694. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81695. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81696. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81697. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81698. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81699. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81700. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81701. _this.bloomKernel = _this.bloomKernel;
  81702. });
  81703. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81704. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81705. });
  81706. _this._buildPipeline();
  81707. return _this;
  81708. }
  81709. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81710. get: function () {
  81711. return this._sharpenEnabled;
  81712. },
  81713. /**
  81714. * Enable or disable the sharpen process from the pipeline
  81715. */
  81716. set: function (enabled) {
  81717. if (this._sharpenEnabled === enabled) {
  81718. return;
  81719. }
  81720. this._sharpenEnabled = enabled;
  81721. this._buildPipeline();
  81722. },
  81723. enumerable: true,
  81724. configurable: true
  81725. });
  81726. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81727. /**
  81728. * Specifies the size of the bloom blur kernel, relative to the final output size
  81729. */
  81730. get: function () {
  81731. return this._bloomKernel;
  81732. },
  81733. set: function (value) {
  81734. this._bloomKernel = value;
  81735. this.bloom.kernel = value / this._hardwareScaleLevel;
  81736. },
  81737. enumerable: true,
  81738. configurable: true
  81739. });
  81740. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81741. get: function () {
  81742. return this._bloomWeight;
  81743. },
  81744. /**
  81745. * The strength of the bloom.
  81746. */
  81747. set: function (value) {
  81748. if (this._bloomWeight === value) {
  81749. return;
  81750. }
  81751. this.bloom.weight = value;
  81752. this._bloomWeight = value;
  81753. },
  81754. enumerable: true,
  81755. configurable: true
  81756. });
  81757. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81758. get: function () {
  81759. return this._bloomThreshold;
  81760. },
  81761. /**
  81762. * The strength of the bloom.
  81763. */
  81764. set: function (value) {
  81765. if (this._bloomThreshold === value) {
  81766. return;
  81767. }
  81768. this.bloom.threshold = value;
  81769. this._bloomThreshold = value;
  81770. },
  81771. enumerable: true,
  81772. configurable: true
  81773. });
  81774. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81775. get: function () {
  81776. return this._bloomScale;
  81777. },
  81778. /**
  81779. * The scale of the bloom, lower value will provide better performance.
  81780. */
  81781. set: function (value) {
  81782. if (this._bloomScale === value) {
  81783. return;
  81784. }
  81785. this._bloomScale = value;
  81786. // recreate bloom and dispose old as this setting is not dynamic
  81787. this._rebuildBloom();
  81788. this._buildPipeline();
  81789. },
  81790. enumerable: true,
  81791. configurable: true
  81792. });
  81793. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81794. get: function () {
  81795. return this._bloomEnabled;
  81796. },
  81797. /**
  81798. * Enable or disable the bloom from the pipeline
  81799. */
  81800. set: function (enabled) {
  81801. if (this._bloomEnabled === enabled) {
  81802. return;
  81803. }
  81804. this._bloomEnabled = enabled;
  81805. this._buildPipeline();
  81806. },
  81807. enumerable: true,
  81808. configurable: true
  81809. });
  81810. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81811. // recreate bloom and dispose old as this setting is not dynamic
  81812. var oldBloom = this.bloom;
  81813. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81814. this.bloom.threshold = oldBloom.threshold;
  81815. for (var i = 0; i < this._cameras.length; i++) {
  81816. oldBloom.disposeEffects(this._cameras[i]);
  81817. }
  81818. };
  81819. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81820. /**
  81821. * If the depth of field is enabled.
  81822. */
  81823. get: function () {
  81824. return this._depthOfFieldEnabled;
  81825. },
  81826. set: function (enabled) {
  81827. if (this._depthOfFieldEnabled === enabled) {
  81828. return;
  81829. }
  81830. this._depthOfFieldEnabled = enabled;
  81831. this._buildPipeline();
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81837. /**
  81838. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81839. */
  81840. get: function () {
  81841. return this._depthOfFieldBlurLevel;
  81842. },
  81843. set: function (value) {
  81844. if (this._depthOfFieldBlurLevel === value) {
  81845. return;
  81846. }
  81847. this._depthOfFieldBlurLevel = value;
  81848. // recreate dof and dispose old as this setting is not dynamic
  81849. var oldDof = this.depthOfField;
  81850. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81851. this.depthOfField.focalLength = oldDof.focalLength;
  81852. this.depthOfField.focusDistance = oldDof.focusDistance;
  81853. this.depthOfField.fStop = oldDof.fStop;
  81854. this.depthOfField.lensSize = oldDof.lensSize;
  81855. for (var i = 0; i < this._cameras.length; i++) {
  81856. oldDof.disposeEffects(this._cameras[i]);
  81857. }
  81858. this._buildPipeline();
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81864. get: function () {
  81865. return this._fxaaEnabled;
  81866. },
  81867. /**
  81868. * If the anti aliasing is enabled.
  81869. */
  81870. set: function (enabled) {
  81871. if (this._fxaaEnabled === enabled) {
  81872. return;
  81873. }
  81874. this._fxaaEnabled = enabled;
  81875. this._buildPipeline();
  81876. },
  81877. enumerable: true,
  81878. configurable: true
  81879. });
  81880. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81881. get: function () {
  81882. return this._samples;
  81883. },
  81884. /**
  81885. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81886. */
  81887. set: function (sampleCount) {
  81888. if (this._samples === sampleCount) {
  81889. return;
  81890. }
  81891. this._samples = sampleCount;
  81892. this._buildPipeline();
  81893. },
  81894. enumerable: true,
  81895. configurable: true
  81896. });
  81897. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81898. get: function () {
  81899. return this._imageProcessingEnabled;
  81900. },
  81901. /**
  81902. * If image processing is enabled.
  81903. */
  81904. set: function (enabled) {
  81905. if (this._imageProcessingEnabled === enabled) {
  81906. return;
  81907. }
  81908. this._imageProcessingEnabled = enabled;
  81909. this._buildPipeline();
  81910. },
  81911. enumerable: true,
  81912. configurable: true
  81913. });
  81914. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81915. get: function () {
  81916. return this._glowLayer == null;
  81917. },
  81918. /**
  81919. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81920. */
  81921. set: function (enabled) {
  81922. if (enabled && !this._glowLayer) {
  81923. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81924. }
  81925. else if (!enabled && this._glowLayer) {
  81926. this._glowLayer.dispose();
  81927. this._glowLayer = null;
  81928. }
  81929. },
  81930. enumerable: true,
  81931. configurable: true
  81932. });
  81933. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81934. get: function () {
  81935. return this._chromaticAberrationEnabled;
  81936. },
  81937. /**
  81938. * Enable or disable the chromaticAberration process from the pipeline
  81939. */
  81940. set: function (enabled) {
  81941. if (this._chromaticAberrationEnabled === enabled) {
  81942. return;
  81943. }
  81944. this._chromaticAberrationEnabled = enabled;
  81945. this._buildPipeline();
  81946. },
  81947. enumerable: true,
  81948. configurable: true
  81949. });
  81950. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81951. get: function () {
  81952. return this._grainEnabled;
  81953. },
  81954. /**
  81955. * Enable or disable the grain process from the pipeline
  81956. */
  81957. set: function (enabled) {
  81958. if (this._grainEnabled === enabled) {
  81959. return;
  81960. }
  81961. this._grainEnabled = enabled;
  81962. this._buildPipeline();
  81963. },
  81964. enumerable: true,
  81965. configurable: true
  81966. });
  81967. /**
  81968. * Force the compilation of the entire pipeline.
  81969. */
  81970. DefaultRenderingPipeline.prototype.prepare = function () {
  81971. var previousState = this._buildAllowed;
  81972. this._buildAllowed = true;
  81973. this._buildPipeline();
  81974. this._buildAllowed = previousState;
  81975. };
  81976. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81977. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81978. if (this._hasCleared) {
  81979. postProcess.autoClear = false;
  81980. }
  81981. else {
  81982. postProcess.autoClear = true;
  81983. this._scene.autoClear = false;
  81984. this._hasCleared = true;
  81985. }
  81986. if (!skipTextureSharing) {
  81987. if (this._prevPrevPostProcess) {
  81988. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81989. }
  81990. else {
  81991. postProcess.useOwnOutput();
  81992. }
  81993. if (this._prevPostProcess) {
  81994. this._prevPrevPostProcess = this._prevPostProcess;
  81995. }
  81996. this._prevPostProcess = postProcess;
  81997. }
  81998. };
  81999. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  82000. var _this = this;
  82001. if (!this._buildAllowed) {
  82002. return;
  82003. }
  82004. this._scene.autoClear = true;
  82005. var engine = this._scene.getEngine();
  82006. this._disposePostProcesses();
  82007. if (this._cameras !== null) {
  82008. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82009. // get back cameras to be used to reattach pipeline
  82010. this._cameras = this._camerasToBeAttached.slice();
  82011. }
  82012. this._reset();
  82013. this._prevPostProcess = null;
  82014. this._prevPrevPostProcess = null;
  82015. this._hasCleared = false;
  82016. if (this.depthOfFieldEnabled) {
  82017. // Multi camera suport
  82018. if (this._cameras.length > 1) {
  82019. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  82020. var camera = _a[_i];
  82021. var depthRenderer = this._scene.enableDepthRenderer(camera);
  82022. depthRenderer.useOnlyInActiveCamera = true;
  82023. }
  82024. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  82025. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  82026. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  82027. }
  82028. });
  82029. }
  82030. else {
  82031. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82032. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  82033. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  82034. }
  82035. if (!this.depthOfField._isReady()) {
  82036. this.depthOfField._updateEffects();
  82037. }
  82038. this.addEffect(this.depthOfField);
  82039. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  82040. }
  82041. else {
  82042. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82043. }
  82044. if (this.bloomEnabled) {
  82045. if (!this.bloom._isReady()) {
  82046. this.bloom._updateEffects();
  82047. }
  82048. this.addEffect(this.bloom);
  82049. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  82050. }
  82051. if (this._imageProcessingEnabled) {
  82052. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  82053. if (this._hdr) {
  82054. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  82055. this._setAutoClearAndTextureSharing(this.imageProcessing);
  82056. }
  82057. else {
  82058. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  82059. }
  82060. }
  82061. if (this.sharpenEnabled) {
  82062. if (!this.sharpen.isReady()) {
  82063. this.sharpen.updateEffect();
  82064. }
  82065. this.addEffect(this._sharpenEffect);
  82066. this._setAutoClearAndTextureSharing(this.sharpen);
  82067. }
  82068. if (this.grainEnabled) {
  82069. if (!this.grain.isReady()) {
  82070. this.grain.updateEffect();
  82071. }
  82072. this.addEffect(this._grainEffect);
  82073. this._setAutoClearAndTextureSharing(this.grain);
  82074. }
  82075. if (this.chromaticAberrationEnabled) {
  82076. if (!this.chromaticAberration.isReady()) {
  82077. this.chromaticAberration.updateEffect();
  82078. }
  82079. this.addEffect(this._chromaticAberrationEffect);
  82080. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  82081. }
  82082. if (this.fxaaEnabled) {
  82083. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  82084. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  82085. this._setAutoClearAndTextureSharing(this.fxaa, true);
  82086. }
  82087. if (this._cameras !== null) {
  82088. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82089. }
  82090. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  82091. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82092. }
  82093. };
  82094. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  82095. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  82096. for (var i = 0; i < this._cameras.length; i++) {
  82097. var camera = this._cameras[i];
  82098. if (this.imageProcessing) {
  82099. this.imageProcessing.dispose(camera);
  82100. }
  82101. if (this.fxaa) {
  82102. this.fxaa.dispose(camera);
  82103. }
  82104. // These are created in the constructor and should not be disposed on every pipeline change
  82105. if (disposeNonRecreated) {
  82106. if (this.sharpen) {
  82107. this.sharpen.dispose(camera);
  82108. }
  82109. if (this.depthOfField) {
  82110. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  82111. this.depthOfField.disposeEffects(camera);
  82112. }
  82113. if (this.bloom) {
  82114. this.bloom.disposeEffects(camera);
  82115. }
  82116. if (this.chromaticAberration) {
  82117. this.chromaticAberration.dispose(camera);
  82118. }
  82119. if (this.grain) {
  82120. this.grain.dispose(camera);
  82121. }
  82122. if (this._glowLayer) {
  82123. this._glowLayer.dispose();
  82124. }
  82125. }
  82126. }
  82127. this.imageProcessing = null;
  82128. this.fxaa = null;
  82129. if (disposeNonRecreated) {
  82130. this.sharpen = null;
  82131. this._sharpenEffect = null;
  82132. this.depthOfField = null;
  82133. this.bloom = null;
  82134. this.chromaticAberration = null;
  82135. this._chromaticAberrationEffect = null;
  82136. this.grain = null;
  82137. this._grainEffect = null;
  82138. this._glowLayer = null;
  82139. }
  82140. };
  82141. /**
  82142. * Adds a camera to the pipeline
  82143. * @param camera the camera to be added
  82144. */
  82145. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  82146. this._camerasToBeAttached.push(camera);
  82147. this._buildPipeline();
  82148. };
  82149. /**
  82150. * Removes a camera from the pipeline
  82151. * @param camera the camera to remove
  82152. */
  82153. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  82154. var index = this._camerasToBeAttached.indexOf(camera);
  82155. this._camerasToBeAttached.splice(index, 1);
  82156. this._buildPipeline();
  82157. };
  82158. /**
  82159. * Dispose of the pipeline and stop all post processes
  82160. */
  82161. DefaultRenderingPipeline.prototype.dispose = function () {
  82162. this._disposePostProcesses(true);
  82163. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82164. this._scene.autoClear = true;
  82165. if (this._resizeObserver) {
  82166. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  82167. this._resizeObserver = null;
  82168. }
  82169. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  82170. _super.prototype.dispose.call(this);
  82171. };
  82172. /**
  82173. * Serialize the rendering pipeline (Used when exporting)
  82174. * @returns the serialized object
  82175. */
  82176. DefaultRenderingPipeline.prototype.serialize = function () {
  82177. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82178. serializationObject.customType = "DefaultRenderingPipeline";
  82179. return serializationObject;
  82180. };
  82181. /**
  82182. * Parse the serialized pipeline
  82183. * @param source Source pipeline.
  82184. * @param scene The scene to load the pipeline to.
  82185. * @param rootUrl The URL of the serialized pipeline.
  82186. * @returns An instantiated pipeline from the serialized object.
  82187. */
  82188. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82189. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  82190. };
  82191. __decorate([
  82192. BABYLON.serialize()
  82193. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  82194. __decorate([
  82195. BABYLON.serialize()
  82196. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  82197. __decorate([
  82198. BABYLON.serialize()
  82199. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  82200. __decorate([
  82201. BABYLON.serialize()
  82202. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  82203. __decorate([
  82204. BABYLON.serialize()
  82205. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  82206. __decorate([
  82207. BABYLON.serialize()
  82208. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  82209. __decorate([
  82210. BABYLON.serialize()
  82211. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  82212. __decorate([
  82213. BABYLON.serialize()
  82214. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  82215. __decorate([
  82216. BABYLON.serialize()
  82217. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  82218. __decorate([
  82219. BABYLON.serialize()
  82220. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  82221. __decorate([
  82222. BABYLON.serialize()
  82223. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  82224. __decorate([
  82225. BABYLON.serialize()
  82226. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  82227. __decorate([
  82228. BABYLON.serialize()
  82229. ], DefaultRenderingPipeline.prototype, "samples", null);
  82230. __decorate([
  82231. BABYLON.serialize()
  82232. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  82233. __decorate([
  82234. BABYLON.serialize()
  82235. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  82236. __decorate([
  82237. BABYLON.serialize()
  82238. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  82239. __decorate([
  82240. BABYLON.serialize()
  82241. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  82242. return DefaultRenderingPipeline;
  82243. }(BABYLON.PostProcessRenderPipeline));
  82244. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  82245. })(BABYLON || (BABYLON = {}));
  82246. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  82247. var BABYLON;
  82248. (function (BABYLON) {
  82249. /**
  82250. * @hidden
  82251. */
  82252. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  82253. __extends(ImageProcessingConfigurationDefines, _super);
  82254. function ImageProcessingConfigurationDefines() {
  82255. var _this = _super.call(this) || this;
  82256. _this.IMAGEPROCESSING = false;
  82257. _this.VIGNETTE = false;
  82258. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82259. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82260. _this.TONEMAPPING = false;
  82261. _this.TONEMAPPING_ACES = false;
  82262. _this.CONTRAST = false;
  82263. _this.COLORCURVES = false;
  82264. _this.COLORGRADING = false;
  82265. _this.COLORGRADING3D = false;
  82266. _this.SAMPLER3DGREENDEPTH = false;
  82267. _this.SAMPLER3DBGRMAP = false;
  82268. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82269. _this.EXPOSURE = false;
  82270. _this.rebuild();
  82271. return _this;
  82272. }
  82273. return ImageProcessingConfigurationDefines;
  82274. }(BABYLON.MaterialDefines));
  82275. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  82276. /**
  82277. * This groups together the common properties used for image processing either in direct forward pass
  82278. * or through post processing effect depending on the use of the image processing pipeline in your scene
  82279. * or not.
  82280. */
  82281. var ImageProcessingConfiguration = /** @class */ (function () {
  82282. function ImageProcessingConfiguration() {
  82283. /**
  82284. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  82285. */
  82286. this.colorCurves = new BABYLON.ColorCurves();
  82287. this._colorCurvesEnabled = false;
  82288. this._colorGradingEnabled = false;
  82289. this._colorGradingWithGreenDepth = true;
  82290. this._colorGradingBGR = true;
  82291. /** @hidden */
  82292. this._exposure = 1.0;
  82293. this._toneMappingEnabled = false;
  82294. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  82295. this._contrast = 1.0;
  82296. /**
  82297. * Vignette stretch size.
  82298. */
  82299. this.vignetteStretch = 0;
  82300. /**
  82301. * Vignette centre X Offset.
  82302. */
  82303. this.vignetteCentreX = 0;
  82304. /**
  82305. * Vignette centre Y Offset.
  82306. */
  82307. this.vignetteCentreY = 0;
  82308. /**
  82309. * Vignette weight or intensity of the vignette effect.
  82310. */
  82311. this.vignetteWeight = 1.5;
  82312. /**
  82313. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82314. * if vignetteEnabled is set to true.
  82315. */
  82316. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82317. /**
  82318. * Camera field of view used by the Vignette effect.
  82319. */
  82320. this.vignetteCameraFov = 0.5;
  82321. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  82322. this._vignetteEnabled = false;
  82323. this._applyByPostProcess = false;
  82324. this._isEnabled = true;
  82325. /**
  82326. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  82327. */
  82328. this.onUpdateParameters = new BABYLON.Observable();
  82329. }
  82330. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  82331. /**
  82332. * Gets wether the color curves effect is enabled.
  82333. */
  82334. get: function () {
  82335. return this._colorCurvesEnabled;
  82336. },
  82337. /**
  82338. * Sets wether the color curves effect is enabled.
  82339. */
  82340. set: function (value) {
  82341. if (this._colorCurvesEnabled === value) {
  82342. return;
  82343. }
  82344. this._colorCurvesEnabled = value;
  82345. this._updateParameters();
  82346. },
  82347. enumerable: true,
  82348. configurable: true
  82349. });
  82350. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  82351. /**
  82352. * Gets wether the color grading effect is enabled.
  82353. */
  82354. get: function () {
  82355. return this._colorGradingEnabled;
  82356. },
  82357. /**
  82358. * Sets wether the color grading effect is enabled.
  82359. */
  82360. set: function (value) {
  82361. if (this._colorGradingEnabled === value) {
  82362. return;
  82363. }
  82364. this._colorGradingEnabled = value;
  82365. this._updateParameters();
  82366. },
  82367. enumerable: true,
  82368. configurable: true
  82369. });
  82370. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  82371. /**
  82372. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  82373. */
  82374. get: function () {
  82375. return this._colorGradingWithGreenDepth;
  82376. },
  82377. /**
  82378. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  82379. */
  82380. set: function (value) {
  82381. if (this._colorGradingWithGreenDepth === value) {
  82382. return;
  82383. }
  82384. this._colorGradingWithGreenDepth = value;
  82385. this._updateParameters();
  82386. },
  82387. enumerable: true,
  82388. configurable: true
  82389. });
  82390. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  82391. /**
  82392. * Gets wether the color grading texture contains BGR values.
  82393. */
  82394. get: function () {
  82395. return this._colorGradingBGR;
  82396. },
  82397. /**
  82398. * Sets wether the color grading texture contains BGR values.
  82399. */
  82400. set: function (value) {
  82401. if (this._colorGradingBGR === value) {
  82402. return;
  82403. }
  82404. this._colorGradingBGR = value;
  82405. this._updateParameters();
  82406. },
  82407. enumerable: true,
  82408. configurable: true
  82409. });
  82410. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  82411. /**
  82412. * Gets the Exposure used in the effect.
  82413. */
  82414. get: function () {
  82415. return this._exposure;
  82416. },
  82417. /**
  82418. * Sets the Exposure used in the effect.
  82419. */
  82420. set: function (value) {
  82421. if (this._exposure === value) {
  82422. return;
  82423. }
  82424. this._exposure = value;
  82425. this._updateParameters();
  82426. },
  82427. enumerable: true,
  82428. configurable: true
  82429. });
  82430. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  82431. /**
  82432. * Gets wether the tone mapping effect is enabled.
  82433. */
  82434. get: function () {
  82435. return this._toneMappingEnabled;
  82436. },
  82437. /**
  82438. * Sets wether the tone mapping effect is enabled.
  82439. */
  82440. set: function (value) {
  82441. if (this._toneMappingEnabled === value) {
  82442. return;
  82443. }
  82444. this._toneMappingEnabled = value;
  82445. this._updateParameters();
  82446. },
  82447. enumerable: true,
  82448. configurable: true
  82449. });
  82450. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  82451. /**
  82452. * Gets the type of tone mapping effect.
  82453. */
  82454. get: function () {
  82455. return this._toneMappingType;
  82456. },
  82457. /**
  82458. * Sets the type of tone mapping effect used in BabylonJS.
  82459. */
  82460. set: function (value) {
  82461. if (this._toneMappingType === value) {
  82462. return;
  82463. }
  82464. this._toneMappingType = value;
  82465. this._updateParameters();
  82466. },
  82467. enumerable: true,
  82468. configurable: true
  82469. });
  82470. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  82471. /**
  82472. * Gets the contrast used in the effect.
  82473. */
  82474. get: function () {
  82475. return this._contrast;
  82476. },
  82477. /**
  82478. * Sets the contrast used in the effect.
  82479. */
  82480. set: function (value) {
  82481. if (this._contrast === value) {
  82482. return;
  82483. }
  82484. this._contrast = value;
  82485. this._updateParameters();
  82486. },
  82487. enumerable: true,
  82488. configurable: true
  82489. });
  82490. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  82491. /**
  82492. * Gets the vignette blend mode allowing different kind of effect.
  82493. */
  82494. get: function () {
  82495. return this._vignetteBlendMode;
  82496. },
  82497. /**
  82498. * Sets the vignette blend mode allowing different kind of effect.
  82499. */
  82500. set: function (value) {
  82501. if (this._vignetteBlendMode === value) {
  82502. return;
  82503. }
  82504. this._vignetteBlendMode = value;
  82505. this._updateParameters();
  82506. },
  82507. enumerable: true,
  82508. configurable: true
  82509. });
  82510. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  82511. /**
  82512. * Gets wether the vignette effect is enabled.
  82513. */
  82514. get: function () {
  82515. return this._vignetteEnabled;
  82516. },
  82517. /**
  82518. * Sets wether the vignette effect is enabled.
  82519. */
  82520. set: function (value) {
  82521. if (this._vignetteEnabled === value) {
  82522. return;
  82523. }
  82524. this._vignetteEnabled = value;
  82525. this._updateParameters();
  82526. },
  82527. enumerable: true,
  82528. configurable: true
  82529. });
  82530. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  82531. /**
  82532. * Gets wether the image processing is applied through a post process or not.
  82533. */
  82534. get: function () {
  82535. return this._applyByPostProcess;
  82536. },
  82537. /**
  82538. * Sets wether the image processing is applied through a post process or not.
  82539. */
  82540. set: function (value) {
  82541. if (this._applyByPostProcess === value) {
  82542. return;
  82543. }
  82544. this._applyByPostProcess = value;
  82545. this._updateParameters();
  82546. },
  82547. enumerable: true,
  82548. configurable: true
  82549. });
  82550. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82551. /**
  82552. * Gets wether the image processing is enabled or not.
  82553. */
  82554. get: function () {
  82555. return this._isEnabled;
  82556. },
  82557. /**
  82558. * Sets wether the image processing is enabled or not.
  82559. */
  82560. set: function (value) {
  82561. if (this._isEnabled === value) {
  82562. return;
  82563. }
  82564. this._isEnabled = value;
  82565. this._updateParameters();
  82566. },
  82567. enumerable: true,
  82568. configurable: true
  82569. });
  82570. /**
  82571. * Method called each time the image processing information changes requires to recompile the effect.
  82572. */
  82573. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82574. this.onUpdateParameters.notifyObservers(this);
  82575. };
  82576. ImageProcessingConfiguration.prototype.getClassName = function () {
  82577. return "ImageProcessingConfiguration";
  82578. };
  82579. /**
  82580. * Prepare the list of uniforms associated with the Image Processing effects.
  82581. * @param uniformsList The list of uniforms used in the effect
  82582. * @param defines the list of defines currently in use
  82583. */
  82584. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82585. if (defines.EXPOSURE) {
  82586. uniforms.push("exposureLinear");
  82587. }
  82588. if (defines.CONTRAST) {
  82589. uniforms.push("contrast");
  82590. }
  82591. if (defines.COLORGRADING) {
  82592. uniforms.push("colorTransformSettings");
  82593. }
  82594. if (defines.VIGNETTE) {
  82595. uniforms.push("vInverseScreenSize");
  82596. uniforms.push("vignetteSettings1");
  82597. uniforms.push("vignetteSettings2");
  82598. }
  82599. if (defines.COLORCURVES) {
  82600. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82601. }
  82602. };
  82603. /**
  82604. * Prepare the list of samplers associated with the Image Processing effects.
  82605. * @param uniformsList The list of uniforms used in the effect
  82606. * @param defines the list of defines currently in use
  82607. */
  82608. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82609. if (defines.COLORGRADING) {
  82610. samplersList.push("txColorTransform");
  82611. }
  82612. };
  82613. /**
  82614. * Prepare the list of defines associated to the shader.
  82615. * @param defines the list of defines to complete
  82616. */
  82617. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82618. if (forPostProcess === void 0) { forPostProcess = false; }
  82619. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82620. defines.VIGNETTE = false;
  82621. defines.TONEMAPPING = false;
  82622. defines.TONEMAPPING_ACES = false;
  82623. defines.CONTRAST = false;
  82624. defines.EXPOSURE = false;
  82625. defines.COLORCURVES = false;
  82626. defines.COLORGRADING = false;
  82627. defines.COLORGRADING3D = false;
  82628. defines.IMAGEPROCESSING = false;
  82629. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82630. return;
  82631. }
  82632. defines.VIGNETTE = this.vignetteEnabled;
  82633. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82634. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82635. defines.TONEMAPPING = this.toneMappingEnabled;
  82636. switch (this._toneMappingType) {
  82637. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82638. defines.TONEMAPPING_ACES = true;
  82639. break;
  82640. }
  82641. defines.CONTRAST = (this.contrast !== 1.0);
  82642. defines.EXPOSURE = (this.exposure !== 1.0);
  82643. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82644. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82645. if (defines.COLORGRADING) {
  82646. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82647. }
  82648. else {
  82649. defines.COLORGRADING3D = false;
  82650. }
  82651. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82652. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82653. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82654. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82655. };
  82656. /**
  82657. * Returns true if all the image processing information are ready.
  82658. */
  82659. ImageProcessingConfiguration.prototype.isReady = function () {
  82660. // Color Grading texure can not be none blocking.
  82661. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82662. };
  82663. /**
  82664. * Binds the image processing to the shader.
  82665. * @param effect The effect to bind to
  82666. */
  82667. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82668. if (aspectRatio === void 0) { aspectRatio = 1; }
  82669. // Color Curves
  82670. if (this._colorCurvesEnabled && this.colorCurves) {
  82671. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82672. }
  82673. // Vignette
  82674. if (this._vignetteEnabled) {
  82675. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82676. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82677. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82678. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82679. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82680. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82681. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82682. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82683. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82684. var vignettePower = -2.0 * this.vignetteWeight;
  82685. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82686. }
  82687. // Exposure
  82688. effect.setFloat("exposureLinear", this.exposure);
  82689. // Contrast
  82690. effect.setFloat("contrast", this.contrast);
  82691. // Color transform settings
  82692. if (this.colorGradingTexture) {
  82693. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82694. var textureSize = this.colorGradingTexture.getSize().height;
  82695. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82696. 0.5 / textureSize, // textureOffset
  82697. textureSize, // textureSize
  82698. this.colorGradingTexture.level // weight
  82699. );
  82700. }
  82701. };
  82702. /**
  82703. * Clones the current image processing instance.
  82704. * @return The cloned image processing
  82705. */
  82706. ImageProcessingConfiguration.prototype.clone = function () {
  82707. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82708. };
  82709. /**
  82710. * Serializes the current image processing instance to a json representation.
  82711. * @return a JSON representation
  82712. */
  82713. ImageProcessingConfiguration.prototype.serialize = function () {
  82714. return BABYLON.SerializationHelper.Serialize(this);
  82715. };
  82716. /**
  82717. * Parses the image processing from a json representation.
  82718. * @param source the JSON source to parse
  82719. * @return The parsed image processing
  82720. */
  82721. ImageProcessingConfiguration.Parse = function (source) {
  82722. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82723. };
  82724. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82725. /**
  82726. * Used to apply the vignette as a mix with the pixel color.
  82727. */
  82728. get: function () {
  82729. return this._VIGNETTEMODE_MULTIPLY;
  82730. },
  82731. enumerable: true,
  82732. configurable: true
  82733. });
  82734. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82735. /**
  82736. * Used to apply the vignette as a replacement of the pixel color.
  82737. */
  82738. get: function () {
  82739. return this._VIGNETTEMODE_OPAQUE;
  82740. },
  82741. enumerable: true,
  82742. configurable: true
  82743. });
  82744. /**
  82745. * Default tone mapping applied in BabylonJS.
  82746. */
  82747. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82748. /**
  82749. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82750. * to other engines rendering to increase portability.
  82751. */
  82752. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82753. // Static constants associated to the image processing.
  82754. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82755. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82756. __decorate([
  82757. BABYLON.serializeAsColorCurves()
  82758. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82759. __decorate([
  82760. BABYLON.serialize()
  82761. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82762. __decorate([
  82763. BABYLON.serializeAsTexture()
  82764. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82765. __decorate([
  82766. BABYLON.serialize()
  82767. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82768. __decorate([
  82769. BABYLON.serialize()
  82770. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82771. __decorate([
  82772. BABYLON.serialize()
  82773. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82774. __decorate([
  82775. BABYLON.serialize()
  82776. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82777. __decorate([
  82778. BABYLON.serialize()
  82779. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82780. __decorate([
  82781. BABYLON.serialize()
  82782. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82783. __decorate([
  82784. BABYLON.serialize()
  82785. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82786. __decorate([
  82787. BABYLON.serialize()
  82788. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82789. __decorate([
  82790. BABYLON.serialize()
  82791. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82792. __decorate([
  82793. BABYLON.serialize()
  82794. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82795. __decorate([
  82796. BABYLON.serialize()
  82797. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82798. __decorate([
  82799. BABYLON.serializeAsColor4()
  82800. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82801. __decorate([
  82802. BABYLON.serialize()
  82803. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82804. __decorate([
  82805. BABYLON.serialize()
  82806. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82807. __decorate([
  82808. BABYLON.serialize()
  82809. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82810. __decorate([
  82811. BABYLON.serialize()
  82812. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82813. __decorate([
  82814. BABYLON.serialize()
  82815. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82816. return ImageProcessingConfiguration;
  82817. }());
  82818. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82819. })(BABYLON || (BABYLON = {}));
  82820. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82821. var BABYLON;
  82822. (function (BABYLON) {
  82823. /**
  82824. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82825. * It can help converting any input color in a desired output one. This can then be used to create effects
  82826. * from sepia, black and white to sixties or futuristic rendering...
  82827. *
  82828. * The only supported format is currently 3dl.
  82829. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82830. */
  82831. var ColorGradingTexture = /** @class */ (function (_super) {
  82832. __extends(ColorGradingTexture, _super);
  82833. /**
  82834. * Instantiates a ColorGradingTexture from the following parameters.
  82835. *
  82836. * @param url The location of the color gradind data (currently only supporting 3dl)
  82837. * @param scene The scene the texture will be used in
  82838. */
  82839. function ColorGradingTexture(url, scene) {
  82840. var _this = _super.call(this, scene) || this;
  82841. if (!url) {
  82842. return _this;
  82843. }
  82844. _this._engine = scene.getEngine();
  82845. _this._textureMatrix = BABYLON.Matrix.Identity();
  82846. _this.name = url;
  82847. _this.url = url;
  82848. _this.hasAlpha = false;
  82849. _this.isCube = false;
  82850. _this.is3D = _this._engine.webGLVersion > 1;
  82851. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82852. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82853. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82854. _this.anisotropicFilteringLevel = 1;
  82855. _this._texture = _this._getFromCache(url, true);
  82856. if (!_this._texture) {
  82857. if (!scene.useDelayedTextureLoading) {
  82858. _this.loadTexture();
  82859. }
  82860. else {
  82861. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82862. }
  82863. }
  82864. return _this;
  82865. }
  82866. /**
  82867. * Returns the texture matrix used in most of the material.
  82868. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82869. */
  82870. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82871. return this._textureMatrix;
  82872. };
  82873. /**
  82874. * Occurs when the file being loaded is a .3dl LUT file.
  82875. */
  82876. ColorGradingTexture.prototype.load3dlTexture = function () {
  82877. var engine = this._engine;
  82878. var texture;
  82879. if (engine.webGLVersion === 1) {
  82880. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82881. }
  82882. else {
  82883. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82884. }
  82885. this._texture = texture;
  82886. var callback = function (text) {
  82887. if (typeof text !== "string") {
  82888. return;
  82889. }
  82890. var data = null;
  82891. var tempData = null;
  82892. var line;
  82893. var lines = text.split('\n');
  82894. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82895. var maxColor = 0;
  82896. for (var i = 0; i < lines.length; i++) {
  82897. line = lines[i];
  82898. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82899. continue;
  82900. if (line.indexOf('#') === 0)
  82901. continue;
  82902. var words = line.split(" ");
  82903. if (size === 0) {
  82904. // Number of space + one
  82905. size = words.length;
  82906. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82907. tempData = new Float32Array(size * size * size * 4);
  82908. continue;
  82909. }
  82910. if (size != 0) {
  82911. var r = Math.max(parseInt(words[0]), 0);
  82912. var g = Math.max(parseInt(words[1]), 0);
  82913. var b = Math.max(parseInt(words[2]), 0);
  82914. maxColor = Math.max(r, maxColor);
  82915. maxColor = Math.max(g, maxColor);
  82916. maxColor = Math.max(b, maxColor);
  82917. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82918. if (tempData) {
  82919. tempData[pixelStorageIndex + 0] = r;
  82920. tempData[pixelStorageIndex + 1] = g;
  82921. tempData[pixelStorageIndex + 2] = b;
  82922. }
  82923. pixelIndexSlice++;
  82924. if (pixelIndexSlice % size == 0) {
  82925. pixelIndexH++;
  82926. pixelIndexSlice = 0;
  82927. if (pixelIndexH % size == 0) {
  82928. pixelIndexW++;
  82929. pixelIndexH = 0;
  82930. }
  82931. }
  82932. }
  82933. }
  82934. if (tempData && data) {
  82935. for (var i = 0; i < tempData.length; i++) {
  82936. if (i > 0 && (i + 1) % 4 === 0) {
  82937. data[i] = 255;
  82938. }
  82939. else {
  82940. var value = tempData[i];
  82941. data[i] = (value / maxColor * 255);
  82942. }
  82943. }
  82944. }
  82945. if (texture.is3D) {
  82946. texture.updateSize(size, size, size);
  82947. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82948. }
  82949. else {
  82950. texture.updateSize(size * size, size);
  82951. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82952. }
  82953. };
  82954. var scene = this.getScene();
  82955. if (scene) {
  82956. scene._loadFile(this.url, callback);
  82957. }
  82958. else {
  82959. this._engine._loadFile(this.url, callback);
  82960. }
  82961. return this._texture;
  82962. };
  82963. /**
  82964. * Starts the loading process of the texture.
  82965. */
  82966. ColorGradingTexture.prototype.loadTexture = function () {
  82967. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82968. this.load3dlTexture();
  82969. }
  82970. };
  82971. /**
  82972. * Clones the color gradind texture.
  82973. */
  82974. ColorGradingTexture.prototype.clone = function () {
  82975. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82976. // Base texture
  82977. newTexture.level = this.level;
  82978. return newTexture;
  82979. };
  82980. /**
  82981. * Called during delayed load for textures.
  82982. */
  82983. ColorGradingTexture.prototype.delayLoad = function () {
  82984. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82985. return;
  82986. }
  82987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82988. this._texture = this._getFromCache(this.url, true);
  82989. if (!this._texture) {
  82990. this.loadTexture();
  82991. }
  82992. };
  82993. /**
  82994. * Parses a color grading texture serialized by Babylon.
  82995. * @param parsedTexture The texture information being parsedTexture
  82996. * @param scene The scene to load the texture in
  82997. * @param rootUrl The root url of the data assets to load
  82998. * @return A color gradind texture
  82999. */
  83000. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83001. var texture = null;
  83002. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83003. texture = new ColorGradingTexture(parsedTexture.name, scene);
  83004. texture.name = parsedTexture.name;
  83005. texture.level = parsedTexture.level;
  83006. }
  83007. return texture;
  83008. };
  83009. /**
  83010. * Serializes the LUT texture to json format.
  83011. */
  83012. ColorGradingTexture.prototype.serialize = function () {
  83013. if (!this.name) {
  83014. return null;
  83015. }
  83016. var serializationObject = {};
  83017. serializationObject.name = this.name;
  83018. serializationObject.level = this.level;
  83019. serializationObject.customType = "BABYLON.ColorGradingTexture";
  83020. return serializationObject;
  83021. };
  83022. /**
  83023. * Empty line regex stored for GC.
  83024. */
  83025. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  83026. return ColorGradingTexture;
  83027. }(BABYLON.BaseTexture));
  83028. BABYLON.ColorGradingTexture = ColorGradingTexture;
  83029. })(BABYLON || (BABYLON = {}));
  83030. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  83031. var BABYLON;
  83032. (function (BABYLON) {
  83033. /**
  83034. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83035. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83036. * 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;
  83037. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83038. */
  83039. var ColorCurves = /** @class */ (function () {
  83040. function ColorCurves() {
  83041. this._dirty = true;
  83042. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  83043. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  83044. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  83045. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  83046. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  83047. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  83048. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  83049. this._globalHue = 30;
  83050. this._globalDensity = 0;
  83051. this._globalSaturation = 0;
  83052. this._globalExposure = 0;
  83053. this._highlightsHue = 30;
  83054. this._highlightsDensity = 0;
  83055. this._highlightsSaturation = 0;
  83056. this._highlightsExposure = 0;
  83057. this._midtonesHue = 30;
  83058. this._midtonesDensity = 0;
  83059. this._midtonesSaturation = 0;
  83060. this._midtonesExposure = 0;
  83061. this._shadowsHue = 30;
  83062. this._shadowsDensity = 0;
  83063. this._shadowsSaturation = 0;
  83064. this._shadowsExposure = 0;
  83065. }
  83066. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  83067. /**
  83068. * Gets the global Hue value.
  83069. * 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).
  83070. */
  83071. get: function () {
  83072. return this._globalHue;
  83073. },
  83074. /**
  83075. * Sets the global Hue value.
  83076. * 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).
  83077. */
  83078. set: function (value) {
  83079. this._globalHue = value;
  83080. this._dirty = true;
  83081. },
  83082. enumerable: true,
  83083. configurable: true
  83084. });
  83085. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  83086. /**
  83087. * Gets the global Density value.
  83088. * 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.
  83089. * Values less than zero provide a filter of opposite hue.
  83090. */
  83091. get: function () {
  83092. return this._globalDensity;
  83093. },
  83094. /**
  83095. * Sets the global Density value.
  83096. * 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.
  83097. * Values less than zero provide a filter of opposite hue.
  83098. */
  83099. set: function (value) {
  83100. this._globalDensity = value;
  83101. this._dirty = true;
  83102. },
  83103. enumerable: true,
  83104. configurable: true
  83105. });
  83106. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  83107. /**
  83108. * Gets the global Saturation value.
  83109. * 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.
  83110. */
  83111. get: function () {
  83112. return this._globalSaturation;
  83113. },
  83114. /**
  83115. * Sets the global Saturation value.
  83116. * 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.
  83117. */
  83118. set: function (value) {
  83119. this._globalSaturation = value;
  83120. this._dirty = true;
  83121. },
  83122. enumerable: true,
  83123. configurable: true
  83124. });
  83125. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  83126. /**
  83127. * Gets the global Exposure value.
  83128. * 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.
  83129. */
  83130. get: function () {
  83131. return this._globalExposure;
  83132. },
  83133. /**
  83134. * Sets the global Exposure value.
  83135. * 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.
  83136. */
  83137. set: function (value) {
  83138. this._globalExposure = value;
  83139. this._dirty = true;
  83140. },
  83141. enumerable: true,
  83142. configurable: true
  83143. });
  83144. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  83145. /**
  83146. * Gets the highlights Hue value.
  83147. * 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).
  83148. */
  83149. get: function () {
  83150. return this._highlightsHue;
  83151. },
  83152. /**
  83153. * Sets the highlights Hue value.
  83154. * 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).
  83155. */
  83156. set: function (value) {
  83157. this._highlightsHue = value;
  83158. this._dirty = true;
  83159. },
  83160. enumerable: true,
  83161. configurable: true
  83162. });
  83163. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  83164. /**
  83165. * Gets the highlights Density value.
  83166. * 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.
  83167. * Values less than zero provide a filter of opposite hue.
  83168. */
  83169. get: function () {
  83170. return this._highlightsDensity;
  83171. },
  83172. /**
  83173. * Sets the highlights Density value.
  83174. * 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.
  83175. * Values less than zero provide a filter of opposite hue.
  83176. */
  83177. set: function (value) {
  83178. this._highlightsDensity = value;
  83179. this._dirty = true;
  83180. },
  83181. enumerable: true,
  83182. configurable: true
  83183. });
  83184. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  83185. /**
  83186. * Gets the highlights Saturation value.
  83187. * 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.
  83188. */
  83189. get: function () {
  83190. return this._highlightsSaturation;
  83191. },
  83192. /**
  83193. * Sets the highlights Saturation value.
  83194. * 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.
  83195. */
  83196. set: function (value) {
  83197. this._highlightsSaturation = value;
  83198. this._dirty = true;
  83199. },
  83200. enumerable: true,
  83201. configurable: true
  83202. });
  83203. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  83204. /**
  83205. * Gets the highlights Exposure value.
  83206. * 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.
  83207. */
  83208. get: function () {
  83209. return this._highlightsExposure;
  83210. },
  83211. /**
  83212. * Sets the highlights Exposure value.
  83213. * 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.
  83214. */
  83215. set: function (value) {
  83216. this._highlightsExposure = value;
  83217. this._dirty = true;
  83218. },
  83219. enumerable: true,
  83220. configurable: true
  83221. });
  83222. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  83223. /**
  83224. * Gets the midtones Hue value.
  83225. * 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).
  83226. */
  83227. get: function () {
  83228. return this._midtonesHue;
  83229. },
  83230. /**
  83231. * Sets the midtones Hue value.
  83232. * 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).
  83233. */
  83234. set: function (value) {
  83235. this._midtonesHue = value;
  83236. this._dirty = true;
  83237. },
  83238. enumerable: true,
  83239. configurable: true
  83240. });
  83241. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  83242. /**
  83243. * Gets the midtones Density value.
  83244. * 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.
  83245. * Values less than zero provide a filter of opposite hue.
  83246. */
  83247. get: function () {
  83248. return this._midtonesDensity;
  83249. },
  83250. /**
  83251. * Sets the midtones Density value.
  83252. * 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.
  83253. * Values less than zero provide a filter of opposite hue.
  83254. */
  83255. set: function (value) {
  83256. this._midtonesDensity = value;
  83257. this._dirty = true;
  83258. },
  83259. enumerable: true,
  83260. configurable: true
  83261. });
  83262. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  83263. /**
  83264. * Gets the midtones Saturation value.
  83265. * 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.
  83266. */
  83267. get: function () {
  83268. return this._midtonesSaturation;
  83269. },
  83270. /**
  83271. * Sets the midtones Saturation value.
  83272. * 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.
  83273. */
  83274. set: function (value) {
  83275. this._midtonesSaturation = value;
  83276. this._dirty = true;
  83277. },
  83278. enumerable: true,
  83279. configurable: true
  83280. });
  83281. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  83282. /**
  83283. * Gets the midtones Exposure value.
  83284. * 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.
  83285. */
  83286. get: function () {
  83287. return this._midtonesExposure;
  83288. },
  83289. /**
  83290. * Sets the midtones Exposure value.
  83291. * 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.
  83292. */
  83293. set: function (value) {
  83294. this._midtonesExposure = value;
  83295. this._dirty = true;
  83296. },
  83297. enumerable: true,
  83298. configurable: true
  83299. });
  83300. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  83301. /**
  83302. * Gets the shadows Hue value.
  83303. * 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).
  83304. */
  83305. get: function () {
  83306. return this._shadowsHue;
  83307. },
  83308. /**
  83309. * Sets the shadows Hue value.
  83310. * 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).
  83311. */
  83312. set: function (value) {
  83313. this._shadowsHue = value;
  83314. this._dirty = true;
  83315. },
  83316. enumerable: true,
  83317. configurable: true
  83318. });
  83319. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  83320. /**
  83321. * Gets the shadows Density value.
  83322. * 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.
  83323. * Values less than zero provide a filter of opposite hue.
  83324. */
  83325. get: function () {
  83326. return this._shadowsDensity;
  83327. },
  83328. /**
  83329. * Sets the shadows Density value.
  83330. * 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.
  83331. * Values less than zero provide a filter of opposite hue.
  83332. */
  83333. set: function (value) {
  83334. this._shadowsDensity = value;
  83335. this._dirty = true;
  83336. },
  83337. enumerable: true,
  83338. configurable: true
  83339. });
  83340. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  83341. /**
  83342. * Gets the shadows Saturation value.
  83343. * 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.
  83344. */
  83345. get: function () {
  83346. return this._shadowsSaturation;
  83347. },
  83348. /**
  83349. * Sets the shadows Saturation value.
  83350. * 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.
  83351. */
  83352. set: function (value) {
  83353. this._shadowsSaturation = value;
  83354. this._dirty = true;
  83355. },
  83356. enumerable: true,
  83357. configurable: true
  83358. });
  83359. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  83360. /**
  83361. * Gets the shadows Exposure value.
  83362. * 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.
  83363. */
  83364. get: function () {
  83365. return this._shadowsExposure;
  83366. },
  83367. /**
  83368. * Sets the shadows Exposure value.
  83369. * 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.
  83370. */
  83371. set: function (value) {
  83372. this._shadowsExposure = value;
  83373. this._dirty = true;
  83374. },
  83375. enumerable: true,
  83376. configurable: true
  83377. });
  83378. ColorCurves.prototype.getClassName = function () {
  83379. return "ColorCurves";
  83380. };
  83381. /**
  83382. * Binds the color curves to the shader.
  83383. * @param colorCurves The color curve to bind
  83384. * @param effect The effect to bind to
  83385. */
  83386. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  83387. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  83388. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  83389. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  83390. if (colorCurves._dirty) {
  83391. colorCurves._dirty = false;
  83392. // Fill in global info.
  83393. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  83394. // Compute highlights info.
  83395. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  83396. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  83397. // Compute midtones info.
  83398. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  83399. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  83400. // Compute shadows info.
  83401. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  83402. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  83403. // Compute deltas (neutral is midtones).
  83404. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  83405. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  83406. }
  83407. if (effect) {
  83408. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  83409. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  83410. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  83411. }
  83412. };
  83413. /**
  83414. * Prepare the list of uniforms associated with the ColorCurves effects.
  83415. * @param uniformsList The list of uniforms used in the effect
  83416. */
  83417. ColorCurves.PrepareUniforms = function (uniformsList) {
  83418. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  83419. };
  83420. /**
  83421. * Returns color grading data based on a hue, density, saturation and exposure value.
  83422. * @param filterHue The hue of the color filter.
  83423. * @param filterDensity The density of the color filter.
  83424. * @param saturation The saturation.
  83425. * @param exposure The exposure.
  83426. * @param result The result data container.
  83427. */
  83428. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  83429. if (hue == null) {
  83430. return;
  83431. }
  83432. hue = ColorCurves.clamp(hue, 0, 360);
  83433. density = ColorCurves.clamp(density, -100, 100);
  83434. saturation = ColorCurves.clamp(saturation, -100, 100);
  83435. exposure = ColorCurves.clamp(exposure, -100, 100);
  83436. // Remap the slider/config filter density with non-linear mapping and also scale by half
  83437. // so that the maximum filter density is only 50% control. This provides fine control
  83438. // for small values and reasonable range.
  83439. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  83440. density *= 0.5;
  83441. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  83442. if (density < 0) {
  83443. density *= -1;
  83444. hue = (hue + 180) % 360;
  83445. }
  83446. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  83447. result.scaleToRef(2, result);
  83448. result.a = 1 + 0.01 * saturation;
  83449. };
  83450. /**
  83451. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  83452. * @param value The input slider value in range [-100,100].
  83453. * @returns Adjusted value.
  83454. */
  83455. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  83456. value /= 100;
  83457. var x = Math.abs(value);
  83458. x = Math.pow(x, 2);
  83459. if (value < 0) {
  83460. x *= -1;
  83461. }
  83462. x *= 100;
  83463. return x;
  83464. };
  83465. /**
  83466. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  83467. * @param hue The hue (H) input.
  83468. * @param saturation The saturation (S) input.
  83469. * @param brightness The brightness (B) input.
  83470. * @result An RGBA color represented as Vector4.
  83471. */
  83472. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  83473. var h = ColorCurves.clamp(hue, 0, 360);
  83474. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  83475. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  83476. if (s === 0) {
  83477. result.r = v;
  83478. result.g = v;
  83479. result.b = v;
  83480. }
  83481. else {
  83482. // sector 0 to 5
  83483. h /= 60;
  83484. var i = Math.floor(h);
  83485. // fractional part of h
  83486. var f = h - i;
  83487. var p = v * (1 - s);
  83488. var q = v * (1 - s * f);
  83489. var t = v * (1 - s * (1 - f));
  83490. switch (i) {
  83491. case 0:
  83492. result.r = v;
  83493. result.g = t;
  83494. result.b = p;
  83495. break;
  83496. case 1:
  83497. result.r = q;
  83498. result.g = v;
  83499. result.b = p;
  83500. break;
  83501. case 2:
  83502. result.r = p;
  83503. result.g = v;
  83504. result.b = t;
  83505. break;
  83506. case 3:
  83507. result.r = p;
  83508. result.g = q;
  83509. result.b = v;
  83510. break;
  83511. case 4:
  83512. result.r = t;
  83513. result.g = p;
  83514. result.b = v;
  83515. break;
  83516. default: // case 5:
  83517. result.r = v;
  83518. result.g = p;
  83519. result.b = q;
  83520. break;
  83521. }
  83522. }
  83523. result.a = 1;
  83524. };
  83525. /**
  83526. * Returns a value clamped between min and max
  83527. * @param value The value to clamp
  83528. * @param min The minimum of value
  83529. * @param max The maximum of value
  83530. * @returns The clamped value.
  83531. */
  83532. ColorCurves.clamp = function (value, min, max) {
  83533. return Math.min(Math.max(value, min), max);
  83534. };
  83535. /**
  83536. * Clones the current color curve instance.
  83537. * @return The cloned curves
  83538. */
  83539. ColorCurves.prototype.clone = function () {
  83540. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  83541. };
  83542. /**
  83543. * Serializes the current color curve instance to a json representation.
  83544. * @return a JSON representation
  83545. */
  83546. ColorCurves.prototype.serialize = function () {
  83547. return BABYLON.SerializationHelper.Serialize(this);
  83548. };
  83549. /**
  83550. * Parses the color curve from a json representation.
  83551. * @param source the JSON source to parse
  83552. * @return The parsed curves
  83553. */
  83554. ColorCurves.Parse = function (source) {
  83555. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83556. };
  83557. __decorate([
  83558. BABYLON.serialize()
  83559. ], ColorCurves.prototype, "_globalHue", void 0);
  83560. __decorate([
  83561. BABYLON.serialize()
  83562. ], ColorCurves.prototype, "_globalDensity", void 0);
  83563. __decorate([
  83564. BABYLON.serialize()
  83565. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83566. __decorate([
  83567. BABYLON.serialize()
  83568. ], ColorCurves.prototype, "_globalExposure", void 0);
  83569. __decorate([
  83570. BABYLON.serialize()
  83571. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83572. __decorate([
  83573. BABYLON.serialize()
  83574. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83575. __decorate([
  83576. BABYLON.serialize()
  83577. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83578. __decorate([
  83579. BABYLON.serialize()
  83580. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83581. __decorate([
  83582. BABYLON.serialize()
  83583. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83584. __decorate([
  83585. BABYLON.serialize()
  83586. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83587. __decorate([
  83588. BABYLON.serialize()
  83589. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83590. __decorate([
  83591. BABYLON.serialize()
  83592. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83593. return ColorCurves;
  83594. }());
  83595. BABYLON.ColorCurves = ColorCurves;
  83596. })(BABYLON || (BABYLON = {}));
  83597. //# sourceMappingURL=babylon.colorCurves.js.map
  83598. var BABYLON;
  83599. (function (BABYLON) {
  83600. var RefractionPostProcess = /** @class */ (function (_super) {
  83601. __extends(RefractionPostProcess, _super);
  83602. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83603. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83604. _this.color = color;
  83605. _this.depth = depth;
  83606. _this.colorLevel = colorLevel;
  83607. _this._ownRefractionTexture = true;
  83608. _this.onActivateObservable.add(function (cam) {
  83609. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83610. });
  83611. _this.onApplyObservable.add(function (effect) {
  83612. effect.setColor3("baseColor", _this.color);
  83613. effect.setFloat("depth", _this.depth);
  83614. effect.setFloat("colorLevel", _this.colorLevel);
  83615. effect.setTexture("refractionSampler", _this._refTexture);
  83616. });
  83617. return _this;
  83618. }
  83619. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83620. /**
  83621. * Gets or sets the refraction texture
  83622. * Please note that you are responsible for disposing the texture if you set it manually
  83623. */
  83624. get: function () {
  83625. return this._refTexture;
  83626. },
  83627. set: function (value) {
  83628. if (this._refTexture && this._ownRefractionTexture) {
  83629. this._refTexture.dispose();
  83630. }
  83631. this._refTexture = value;
  83632. this._ownRefractionTexture = false;
  83633. },
  83634. enumerable: true,
  83635. configurable: true
  83636. });
  83637. // Methods
  83638. RefractionPostProcess.prototype.dispose = function (camera) {
  83639. if (this._refTexture && this._ownRefractionTexture) {
  83640. this._refTexture.dispose();
  83641. this._refTexture = null;
  83642. }
  83643. _super.prototype.dispose.call(this, camera);
  83644. };
  83645. return RefractionPostProcess;
  83646. }(BABYLON.PostProcess));
  83647. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83648. })(BABYLON || (BABYLON = {}));
  83649. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83650. var BABYLON;
  83651. (function (BABYLON) {
  83652. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83653. __extends(BlackAndWhitePostProcess, _super);
  83654. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83655. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83656. _this.degree = 1;
  83657. _this.onApplyObservable.add(function (effect) {
  83658. effect.setFloat("degree", _this.degree);
  83659. });
  83660. return _this;
  83661. }
  83662. return BlackAndWhitePostProcess;
  83663. }(BABYLON.PostProcess));
  83664. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83665. })(BABYLON || (BABYLON = {}));
  83666. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83667. var BABYLON;
  83668. (function (BABYLON) {
  83669. /**
  83670. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83671. * input texture to perform effects such as edge detection or sharpening
  83672. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83673. */
  83674. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83675. __extends(ConvolutionPostProcess, _super);
  83676. /**
  83677. * Creates a new instance ConvolutionPostProcess
  83678. * @param name The name of the effect.
  83679. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83680. * @param options The required width/height ratio to downsize to before computing the render pass.
  83681. * @param camera The camera to apply the render pass to.
  83682. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83683. * @param engine The engine which the post process will be applied. (default: current engine)
  83684. * @param reusable If the post process can be reused on the same frame. (default: false)
  83685. * @param textureType Type of textures used when performing the post process. (default: 0)
  83686. */
  83687. function ConvolutionPostProcess(name,
  83688. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83689. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83690. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83691. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83692. _this.kernel = kernel;
  83693. _this.onApply = function (effect) {
  83694. effect.setFloat2("screenSize", _this.width, _this.height);
  83695. effect.setArray("kernel", _this.kernel);
  83696. };
  83697. return _this;
  83698. }
  83699. // Statics
  83700. /**
  83701. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83702. */
  83703. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83704. /**
  83705. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83706. */
  83707. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83708. /**
  83709. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83710. */
  83711. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83712. /**
  83713. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83714. */
  83715. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83716. /**
  83717. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83718. */
  83719. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83720. /**
  83721. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83722. */
  83723. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83724. return ConvolutionPostProcess;
  83725. }(BABYLON.PostProcess));
  83726. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83727. })(BABYLON || (BABYLON = {}));
  83728. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83729. var BABYLON;
  83730. (function (BABYLON) {
  83731. var FilterPostProcess = /** @class */ (function (_super) {
  83732. __extends(FilterPostProcess, _super);
  83733. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83734. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83735. _this.kernelMatrix = kernelMatrix;
  83736. _this.onApply = function (effect) {
  83737. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83738. };
  83739. return _this;
  83740. }
  83741. return FilterPostProcess;
  83742. }(BABYLON.PostProcess));
  83743. BABYLON.FilterPostProcess = FilterPostProcess;
  83744. })(BABYLON || (BABYLON = {}));
  83745. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83746. var BABYLON;
  83747. (function (BABYLON) {
  83748. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83749. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83750. __extends(VolumetricLightScatteringPostProcess, _super);
  83751. /**
  83752. * @constructor
  83753. * @param {string} name - The post-process name
  83754. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  83755. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83756. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83757. * @param {number} samples - The post-process quality, default 100
  83758. * @param {number} samplingMode - The post-process filtering mode
  83759. * @param {BABYLON.Engine} engine - The babylon engine
  83760. * @param {boolean} reusable - If the post-process is reusable
  83761. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83762. */
  83763. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83764. if (samples === void 0) { samples = 100; }
  83765. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83766. 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;
  83767. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83768. /**
  83769. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83770. */
  83771. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83772. /**
  83773. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83774. */
  83775. _this.useCustomMeshPosition = false;
  83776. /**
  83777. * If the post-process should inverse the light scattering direction
  83778. */
  83779. _this.invert = true;
  83780. /**
  83781. * Array containing the excluded meshes not rendered in the internal pass
  83782. */
  83783. _this.excludedMeshes = new Array();
  83784. /**
  83785. * Controls the overall intensity of the post-process
  83786. */
  83787. _this.exposure = 0.3;
  83788. /**
  83789. * Dissipates each sample's contribution in range [0, 1]
  83790. */
  83791. _this.decay = 0.96815;
  83792. /**
  83793. * Controls the overall intensity of each sample
  83794. */
  83795. _this.weight = 0.58767;
  83796. /**
  83797. * Controls the density of each sample
  83798. */
  83799. _this.density = 0.926;
  83800. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83801. engine = scene.getEngine();
  83802. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83803. // Configure mesh
  83804. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83805. // Configure
  83806. _this._createPass(scene, ratio.passRatio || ratio);
  83807. _this.onActivate = function (camera) {
  83808. if (!_this.isSupported) {
  83809. _this.dispose(camera);
  83810. }
  83811. _this.onActivate = null;
  83812. };
  83813. _this.onApplyObservable.add(function (effect) {
  83814. _this._updateMeshScreenCoordinates(scene);
  83815. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83816. effect.setFloat("exposure", _this.exposure);
  83817. effect.setFloat("decay", _this.decay);
  83818. effect.setFloat("weight", _this.weight);
  83819. effect.setFloat("density", _this.density);
  83820. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83821. });
  83822. return _this;
  83823. }
  83824. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83825. get: function () {
  83826. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83827. return false;
  83828. },
  83829. set: function (useDiffuseColor) {
  83830. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83831. },
  83832. enumerable: true,
  83833. configurable: true
  83834. });
  83835. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83836. return "VolumetricLightScatteringPostProcess";
  83837. };
  83838. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83839. var mesh = subMesh.getMesh();
  83840. // Render this.mesh as default
  83841. if (mesh === this.mesh && mesh.material) {
  83842. return mesh.material.isReady(mesh);
  83843. }
  83844. var defines = [];
  83845. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83846. var material = subMesh.getMaterial();
  83847. // Alpha test
  83848. if (material) {
  83849. if (material.needAlphaTesting()) {
  83850. defines.push("#define ALPHATEST");
  83851. }
  83852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83853. attribs.push(BABYLON.VertexBuffer.UVKind);
  83854. defines.push("#define UV1");
  83855. }
  83856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83857. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83858. defines.push("#define UV2");
  83859. }
  83860. }
  83861. // Bones
  83862. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83863. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83864. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83865. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83866. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83867. }
  83868. else {
  83869. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83870. }
  83871. // Instances
  83872. if (useInstances) {
  83873. defines.push("#define INSTANCES");
  83874. attribs.push("world0");
  83875. attribs.push("world1");
  83876. attribs.push("world2");
  83877. attribs.push("world3");
  83878. }
  83879. // Get correct effect
  83880. var join = defines.join("\n");
  83881. if (this._cachedDefines !== join) {
  83882. this._cachedDefines = join;
  83883. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83884. }
  83885. return this._volumetricLightScatteringPass.isReady();
  83886. };
  83887. /**
  83888. * Sets the new light position for light scattering effect
  83889. * @param {BABYLON.Vector3} The new custom light position
  83890. */
  83891. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83892. this.customMeshPosition = position;
  83893. };
  83894. /**
  83895. * Returns the light position for light scattering effect
  83896. * @return {BABYLON.Vector3} The custom light position
  83897. */
  83898. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83899. return this.customMeshPosition;
  83900. };
  83901. /**
  83902. * Disposes the internal assets and detaches the post-process from the camera
  83903. */
  83904. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83905. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83906. if (rttIndex !== -1) {
  83907. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83908. }
  83909. this._volumetricLightScatteringRTT.dispose();
  83910. _super.prototype.dispose.call(this, camera);
  83911. };
  83912. /**
  83913. * Returns the render target texture used by the post-process
  83914. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83915. */
  83916. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83917. return this._volumetricLightScatteringRTT;
  83918. };
  83919. // Private methods
  83920. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83921. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83922. return true;
  83923. }
  83924. return false;
  83925. };
  83926. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83927. var _this = this;
  83928. var engine = scene.getEngine();
  83929. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83930. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83931. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83932. this._volumetricLightScatteringRTT.renderList = null;
  83933. this._volumetricLightScatteringRTT.renderParticles = false;
  83934. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83935. var camera = this.getCamera();
  83936. if (camera) {
  83937. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83938. }
  83939. else {
  83940. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83941. }
  83942. // Custom render function for submeshes
  83943. var renderSubMesh = function (subMesh) {
  83944. var mesh = subMesh.getRenderingMesh();
  83945. if (_this._meshExcluded(mesh)) {
  83946. return;
  83947. }
  83948. var material = subMesh.getMaterial();
  83949. if (!material) {
  83950. return;
  83951. }
  83952. var scene = mesh.getScene();
  83953. var engine = scene.getEngine();
  83954. // Culling
  83955. engine.setState(material.backFaceCulling);
  83956. // Managing instances
  83957. var batch = mesh._getInstancesRenderList(subMesh._id);
  83958. if (batch.mustReturn) {
  83959. return;
  83960. }
  83961. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83962. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83963. var effect = _this._volumetricLightScatteringPass;
  83964. if (mesh === _this.mesh) {
  83965. if (subMesh.effect) {
  83966. effect = subMesh.effect;
  83967. }
  83968. else {
  83969. effect = material.getEffect();
  83970. }
  83971. }
  83972. engine.enableEffect(effect);
  83973. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83974. if (mesh === _this.mesh) {
  83975. material.bind(mesh.getWorldMatrix(), mesh);
  83976. }
  83977. else {
  83978. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83979. // Alpha test
  83980. if (material && material.needAlphaTesting()) {
  83981. var alphaTexture = material.getAlphaTestTexture();
  83982. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83983. if (alphaTexture) {
  83984. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83985. }
  83986. }
  83987. // Bones
  83988. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83989. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83990. }
  83991. }
  83992. // Draw
  83993. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83994. }
  83995. };
  83996. // Render target texture callbacks
  83997. var savedSceneClearColor;
  83998. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83999. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  84000. savedSceneClearColor = scene.clearColor;
  84001. scene.clearColor = sceneClearColor;
  84002. });
  84003. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  84004. scene.clearColor = savedSceneClearColor;
  84005. });
  84006. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84007. var engine = scene.getEngine();
  84008. var index;
  84009. if (depthOnlySubMeshes.length) {
  84010. engine.setColorWrite(false);
  84011. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84012. renderSubMesh(depthOnlySubMeshes.data[index]);
  84013. }
  84014. engine.setColorWrite(true);
  84015. }
  84016. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84017. renderSubMesh(opaqueSubMeshes.data[index]);
  84018. }
  84019. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84020. renderSubMesh(alphaTestSubMeshes.data[index]);
  84021. }
  84022. if (transparentSubMeshes.length) {
  84023. // Sort sub meshes
  84024. for (index = 0; index < transparentSubMeshes.length; index++) {
  84025. var submesh = transparentSubMeshes.data[index];
  84026. var boundingInfo = submesh.getBoundingInfo();
  84027. if (boundingInfo && scene.activeCamera) {
  84028. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  84029. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  84030. }
  84031. }
  84032. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  84033. sortedArray.sort(function (a, b) {
  84034. // Alpha index first
  84035. if (a._alphaIndex > b._alphaIndex) {
  84036. return 1;
  84037. }
  84038. if (a._alphaIndex < b._alphaIndex) {
  84039. return -1;
  84040. }
  84041. // Then distance to camera
  84042. if (a._distanceToCamera < b._distanceToCamera) {
  84043. return 1;
  84044. }
  84045. if (a._distanceToCamera > b._distanceToCamera) {
  84046. return -1;
  84047. }
  84048. return 0;
  84049. });
  84050. // Render sub meshes
  84051. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  84052. for (index = 0; index < sortedArray.length; index++) {
  84053. renderSubMesh(sortedArray[index]);
  84054. }
  84055. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84056. }
  84057. };
  84058. };
  84059. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  84060. var transform = scene.getTransformMatrix();
  84061. var meshPosition;
  84062. if (this.useCustomMeshPosition) {
  84063. meshPosition = this.customMeshPosition;
  84064. }
  84065. else if (this.attachedNode) {
  84066. meshPosition = this.attachedNode.position;
  84067. }
  84068. else {
  84069. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  84070. }
  84071. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  84072. this._screenCoordinates.x = pos.x / this._viewPort.width;
  84073. this._screenCoordinates.y = pos.y / this._viewPort.height;
  84074. if (this.invert)
  84075. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  84076. };
  84077. // Static methods
  84078. /**
  84079. * Creates a default mesh for the Volumeric Light Scattering post-process
  84080. * @param {string} The mesh name
  84081. * @param {BABYLON.Scene} The scene where to create the mesh
  84082. * @return {BABYLON.Mesh} the default mesh
  84083. */
  84084. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  84085. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  84086. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  84087. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  84088. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  84089. mesh.material = material;
  84090. return mesh;
  84091. };
  84092. __decorate([
  84093. BABYLON.serializeAsVector3()
  84094. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  84095. __decorate([
  84096. BABYLON.serialize()
  84097. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  84098. __decorate([
  84099. BABYLON.serialize()
  84100. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  84101. __decorate([
  84102. BABYLON.serializeAsMeshReference()
  84103. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  84104. __decorate([
  84105. BABYLON.serialize()
  84106. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  84107. __decorate([
  84108. BABYLON.serialize()
  84109. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  84110. __decorate([
  84111. BABYLON.serialize()
  84112. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  84113. __decorate([
  84114. BABYLON.serialize()
  84115. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  84116. __decorate([
  84117. BABYLON.serialize()
  84118. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  84119. return VolumetricLightScatteringPostProcess;
  84120. }(BABYLON.PostProcess));
  84121. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  84122. })(BABYLON || (BABYLON = {}));
  84123. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  84124. //
  84125. // This post-process allows the modification of rendered colors by using
  84126. // a 'look-up table' (LUT). This effect is also called Color Grading.
  84127. //
  84128. // The object needs to be provided an url to a texture containing the color
  84129. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  84130. // Use an image editing software to tweak the LUT to match your needs.
  84131. //
  84132. // For an example of a color LUT, see here:
  84133. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  84134. // For explanations on color grading, see here:
  84135. // http://udn.epicgames.com/Three/ColorGrading.html
  84136. //
  84137. var BABYLON;
  84138. (function (BABYLON) {
  84139. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  84140. __extends(ColorCorrectionPostProcess, _super);
  84141. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  84142. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  84143. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84144. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  84145. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84146. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84147. _this.onApply = function (effect) {
  84148. effect.setTexture("colorTable", _this._colorTableTexture);
  84149. };
  84150. return _this;
  84151. }
  84152. return ColorCorrectionPostProcess;
  84153. }(BABYLON.PostProcess));
  84154. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  84155. })(BABYLON || (BABYLON = {}));
  84156. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  84157. var BABYLON;
  84158. (function (BABYLON) {
  84159. /** Defines operator used for tonemapping */
  84160. var TonemappingOperator;
  84161. (function (TonemappingOperator) {
  84162. /** Hable */
  84163. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  84164. /** Reinhard */
  84165. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  84166. /** HejiDawson */
  84167. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  84168. /** Photographic */
  84169. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  84170. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  84171. ;
  84172. /**
  84173. * Defines a post process to apply tone mapping
  84174. */
  84175. var TonemapPostProcess = /** @class */ (function (_super) {
  84176. __extends(TonemapPostProcess, _super);
  84177. /**
  84178. * Creates a new TonemapPostProcess
  84179. * @param name defines the name of the postprocess
  84180. * @param _operator defines the operator to use
  84181. * @param exposureAdjustment defines the required exposure adjustement
  84182. * @param camera defines the camera to use (can be null)
  84183. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  84184. * @param engine defines the hosting engine (can be ignore if camera is set)
  84185. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  84186. */
  84187. function TonemapPostProcess(name, _operator,
  84188. /** Defines the required exposure adjustement */
  84189. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  84190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84191. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84192. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  84193. _this._operator = _operator;
  84194. _this.exposureAdjustment = exposureAdjustment;
  84195. var defines = "#define ";
  84196. if (_this._operator === TonemappingOperator.Hable)
  84197. defines += "HABLE_TONEMAPPING";
  84198. else if (_this._operator === TonemappingOperator.Reinhard)
  84199. defines += "REINHARD_TONEMAPPING";
  84200. else if (_this._operator === TonemappingOperator.HejiDawson)
  84201. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  84202. else if (_this._operator === TonemappingOperator.Photographic)
  84203. defines += "PHOTOGRAPHIC_TONEMAPPING";
  84204. //sadly a second call to create the effect.
  84205. _this.updateEffect(defines);
  84206. _this.onApply = function (effect) {
  84207. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  84208. };
  84209. return _this;
  84210. }
  84211. return TonemapPostProcess;
  84212. }(BABYLON.PostProcess));
  84213. BABYLON.TonemapPostProcess = TonemapPostProcess;
  84214. })(BABYLON || (BABYLON = {}));
  84215. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  84216. var BABYLON;
  84217. (function (BABYLON) {
  84218. var DisplayPassPostProcess = /** @class */ (function (_super) {
  84219. __extends(DisplayPassPostProcess, _super);
  84220. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  84221. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  84222. }
  84223. return DisplayPassPostProcess;
  84224. }(BABYLON.PostProcess));
  84225. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  84226. })(BABYLON || (BABYLON = {}));
  84227. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  84228. var BABYLON;
  84229. (function (BABYLON) {
  84230. var HighlightsPostProcess = /** @class */ (function (_super) {
  84231. __extends(HighlightsPostProcess, _super);
  84232. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84234. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  84235. }
  84236. return HighlightsPostProcess;
  84237. }(BABYLON.PostProcess));
  84238. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  84239. })(BABYLON || (BABYLON = {}));
  84240. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  84241. var BABYLON;
  84242. (function (BABYLON) {
  84243. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  84244. __extends(ImageProcessingPostProcess, _super);
  84245. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  84246. if (camera === void 0) { camera = null; }
  84247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84248. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  84249. _this._fromLinearSpace = true;
  84250. /**
  84251. * Defines cache preventing GC.
  84252. */
  84253. _this._defines = {
  84254. IMAGEPROCESSING: false,
  84255. VIGNETTE: false,
  84256. VIGNETTEBLENDMODEMULTIPLY: false,
  84257. VIGNETTEBLENDMODEOPAQUE: false,
  84258. TONEMAPPING: false,
  84259. TONEMAPPING_ACES: false,
  84260. CONTRAST: false,
  84261. COLORCURVES: false,
  84262. COLORGRADING: false,
  84263. COLORGRADING3D: false,
  84264. FROMLINEARSPACE: false,
  84265. SAMPLER3DGREENDEPTH: false,
  84266. SAMPLER3DBGRMAP: false,
  84267. IMAGEPROCESSINGPOSTPROCESS: false,
  84268. EXPOSURE: false,
  84269. };
  84270. // Setup the configuration as forced by the constructor. This would then not force the
  84271. // scene materials output in linear space and let untouched the default forward pass.
  84272. if (imageProcessingConfiguration) {
  84273. imageProcessingConfiguration.applyByPostProcess = true;
  84274. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  84275. // This will cause the shader to be compiled
  84276. _this.fromLinearSpace = false;
  84277. }
  84278. // Setup the default processing configuration to the scene.
  84279. else {
  84280. _this._attachImageProcessingConfiguration(null, true);
  84281. _this.imageProcessingConfiguration.applyByPostProcess = true;
  84282. }
  84283. _this.onApply = function (effect) {
  84284. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  84285. };
  84286. return _this;
  84287. }
  84288. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  84289. /**
  84290. * Gets the image processing configuration used either in this material.
  84291. */
  84292. get: function () {
  84293. return this._imageProcessingConfiguration;
  84294. },
  84295. /**
  84296. * Sets the Default image processing configuration used either in the this material.
  84297. *
  84298. * If sets to null, the scene one is in use.
  84299. */
  84300. set: function (value) {
  84301. this._attachImageProcessingConfiguration(value);
  84302. },
  84303. enumerable: true,
  84304. configurable: true
  84305. });
  84306. /**
  84307. * Attaches a new image processing configuration to the PBR Material.
  84308. * @param configuration
  84309. */
  84310. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  84311. var _this = this;
  84312. if (doNotBuild === void 0) { doNotBuild = false; }
  84313. if (configuration === this._imageProcessingConfiguration) {
  84314. return;
  84315. }
  84316. // Detaches observer.
  84317. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84318. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84319. }
  84320. // Pick the scene configuration if needed.
  84321. if (!configuration) {
  84322. var scene = null;
  84323. var engine = this.getEngine();
  84324. var camera = this.getCamera();
  84325. if (camera) {
  84326. scene = camera.getScene();
  84327. }
  84328. else if (engine && engine.scenes) {
  84329. var scenes = engine.scenes;
  84330. scene = scenes[scenes.length - 1];
  84331. }
  84332. else {
  84333. scene = BABYLON.Engine.LastCreatedScene;
  84334. }
  84335. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  84336. }
  84337. else {
  84338. this._imageProcessingConfiguration = configuration;
  84339. }
  84340. // Attaches observer.
  84341. if (this._imageProcessingConfiguration) {
  84342. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84343. _this._updateParameters();
  84344. });
  84345. }
  84346. // Ensure the effect will be rebuilt.
  84347. if (!doNotBuild) {
  84348. this._updateParameters();
  84349. }
  84350. };
  84351. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  84352. /**
  84353. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84354. */
  84355. get: function () {
  84356. return this.imageProcessingConfiguration.colorCurves;
  84357. },
  84358. /**
  84359. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84360. */
  84361. set: function (value) {
  84362. this.imageProcessingConfiguration.colorCurves = value;
  84363. },
  84364. enumerable: true,
  84365. configurable: true
  84366. });
  84367. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  84368. /**
  84369. * Gets wether the color curves effect is enabled.
  84370. */
  84371. get: function () {
  84372. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84373. },
  84374. /**
  84375. * Sets wether the color curves effect is enabled.
  84376. */
  84377. set: function (value) {
  84378. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84379. },
  84380. enumerable: true,
  84381. configurable: true
  84382. });
  84383. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  84384. /**
  84385. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84386. */
  84387. get: function () {
  84388. return this.imageProcessingConfiguration.colorGradingTexture;
  84389. },
  84390. /**
  84391. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84392. */
  84393. set: function (value) {
  84394. this.imageProcessingConfiguration.colorGradingTexture = value;
  84395. },
  84396. enumerable: true,
  84397. configurable: true
  84398. });
  84399. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  84400. /**
  84401. * Gets wether the color grading effect is enabled.
  84402. */
  84403. get: function () {
  84404. return this.imageProcessingConfiguration.colorGradingEnabled;
  84405. },
  84406. /**
  84407. * Gets wether the color grading effect is enabled.
  84408. */
  84409. set: function (value) {
  84410. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84411. },
  84412. enumerable: true,
  84413. configurable: true
  84414. });
  84415. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  84416. /**
  84417. * Gets exposure used in the effect.
  84418. */
  84419. get: function () {
  84420. return this.imageProcessingConfiguration.exposure;
  84421. },
  84422. /**
  84423. * Sets exposure used in the effect.
  84424. */
  84425. set: function (value) {
  84426. this.imageProcessingConfiguration.exposure = value;
  84427. },
  84428. enumerable: true,
  84429. configurable: true
  84430. });
  84431. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  84432. /**
  84433. * Gets wether tonemapping is enabled or not.
  84434. */
  84435. get: function () {
  84436. return this._imageProcessingConfiguration.toneMappingEnabled;
  84437. },
  84438. /**
  84439. * Sets wether tonemapping is enabled or not
  84440. */
  84441. set: function (value) {
  84442. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84443. },
  84444. enumerable: true,
  84445. configurable: true
  84446. });
  84447. ;
  84448. ;
  84449. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  84450. /**
  84451. * Gets contrast used in the effect.
  84452. */
  84453. get: function () {
  84454. return this.imageProcessingConfiguration.contrast;
  84455. },
  84456. /**
  84457. * Sets contrast used in the effect.
  84458. */
  84459. set: function (value) {
  84460. this.imageProcessingConfiguration.contrast = value;
  84461. },
  84462. enumerable: true,
  84463. configurable: true
  84464. });
  84465. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  84466. /**
  84467. * Gets Vignette stretch size.
  84468. */
  84469. get: function () {
  84470. return this.imageProcessingConfiguration.vignetteStretch;
  84471. },
  84472. /**
  84473. * Sets Vignette stretch size.
  84474. */
  84475. set: function (value) {
  84476. this.imageProcessingConfiguration.vignetteStretch = value;
  84477. },
  84478. enumerable: true,
  84479. configurable: true
  84480. });
  84481. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  84482. /**
  84483. * Gets Vignette centre X Offset.
  84484. */
  84485. get: function () {
  84486. return this.imageProcessingConfiguration.vignetteCentreX;
  84487. },
  84488. /**
  84489. * Sets Vignette centre X Offset.
  84490. */
  84491. set: function (value) {
  84492. this.imageProcessingConfiguration.vignetteCentreX = value;
  84493. },
  84494. enumerable: true,
  84495. configurable: true
  84496. });
  84497. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  84498. /**
  84499. * Gets Vignette centre Y Offset.
  84500. */
  84501. get: function () {
  84502. return this.imageProcessingConfiguration.vignetteCentreY;
  84503. },
  84504. /**
  84505. * Sets Vignette centre Y Offset.
  84506. */
  84507. set: function (value) {
  84508. this.imageProcessingConfiguration.vignetteCentreY = value;
  84509. },
  84510. enumerable: true,
  84511. configurable: true
  84512. });
  84513. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  84514. /**
  84515. * Gets Vignette weight or intensity of the vignette effect.
  84516. */
  84517. get: function () {
  84518. return this.imageProcessingConfiguration.vignetteWeight;
  84519. },
  84520. /**
  84521. * Sets Vignette weight or intensity of the vignette effect.
  84522. */
  84523. set: function (value) {
  84524. this.imageProcessingConfiguration.vignetteWeight = value;
  84525. },
  84526. enumerable: true,
  84527. configurable: true
  84528. });
  84529. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  84530. /**
  84531. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84532. * if vignetteEnabled is set to true.
  84533. */
  84534. get: function () {
  84535. return this.imageProcessingConfiguration.vignetteColor;
  84536. },
  84537. /**
  84538. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84539. * if vignetteEnabled is set to true.
  84540. */
  84541. set: function (value) {
  84542. this.imageProcessingConfiguration.vignetteColor = value;
  84543. },
  84544. enumerable: true,
  84545. configurable: true
  84546. });
  84547. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84548. /**
  84549. * Gets Camera field of view used by the Vignette effect.
  84550. */
  84551. get: function () {
  84552. return this.imageProcessingConfiguration.vignetteCameraFov;
  84553. },
  84554. /**
  84555. * Sets Camera field of view used by the Vignette effect.
  84556. */
  84557. set: function (value) {
  84558. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84559. },
  84560. enumerable: true,
  84561. configurable: true
  84562. });
  84563. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84564. /**
  84565. * Gets the vignette blend mode allowing different kind of effect.
  84566. */
  84567. get: function () {
  84568. return this.imageProcessingConfiguration.vignetteBlendMode;
  84569. },
  84570. /**
  84571. * Sets the vignette blend mode allowing different kind of effect.
  84572. */
  84573. set: function (value) {
  84574. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84575. },
  84576. enumerable: true,
  84577. configurable: true
  84578. });
  84579. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84580. /**
  84581. * Gets wether the vignette effect is enabled.
  84582. */
  84583. get: function () {
  84584. return this.imageProcessingConfiguration.vignetteEnabled;
  84585. },
  84586. /**
  84587. * Sets wether the vignette effect is enabled.
  84588. */
  84589. set: function (value) {
  84590. this.imageProcessingConfiguration.vignetteEnabled = value;
  84591. },
  84592. enumerable: true,
  84593. configurable: true
  84594. });
  84595. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84596. /**
  84597. * Gets wether the input of the processing is in Gamma or Linear Space.
  84598. */
  84599. get: function () {
  84600. return this._fromLinearSpace;
  84601. },
  84602. /**
  84603. * Sets wether the input of the processing is in Gamma or Linear Space.
  84604. */
  84605. set: function (value) {
  84606. if (this._fromLinearSpace === value) {
  84607. return;
  84608. }
  84609. this._fromLinearSpace = value;
  84610. this._updateParameters();
  84611. },
  84612. enumerable: true,
  84613. configurable: true
  84614. });
  84615. ImageProcessingPostProcess.prototype.getClassName = function () {
  84616. return "ImageProcessingPostProcess";
  84617. };
  84618. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84619. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84620. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84621. var defines = "";
  84622. for (var define in this._defines) {
  84623. if (this._defines[define]) {
  84624. defines += "#define " + define + ";\r\n";
  84625. }
  84626. }
  84627. var samplers = ["textureSampler"];
  84628. var uniforms = ["scale"];
  84629. if (BABYLON.ImageProcessingConfiguration) {
  84630. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84631. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84632. }
  84633. this.updateEffect(defines, uniforms, samplers);
  84634. };
  84635. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84636. _super.prototype.dispose.call(this, camera);
  84637. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84638. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84639. }
  84640. if (this._imageProcessingConfiguration) {
  84641. this.imageProcessingConfiguration.applyByPostProcess = false;
  84642. }
  84643. };
  84644. __decorate([
  84645. BABYLON.serialize()
  84646. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84647. return ImageProcessingPostProcess;
  84648. }(BABYLON.PostProcess));
  84649. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84650. })(BABYLON || (BABYLON = {}));
  84651. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84652. var BABYLON;
  84653. (function (BABYLON) {
  84654. /**
  84655. * Class used to store bone information
  84656. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84657. */
  84658. var Bone = /** @class */ (function (_super) {
  84659. __extends(Bone, _super);
  84660. /**
  84661. * Create a new bone
  84662. * @param name defines the bone name
  84663. * @param skeleton defines the parent skeleton
  84664. * @param parentBone defines the parent (can be null if the bone is the root)
  84665. * @param localMatrix defines the local matrix
  84666. * @param restPose defines the rest pose matrix
  84667. * @param baseMatrix defines the base matrix
  84668. * @param index defines index of the bone in the hiearchy
  84669. */
  84670. function Bone(
  84671. /**
  84672. * defines the bone name
  84673. */
  84674. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84675. if (parentBone === void 0) { parentBone = null; }
  84676. if (localMatrix === void 0) { localMatrix = null; }
  84677. if (restPose === void 0) { restPose = null; }
  84678. if (baseMatrix === void 0) { baseMatrix = null; }
  84679. if (index === void 0) { index = null; }
  84680. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84681. _this.name = name;
  84682. /**
  84683. * Gets the list of child bones
  84684. */
  84685. _this.children = new Array();
  84686. /** Gets the animations associated with this bone */
  84687. _this.animations = new Array();
  84688. /**
  84689. * @hidden Internal only
  84690. * Set this value to map this bone to a different index in the transform matrices
  84691. * Set this value to -1 to exclude the bone from the transform matrices
  84692. */
  84693. _this._index = null;
  84694. _this._absoluteTransform = new BABYLON.Matrix();
  84695. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84696. _this._scalingDeterminant = 1;
  84697. _this._worldTransform = new BABYLON.Matrix();
  84698. _this._needToDecompose = true;
  84699. _this._needToCompose = false;
  84700. _this._skeleton = skeleton;
  84701. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84702. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84703. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84704. _this._index = index;
  84705. skeleton.bones.push(_this);
  84706. _this.setParent(parentBone, false);
  84707. if (baseMatrix || localMatrix) {
  84708. _this._updateDifferenceMatrix();
  84709. }
  84710. return _this;
  84711. }
  84712. Object.defineProperty(Bone.prototype, "_matrix", {
  84713. /** @hidden */
  84714. get: function () {
  84715. this._compose();
  84716. return this._localMatrix;
  84717. },
  84718. /** @hidden */
  84719. set: function (value) {
  84720. this._localMatrix.copyFrom(value);
  84721. this._needToDecompose = true;
  84722. },
  84723. enumerable: true,
  84724. configurable: true
  84725. });
  84726. // Members
  84727. /**
  84728. * Gets the parent skeleton
  84729. * @returns a skeleton
  84730. */
  84731. Bone.prototype.getSkeleton = function () {
  84732. return this._skeleton;
  84733. };
  84734. /**
  84735. * Gets parent bone
  84736. * @returns a bone or null if the bone is the root of the bone hierarchy
  84737. */
  84738. Bone.prototype.getParent = function () {
  84739. return this._parent;
  84740. };
  84741. /**
  84742. * Sets the parent bone
  84743. * @param parent defines the parent (can be null if the bone is the root)
  84744. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84745. */
  84746. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84747. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84748. if (this._parent === parent) {
  84749. return;
  84750. }
  84751. if (this._parent) {
  84752. var index = this._parent.children.indexOf(this);
  84753. if (index !== -1) {
  84754. this._parent.children.splice(index, 1);
  84755. }
  84756. }
  84757. this._parent = parent;
  84758. if (this._parent) {
  84759. this._parent.children.push(this);
  84760. }
  84761. if (updateDifferenceMatrix) {
  84762. this._updateDifferenceMatrix();
  84763. }
  84764. this.markAsDirty();
  84765. };
  84766. /**
  84767. * Gets the local matrix
  84768. * @returns a matrix
  84769. */
  84770. Bone.prototype.getLocalMatrix = function () {
  84771. this._compose();
  84772. return this._localMatrix;
  84773. };
  84774. /**
  84775. * Gets the base matrix (initial matrix which remains unchanged)
  84776. * @returns a matrix
  84777. */
  84778. Bone.prototype.getBaseMatrix = function () {
  84779. return this._baseMatrix;
  84780. };
  84781. /**
  84782. * Gets the rest pose matrix
  84783. * @returns a matrix
  84784. */
  84785. Bone.prototype.getRestPose = function () {
  84786. return this._restPose;
  84787. };
  84788. /**
  84789. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84790. */
  84791. Bone.prototype.getWorldMatrix = function () {
  84792. return this._worldTransform;
  84793. };
  84794. /**
  84795. * Sets the local matrix to rest pose matrix
  84796. */
  84797. Bone.prototype.returnToRest = function () {
  84798. this.updateMatrix(this._restPose.clone());
  84799. };
  84800. /**
  84801. * Gets the inverse of the absolute transform matrix.
  84802. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84803. * @returns a matrix
  84804. */
  84805. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84806. return this._invertedAbsoluteTransform;
  84807. };
  84808. /**
  84809. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84810. * @returns a matrix
  84811. */
  84812. Bone.prototype.getAbsoluteTransform = function () {
  84813. return this._absoluteTransform;
  84814. };
  84815. Object.defineProperty(Bone.prototype, "position", {
  84816. // Properties (matches AbstractMesh properties)
  84817. /** Gets or sets current position (in local space) */
  84818. get: function () {
  84819. this._decompose();
  84820. return this._localPosition;
  84821. },
  84822. set: function (newPosition) {
  84823. this._decompose();
  84824. this._localPosition.copyFrom(newPosition);
  84825. this._markAsDirtyAndCompose();
  84826. },
  84827. enumerable: true,
  84828. configurable: true
  84829. });
  84830. Object.defineProperty(Bone.prototype, "rotation", {
  84831. /** Gets or sets current rotation (in local space) */
  84832. get: function () {
  84833. return this.getRotation();
  84834. },
  84835. set: function (newRotation) {
  84836. this.setRotation(newRotation);
  84837. },
  84838. enumerable: true,
  84839. configurable: true
  84840. });
  84841. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84842. /** Gets or sets current rotation quaternion (in local space) */
  84843. get: function () {
  84844. this._decompose();
  84845. return this._localRotation;
  84846. },
  84847. set: function (newRotation) {
  84848. this.setRotationQuaternion(newRotation);
  84849. },
  84850. enumerable: true,
  84851. configurable: true
  84852. });
  84853. Object.defineProperty(Bone.prototype, "scaling", {
  84854. /** Gets or sets current scaling (in local space) */
  84855. get: function () {
  84856. return this.getScale();
  84857. },
  84858. set: function (newScaling) {
  84859. this.setScale(newScaling);
  84860. },
  84861. enumerable: true,
  84862. configurable: true
  84863. });
  84864. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84865. /**
  84866. * Gets the animation properties override
  84867. */
  84868. get: function () {
  84869. return this._skeleton.animationPropertiesOverride;
  84870. },
  84871. enumerable: true,
  84872. configurable: true
  84873. });
  84874. // Methods
  84875. Bone.prototype._decompose = function () {
  84876. if (!this._needToDecompose) {
  84877. return;
  84878. }
  84879. this._needToDecompose = false;
  84880. if (!this._localScaling) {
  84881. this._localScaling = BABYLON.Vector3.Zero();
  84882. this._localRotation = BABYLON.Quaternion.Zero();
  84883. this._localPosition = BABYLON.Vector3.Zero();
  84884. }
  84885. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84886. };
  84887. Bone.prototype._compose = function () {
  84888. if (!this._needToCompose) {
  84889. return;
  84890. }
  84891. this._needToCompose = false;
  84892. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84893. };
  84894. /**
  84895. * Update the base and local matrices
  84896. * @param matrix defines the new base or local matrix
  84897. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84898. * @param updateLocalMatrix defines if the local matrix should be updated
  84899. */
  84900. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84901. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84902. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84903. this._baseMatrix.copyFrom(matrix);
  84904. if (updateDifferenceMatrix) {
  84905. this._updateDifferenceMatrix();
  84906. }
  84907. if (updateLocalMatrix) {
  84908. this._localMatrix.copyFrom(matrix);
  84909. this._markAsDirtyAndDecompose();
  84910. }
  84911. else {
  84912. this.markAsDirty();
  84913. }
  84914. };
  84915. /** @hidden */
  84916. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84917. if (updateChildren === void 0) { updateChildren = true; }
  84918. if (!rootMatrix) {
  84919. rootMatrix = this._baseMatrix;
  84920. }
  84921. if (this._parent) {
  84922. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84923. }
  84924. else {
  84925. this._absoluteTransform.copyFrom(rootMatrix);
  84926. }
  84927. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84928. if (updateChildren) {
  84929. for (var index = 0; index < this.children.length; index++) {
  84930. this.children[index]._updateDifferenceMatrix();
  84931. }
  84932. }
  84933. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84934. };
  84935. /**
  84936. * Flag the bone as dirty (Forcing it to update everything)
  84937. */
  84938. Bone.prototype.markAsDirty = function () {
  84939. this._currentRenderId++;
  84940. this._childRenderId++;
  84941. this._skeleton._markAsDirty();
  84942. };
  84943. Bone.prototype._markAsDirtyAndCompose = function () {
  84944. this.markAsDirty();
  84945. this._needToCompose = true;
  84946. };
  84947. Bone.prototype._markAsDirtyAndDecompose = function () {
  84948. this.markAsDirty();
  84949. this._needToDecompose = true;
  84950. };
  84951. /**
  84952. * Copy an animation range from another bone
  84953. * @param source defines the source bone
  84954. * @param rangeName defines the range name to copy
  84955. * @param frameOffset defines the frame offset
  84956. * @param rescaleAsRequired defines if rescaling must be applied if required
  84957. * @param skelDimensionsRatio defines the scaling ratio
  84958. * @returns true if operation was successful
  84959. */
  84960. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84961. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84962. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84963. // all animation may be coming from a library skeleton, so may need to create animation
  84964. if (this.animations.length === 0) {
  84965. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84966. this.animations[0].setKeys([]);
  84967. }
  84968. // get animation info / verify there is such a range from the source bone
  84969. var sourceRange = source.animations[0].getRange(rangeName);
  84970. if (!sourceRange) {
  84971. return false;
  84972. }
  84973. var from = sourceRange.from;
  84974. var to = sourceRange.to;
  84975. var sourceKeys = source.animations[0].getKeys();
  84976. // rescaling prep
  84977. var sourceBoneLength = source.length;
  84978. var sourceParent = source.getParent();
  84979. var parent = this.getParent();
  84980. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84981. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84982. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84983. var destKeys = this.animations[0].getKeys();
  84984. // loop vars declaration
  84985. var orig;
  84986. var origTranslation;
  84987. var mat;
  84988. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84989. orig = sourceKeys[key];
  84990. if (orig.frame >= from && orig.frame <= to) {
  84991. if (rescaleAsRequired) {
  84992. mat = orig.value.clone();
  84993. // scale based on parent ratio, when bone has parent
  84994. if (parentScalingReqd) {
  84995. origTranslation = mat.getTranslation();
  84996. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84997. // scale based on skeleton dimension ratio when root bone, and value is passed
  84998. }
  84999. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  85000. origTranslation = mat.getTranslation();
  85001. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  85002. // use original when root bone, and no data for skelDimensionsRatio
  85003. }
  85004. else {
  85005. mat = orig.value;
  85006. }
  85007. }
  85008. else {
  85009. mat = orig.value;
  85010. }
  85011. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  85012. }
  85013. }
  85014. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  85015. return true;
  85016. };
  85017. /**
  85018. * Translate the bone in local or world space
  85019. * @param vec The amount to translate the bone
  85020. * @param space The space that the translation is in
  85021. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85022. */
  85023. Bone.prototype.translate = function (vec, space, mesh) {
  85024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85025. var lm = this.getLocalMatrix();
  85026. if (space == BABYLON.Space.LOCAL) {
  85027. lm.m[12] += vec.x;
  85028. lm.m[13] += vec.y;
  85029. lm.m[14] += vec.z;
  85030. }
  85031. else {
  85032. var wm = null;
  85033. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85034. if (mesh) {
  85035. wm = mesh.getWorldMatrix();
  85036. }
  85037. this._skeleton.computeAbsoluteTransforms();
  85038. var tmat = Bone._tmpMats[0];
  85039. var tvec = Bone._tmpVecs[0];
  85040. if (this._parent) {
  85041. if (mesh && wm) {
  85042. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85043. tmat.multiplyToRef(wm, tmat);
  85044. }
  85045. else {
  85046. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85047. }
  85048. }
  85049. tmat.m[12] = 0;
  85050. tmat.m[13] = 0;
  85051. tmat.m[14] = 0;
  85052. tmat.invert();
  85053. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  85054. lm.m[12] += tvec.x;
  85055. lm.m[13] += tvec.y;
  85056. lm.m[14] += tvec.z;
  85057. }
  85058. this._markAsDirtyAndDecompose();
  85059. };
  85060. /**
  85061. * Set the postion of the bone in local or world space
  85062. * @param position The position to set the bone
  85063. * @param space The space that the position is in
  85064. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85065. */
  85066. Bone.prototype.setPosition = function (position, space, mesh) {
  85067. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85068. var lm = this.getLocalMatrix();
  85069. if (space == BABYLON.Space.LOCAL) {
  85070. lm.m[12] = position.x;
  85071. lm.m[13] = position.y;
  85072. lm.m[14] = position.z;
  85073. }
  85074. else {
  85075. var wm = null;
  85076. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85077. if (mesh) {
  85078. wm = mesh.getWorldMatrix();
  85079. }
  85080. this._skeleton.computeAbsoluteTransforms();
  85081. var tmat = Bone._tmpMats[0];
  85082. var vec = Bone._tmpVecs[0];
  85083. if (this._parent) {
  85084. if (mesh && wm) {
  85085. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85086. tmat.multiplyToRef(wm, tmat);
  85087. }
  85088. else {
  85089. tmat.copyFrom(this._parent.getAbsoluteTransform());
  85090. }
  85091. }
  85092. tmat.invert();
  85093. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  85094. lm.m[12] = vec.x;
  85095. lm.m[13] = vec.y;
  85096. lm.m[14] = vec.z;
  85097. }
  85098. this._markAsDirtyAndDecompose();
  85099. };
  85100. /**
  85101. * Set the absolute position of the bone (world space)
  85102. * @param position The position to set the bone
  85103. * @param mesh The mesh that this bone is attached to
  85104. */
  85105. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  85106. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  85107. };
  85108. /**
  85109. * Scale the bone on the x, y and z axes (in local space)
  85110. * @param x The amount to scale the bone on the x axis
  85111. * @param y The amount to scale the bone on the y axis
  85112. * @param z The amount to scale the bone on the z axis
  85113. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  85114. */
  85115. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  85116. if (scaleChildren === void 0) { scaleChildren = false; }
  85117. var locMat = this.getLocalMatrix();
  85118. // Apply new scaling on top of current local matrix
  85119. var scaleMat = Bone._tmpMats[0];
  85120. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  85121. scaleMat.multiplyToRef(locMat, locMat);
  85122. // Invert scaling matrix and apply the inverse to all children
  85123. scaleMat.invert();
  85124. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  85125. var child = _a[_i];
  85126. var cm = child.getLocalMatrix();
  85127. cm.multiplyToRef(scaleMat, cm);
  85128. cm.m[12] *= x;
  85129. cm.m[13] *= y;
  85130. cm.m[14] *= z;
  85131. child._markAsDirtyAndDecompose();
  85132. }
  85133. this._markAsDirtyAndDecompose();
  85134. if (scaleChildren) {
  85135. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  85136. var child = _c[_b];
  85137. child.scale(x, y, z, scaleChildren);
  85138. }
  85139. }
  85140. };
  85141. /**
  85142. * Set the bone scaling in local space
  85143. * @param scale defines the scaling vector
  85144. */
  85145. Bone.prototype.setScale = function (scale) {
  85146. this._decompose();
  85147. this._localScaling.copyFrom(scale);
  85148. this._markAsDirtyAndCompose();
  85149. };
  85150. /**
  85151. * Gets the current scaling in local space
  85152. * @returns the current scaling vector
  85153. */
  85154. Bone.prototype.getScale = function () {
  85155. this._decompose();
  85156. return this._localScaling;
  85157. };
  85158. /**
  85159. * Gets the current scaling in local space and stores it in a target vector
  85160. * @param result defines the target vector
  85161. */
  85162. Bone.prototype.getScaleToRef = function (result) {
  85163. this._decompose();
  85164. result.copyFrom(this._localScaling);
  85165. };
  85166. /**
  85167. * Set the yaw, pitch, and roll of the bone in local or world space
  85168. * @param yaw The rotation of the bone on the y axis
  85169. * @param pitch The rotation of the bone on the x axis
  85170. * @param roll The rotation of the bone on the z axis
  85171. * @param space The space that the axes of rotation are in
  85172. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85173. */
  85174. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  85175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85176. if (space === BABYLON.Space.LOCAL) {
  85177. var quat = Bone._tmpQuat;
  85178. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  85179. this.setRotationQuaternion(quat, space, mesh);
  85180. return;
  85181. }
  85182. var rotMatInv = Bone._tmpMats[0];
  85183. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85184. return;
  85185. }
  85186. var rotMat = Bone._tmpMats[1];
  85187. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  85188. rotMatInv.multiplyToRef(rotMat, rotMat);
  85189. this._rotateWithMatrix(rotMat, space, mesh);
  85190. };
  85191. /**
  85192. * Add a rotation to the bone on an axis in local or world space
  85193. * @param axis The axis to rotate the bone on
  85194. * @param amount The amount to rotate the bone
  85195. * @param space The space that the axis is in
  85196. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85197. */
  85198. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  85199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85200. var rmat = Bone._tmpMats[0];
  85201. rmat.m[12] = 0;
  85202. rmat.m[13] = 0;
  85203. rmat.m[14] = 0;
  85204. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  85205. this._rotateWithMatrix(rmat, space, mesh);
  85206. };
  85207. /**
  85208. * Set the rotation of the bone to a particular axis angle in local or world space
  85209. * @param axis The axis to rotate the bone on
  85210. * @param angle The angle that the bone should be rotated to
  85211. * @param space The space that the axis is in
  85212. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85213. */
  85214. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  85215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85216. if (space === BABYLON.Space.LOCAL) {
  85217. var quat = Bone._tmpQuat;
  85218. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  85219. this.setRotationQuaternion(quat, space, mesh);
  85220. return;
  85221. }
  85222. var rotMatInv = Bone._tmpMats[0];
  85223. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85224. return;
  85225. }
  85226. var rotMat = Bone._tmpMats[1];
  85227. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  85228. rotMatInv.multiplyToRef(rotMat, rotMat);
  85229. this._rotateWithMatrix(rotMat, space, mesh);
  85230. };
  85231. /**
  85232. * Set the euler rotation of the bone in local of world space
  85233. * @param rotation The euler rotation that the bone should be set to
  85234. * @param space The space that the rotation is in
  85235. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85236. */
  85237. Bone.prototype.setRotation = function (rotation, space, mesh) {
  85238. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85239. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  85240. };
  85241. /**
  85242. * Set the quaternion rotation of the bone in local of world space
  85243. * @param quat The quaternion rotation that the bone should be set to
  85244. * @param space The space that the rotation is in
  85245. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85246. */
  85247. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  85248. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85249. if (space === BABYLON.Space.LOCAL) {
  85250. this._decompose();
  85251. this._localRotation.copyFrom(quat);
  85252. this._markAsDirtyAndCompose();
  85253. return;
  85254. }
  85255. var rotMatInv = Bone._tmpMats[0];
  85256. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85257. return;
  85258. }
  85259. var rotMat = Bone._tmpMats[1];
  85260. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  85261. rotMatInv.multiplyToRef(rotMat, rotMat);
  85262. this._rotateWithMatrix(rotMat, space, mesh);
  85263. };
  85264. /**
  85265. * Set the rotation matrix of the bone in local of world space
  85266. * @param rotMat The rotation matrix that the bone should be set to
  85267. * @param space The space that the rotation is in
  85268. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85269. */
  85270. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  85271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85272. if (space === BABYLON.Space.LOCAL) {
  85273. var quat = Bone._tmpQuat;
  85274. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  85275. this.setRotationQuaternion(quat, space, mesh);
  85276. return;
  85277. }
  85278. var rotMatInv = Bone._tmpMats[0];
  85279. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  85280. return;
  85281. }
  85282. var rotMat2 = Bone._tmpMats[1];
  85283. rotMat2.copyFrom(rotMat);
  85284. rotMatInv.multiplyToRef(rotMat, rotMat2);
  85285. this._rotateWithMatrix(rotMat2, space, mesh);
  85286. };
  85287. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  85288. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85289. var lmat = this.getLocalMatrix();
  85290. var lx = lmat.m[12];
  85291. var ly = lmat.m[13];
  85292. var lz = lmat.m[14];
  85293. var parent = this.getParent();
  85294. var parentScale = Bone._tmpMats[3];
  85295. var parentScaleInv = Bone._tmpMats[4];
  85296. if (parent && space == BABYLON.Space.WORLD) {
  85297. if (mesh) {
  85298. parentScale.copyFrom(mesh.getWorldMatrix());
  85299. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  85300. }
  85301. else {
  85302. parentScale.copyFrom(parent.getAbsoluteTransform());
  85303. }
  85304. parentScaleInv.copyFrom(parentScale);
  85305. parentScaleInv.invert();
  85306. lmat.multiplyToRef(parentScale, lmat);
  85307. lmat.multiplyToRef(rmat, lmat);
  85308. lmat.multiplyToRef(parentScaleInv, lmat);
  85309. }
  85310. else {
  85311. if (space == BABYLON.Space.WORLD && mesh) {
  85312. parentScale.copyFrom(mesh.getWorldMatrix());
  85313. parentScaleInv.copyFrom(parentScale);
  85314. parentScaleInv.invert();
  85315. lmat.multiplyToRef(parentScale, lmat);
  85316. lmat.multiplyToRef(rmat, lmat);
  85317. lmat.multiplyToRef(parentScaleInv, lmat);
  85318. }
  85319. else {
  85320. lmat.multiplyToRef(rmat, lmat);
  85321. }
  85322. }
  85323. lmat.m[12] = lx;
  85324. lmat.m[13] = ly;
  85325. lmat.m[14] = lz;
  85326. this.computeAbsoluteTransforms();
  85327. this._markAsDirtyAndDecompose();
  85328. };
  85329. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  85330. var scaleMatrix = Bone._tmpMats[2];
  85331. rotMatInv.copyFrom(this.getAbsoluteTransform());
  85332. if (mesh) {
  85333. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  85334. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  85335. }
  85336. rotMatInv.invert();
  85337. if (isNaN(rotMatInv.m[0])) {
  85338. // Matrix failed to invert.
  85339. // This can happen if scale is zero for example.
  85340. return false;
  85341. }
  85342. scaleMatrix.m[0] *= this._scalingDeterminant;
  85343. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  85344. return true;
  85345. };
  85346. /**
  85347. * Get the position of the bone in local or world space
  85348. * @param space The space that the returned position is in
  85349. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85350. * @returns The position of the bone
  85351. */
  85352. Bone.prototype.getPosition = function (space, mesh) {
  85353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85354. if (mesh === void 0) { mesh = null; }
  85355. var pos = BABYLON.Vector3.Zero();
  85356. this.getPositionToRef(space, mesh, pos);
  85357. return pos;
  85358. };
  85359. /**
  85360. * Copy the position of the bone to a vector3 in local or world space
  85361. * @param space The space that the returned position is in
  85362. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85363. * @param result The vector3 to copy the position to
  85364. */
  85365. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  85366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85367. if (space == BABYLON.Space.LOCAL) {
  85368. var lm = this.getLocalMatrix();
  85369. result.x = lm.m[12];
  85370. result.y = lm.m[13];
  85371. result.z = lm.m[14];
  85372. }
  85373. else {
  85374. var wm = null;
  85375. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85376. if (mesh) {
  85377. wm = mesh.getWorldMatrix();
  85378. }
  85379. this._skeleton.computeAbsoluteTransforms();
  85380. var tmat = Bone._tmpMats[0];
  85381. if (mesh && wm) {
  85382. tmat.copyFrom(this.getAbsoluteTransform());
  85383. tmat.multiplyToRef(wm, tmat);
  85384. }
  85385. else {
  85386. tmat = this.getAbsoluteTransform();
  85387. }
  85388. result.x = tmat.m[12];
  85389. result.y = tmat.m[13];
  85390. result.z = tmat.m[14];
  85391. }
  85392. };
  85393. /**
  85394. * Get the absolute position of the bone (world space)
  85395. * @param mesh The mesh that this bone is attached to
  85396. * @returns The absolute position of the bone
  85397. */
  85398. Bone.prototype.getAbsolutePosition = function (mesh) {
  85399. if (mesh === void 0) { mesh = null; }
  85400. var pos = BABYLON.Vector3.Zero();
  85401. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  85402. return pos;
  85403. };
  85404. /**
  85405. * Copy the absolute position of the bone (world space) to the result param
  85406. * @param mesh The mesh that this bone is attached to
  85407. * @param result The vector3 to copy the absolute position to
  85408. */
  85409. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  85410. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  85411. };
  85412. /**
  85413. * Compute the absolute transforms of this bone and its children
  85414. */
  85415. Bone.prototype.computeAbsoluteTransforms = function () {
  85416. this._compose();
  85417. if (this._parent) {
  85418. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  85419. }
  85420. else {
  85421. this._absoluteTransform.copyFrom(this._localMatrix);
  85422. var poseMatrix = this._skeleton.getPoseMatrix();
  85423. if (poseMatrix) {
  85424. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  85425. }
  85426. }
  85427. var children = this.children;
  85428. var len = children.length;
  85429. for (var i = 0; i < len; i++) {
  85430. children[i].computeAbsoluteTransforms();
  85431. }
  85432. };
  85433. /**
  85434. * Get the world direction from an axis that is in the local space of the bone
  85435. * @param localAxis The local direction that is used to compute the world direction
  85436. * @param mesh The mesh that this bone is attached to
  85437. * @returns The world direction
  85438. */
  85439. Bone.prototype.getDirection = function (localAxis, mesh) {
  85440. if (mesh === void 0) { mesh = null; }
  85441. var result = BABYLON.Vector3.Zero();
  85442. this.getDirectionToRef(localAxis, mesh, result);
  85443. return result;
  85444. };
  85445. /**
  85446. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  85447. * @param localAxis The local direction that is used to compute the world direction
  85448. * @param mesh The mesh that this bone is attached to
  85449. * @param result The vector3 that the world direction will be copied to
  85450. */
  85451. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  85452. if (mesh === void 0) { mesh = null; }
  85453. var wm = null;
  85454. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85455. if (mesh) {
  85456. wm = mesh.getWorldMatrix();
  85457. }
  85458. this._skeleton.computeAbsoluteTransforms();
  85459. var mat = Bone._tmpMats[0];
  85460. mat.copyFrom(this.getAbsoluteTransform());
  85461. if (mesh && wm) {
  85462. mat.multiplyToRef(wm, mat);
  85463. }
  85464. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  85465. result.normalize();
  85466. };
  85467. /**
  85468. * Get the euler rotation of the bone in local or world space
  85469. * @param space The space that the rotation should be in
  85470. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85471. * @returns The euler rotation
  85472. */
  85473. Bone.prototype.getRotation = function (space, mesh) {
  85474. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85475. if (mesh === void 0) { mesh = null; }
  85476. var result = BABYLON.Vector3.Zero();
  85477. this.getRotationToRef(space, mesh, result);
  85478. return result;
  85479. };
  85480. /**
  85481. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  85482. * @param space The space that the rotation should be in
  85483. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85484. * @param result The vector3 that the rotation should be copied to
  85485. */
  85486. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  85487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85488. if (mesh === void 0) { mesh = null; }
  85489. var quat = Bone._tmpQuat;
  85490. this.getRotationQuaternionToRef(space, mesh, quat);
  85491. quat.toEulerAnglesToRef(result);
  85492. };
  85493. /**
  85494. * Get the quaternion rotation of the bone in either local or world space
  85495. * @param space The space that the rotation should be in
  85496. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85497. * @returns The quaternion rotation
  85498. */
  85499. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  85500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85501. if (mesh === void 0) { mesh = null; }
  85502. var result = BABYLON.Quaternion.Identity();
  85503. this.getRotationQuaternionToRef(space, mesh, result);
  85504. return result;
  85505. };
  85506. /**
  85507. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  85508. * @param space The space that the rotation should be in
  85509. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85510. * @param result The quaternion that the rotation should be copied to
  85511. */
  85512. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  85513. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85514. if (mesh === void 0) { mesh = null; }
  85515. if (space == BABYLON.Space.LOCAL) {
  85516. this._decompose();
  85517. result.copyFrom(this._localRotation);
  85518. }
  85519. else {
  85520. var mat = Bone._tmpMats[0];
  85521. var amat = this.getAbsoluteTransform();
  85522. if (mesh) {
  85523. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85524. }
  85525. else {
  85526. mat.copyFrom(amat);
  85527. }
  85528. mat.m[0] *= this._scalingDeterminant;
  85529. mat.m[1] *= this._scalingDeterminant;
  85530. mat.m[2] *= this._scalingDeterminant;
  85531. mat.decompose(undefined, result, undefined);
  85532. }
  85533. };
  85534. /**
  85535. * Get the rotation matrix of the bone in local or world space
  85536. * @param space The space that the rotation should be in
  85537. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85538. * @returns The rotation matrix
  85539. */
  85540. Bone.prototype.getRotationMatrix = function (space, mesh) {
  85541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85542. var result = BABYLON.Matrix.Identity();
  85543. this.getRotationMatrixToRef(space, mesh, result);
  85544. return result;
  85545. };
  85546. /**
  85547. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85548. * @param space The space that the rotation should be in
  85549. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85550. * @param result The quaternion that the rotation should be copied to
  85551. */
  85552. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85553. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85554. if (space == BABYLON.Space.LOCAL) {
  85555. this.getLocalMatrix().getRotationMatrixToRef(result);
  85556. }
  85557. else {
  85558. var mat = Bone._tmpMats[0];
  85559. var amat = this.getAbsoluteTransform();
  85560. if (mesh) {
  85561. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85562. }
  85563. else {
  85564. mat.copyFrom(amat);
  85565. }
  85566. mat.m[0] *= this._scalingDeterminant;
  85567. mat.m[1] *= this._scalingDeterminant;
  85568. mat.m[2] *= this._scalingDeterminant;
  85569. mat.getRotationMatrixToRef(result);
  85570. }
  85571. };
  85572. /**
  85573. * Get the world position of a point that is in the local space of the bone
  85574. * @param position The local position
  85575. * @param mesh The mesh that this bone is attached to
  85576. * @returns The world position
  85577. */
  85578. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85579. if (mesh === void 0) { mesh = null; }
  85580. var result = BABYLON.Vector3.Zero();
  85581. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85582. return result;
  85583. };
  85584. /**
  85585. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85586. * @param position The local position
  85587. * @param mesh The mesh that this bone is attached to
  85588. * @param result The vector3 that the world position should be copied to
  85589. */
  85590. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85591. if (mesh === void 0) { mesh = null; }
  85592. var wm = null;
  85593. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85594. if (mesh) {
  85595. wm = mesh.getWorldMatrix();
  85596. }
  85597. this._skeleton.computeAbsoluteTransforms();
  85598. var tmat = Bone._tmpMats[0];
  85599. if (mesh && wm) {
  85600. tmat.copyFrom(this.getAbsoluteTransform());
  85601. tmat.multiplyToRef(wm, tmat);
  85602. }
  85603. else {
  85604. tmat = this.getAbsoluteTransform();
  85605. }
  85606. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85607. };
  85608. /**
  85609. * Get the local position of a point that is in world space
  85610. * @param position The world position
  85611. * @param mesh The mesh that this bone is attached to
  85612. * @returns The local position
  85613. */
  85614. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85615. if (mesh === void 0) { mesh = null; }
  85616. var result = BABYLON.Vector3.Zero();
  85617. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85618. return result;
  85619. };
  85620. /**
  85621. * Get the local position of a point that is in world space and copy it to the result param
  85622. * @param position The world position
  85623. * @param mesh The mesh that this bone is attached to
  85624. * @param result The vector3 that the local position should be copied to
  85625. */
  85626. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85627. if (mesh === void 0) { mesh = null; }
  85628. var wm = null;
  85629. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85630. if (mesh) {
  85631. wm = mesh.getWorldMatrix();
  85632. }
  85633. this._skeleton.computeAbsoluteTransforms();
  85634. var tmat = Bone._tmpMats[0];
  85635. tmat.copyFrom(this.getAbsoluteTransform());
  85636. if (mesh && wm) {
  85637. tmat.multiplyToRef(wm, tmat);
  85638. }
  85639. tmat.invert();
  85640. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85641. };
  85642. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85643. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85644. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85645. return Bone;
  85646. }(BABYLON.Node));
  85647. BABYLON.Bone = Bone;
  85648. })(BABYLON || (BABYLON = {}));
  85649. //# sourceMappingURL=babylon.bone.js.map
  85650. var BABYLON;
  85651. (function (BABYLON) {
  85652. /**
  85653. * Class used to apply inverse kinematics to bones
  85654. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85655. */
  85656. var BoneIKController = /** @class */ (function () {
  85657. /**
  85658. * Creates a new BoneIKController
  85659. * @param mesh defines the mesh to control
  85660. * @param bone defines the bone to control
  85661. * @param options defines options to set up the controller
  85662. */
  85663. function BoneIKController(mesh, bone, options) {
  85664. /**
  85665. * Gets or sets the target position
  85666. */
  85667. this.targetPosition = BABYLON.Vector3.Zero();
  85668. /**
  85669. * Gets or sets the pole target position
  85670. */
  85671. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85672. /**
  85673. * Gets or sets the pole target local offset
  85674. */
  85675. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85676. /**
  85677. * Gets or sets the pole angle
  85678. */
  85679. this.poleAngle = 0;
  85680. /**
  85681. * 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)
  85682. */
  85683. this.slerpAmount = 1;
  85684. this._bone1Quat = BABYLON.Quaternion.Identity();
  85685. this._bone1Mat = BABYLON.Matrix.Identity();
  85686. this._bone2Ang = Math.PI;
  85687. this._maxAngle = Math.PI;
  85688. this._rightHandedSystem = false;
  85689. this._bendAxis = BABYLON.Vector3.Right();
  85690. this._slerping = false;
  85691. this._adjustRoll = 0;
  85692. this._bone2 = bone;
  85693. this._bone1 = bone.getParent();
  85694. if (!this._bone1) {
  85695. return;
  85696. }
  85697. this.mesh = mesh;
  85698. var bonePos = bone.getPosition();
  85699. if (bone.getAbsoluteTransform().determinant() > 0) {
  85700. this._rightHandedSystem = true;
  85701. this._bendAxis.x = 0;
  85702. this._bendAxis.y = 0;
  85703. this._bendAxis.z = -1;
  85704. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85705. this._adjustRoll = Math.PI * .5;
  85706. this._bendAxis.z = 1;
  85707. }
  85708. }
  85709. if (this._bone1.length) {
  85710. var boneScale1 = this._bone1.getScale();
  85711. var boneScale2 = this._bone2.getScale();
  85712. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85713. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85714. }
  85715. else if (this._bone1.children[0]) {
  85716. mesh.computeWorldMatrix(true);
  85717. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85718. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85719. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85720. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85721. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85722. }
  85723. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85724. this.maxAngle = Math.PI;
  85725. if (options) {
  85726. if (options.targetMesh) {
  85727. this.targetMesh = options.targetMesh;
  85728. this.targetMesh.computeWorldMatrix(true);
  85729. }
  85730. if (options.poleTargetMesh) {
  85731. this.poleTargetMesh = options.poleTargetMesh;
  85732. this.poleTargetMesh.computeWorldMatrix(true);
  85733. }
  85734. else if (options.poleTargetBone) {
  85735. this.poleTargetBone = options.poleTargetBone;
  85736. }
  85737. else if (this._bone1.getParent()) {
  85738. this.poleTargetBone = this._bone1.getParent();
  85739. }
  85740. if (options.poleTargetLocalOffset) {
  85741. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85742. }
  85743. if (options.poleAngle) {
  85744. this.poleAngle = options.poleAngle;
  85745. }
  85746. if (options.bendAxis) {
  85747. this._bendAxis.copyFrom(options.bendAxis);
  85748. }
  85749. if (options.maxAngle) {
  85750. this.maxAngle = options.maxAngle;
  85751. }
  85752. if (options.slerpAmount) {
  85753. this.slerpAmount = options.slerpAmount;
  85754. }
  85755. }
  85756. }
  85757. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85758. /**
  85759. * Gets or sets maximum allowed angle
  85760. */
  85761. get: function () {
  85762. return this._maxAngle;
  85763. },
  85764. set: function (value) {
  85765. this._setMaxAngle(value);
  85766. },
  85767. enumerable: true,
  85768. configurable: true
  85769. });
  85770. BoneIKController.prototype._setMaxAngle = function (ang) {
  85771. if (ang < 0) {
  85772. ang = 0;
  85773. }
  85774. if (ang > Math.PI || ang == undefined) {
  85775. ang = Math.PI;
  85776. }
  85777. this._maxAngle = ang;
  85778. var a = this._bone1Length;
  85779. var b = this._bone2Length;
  85780. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85781. };
  85782. /**
  85783. * Force the controller to update the bones
  85784. */
  85785. BoneIKController.prototype.update = function () {
  85786. var bone1 = this._bone1;
  85787. if (!bone1) {
  85788. return;
  85789. }
  85790. var target = this.targetPosition;
  85791. var poleTarget = this.poleTargetPosition;
  85792. var mat1 = BoneIKController._tmpMats[0];
  85793. var mat2 = BoneIKController._tmpMats[1];
  85794. if (this.targetMesh) {
  85795. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85796. }
  85797. if (this.poleTargetBone) {
  85798. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85799. }
  85800. else if (this.poleTargetMesh) {
  85801. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85802. }
  85803. var bonePos = BoneIKController._tmpVecs[0];
  85804. var zaxis = BoneIKController._tmpVecs[1];
  85805. var xaxis = BoneIKController._tmpVecs[2];
  85806. var yaxis = BoneIKController._tmpVecs[3];
  85807. var upAxis = BoneIKController._tmpVecs[4];
  85808. var _tmpQuat = BoneIKController._tmpQuat;
  85809. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85810. poleTarget.subtractToRef(bonePos, upAxis);
  85811. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85812. upAxis.y = 1;
  85813. }
  85814. else {
  85815. upAxis.normalize();
  85816. }
  85817. target.subtractToRef(bonePos, yaxis);
  85818. yaxis.normalize();
  85819. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85820. zaxis.normalize();
  85821. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85822. xaxis.normalize();
  85823. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85824. var a = this._bone1Length;
  85825. var b = this._bone2Length;
  85826. var c = BABYLON.Vector3.Distance(bonePos, target);
  85827. if (this._maxReach > 0) {
  85828. c = Math.min(this._maxReach, c);
  85829. }
  85830. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85831. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85832. if (acosa > 1) {
  85833. acosa = 1;
  85834. }
  85835. if (acosb > 1) {
  85836. acosb = 1;
  85837. }
  85838. if (acosa < -1) {
  85839. acosa = -1;
  85840. }
  85841. if (acosb < -1) {
  85842. acosb = -1;
  85843. }
  85844. var angA = Math.acos(acosa);
  85845. var angB = Math.acos(acosb);
  85846. var angC = -angA - angB;
  85847. if (this._rightHandedSystem) {
  85848. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85849. mat2.multiplyToRef(mat1, mat1);
  85850. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85851. mat2.multiplyToRef(mat1, mat1);
  85852. }
  85853. else {
  85854. var _tmpVec = BoneIKController._tmpVecs[5];
  85855. _tmpVec.copyFrom(this._bendAxis);
  85856. _tmpVec.x *= -1;
  85857. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85858. mat2.multiplyToRef(mat1, mat1);
  85859. }
  85860. if (this.poleAngle) {
  85861. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85862. mat1.multiplyToRef(mat2, mat1);
  85863. }
  85864. if (this._bone1) {
  85865. if (this.slerpAmount < 1) {
  85866. if (!this._slerping) {
  85867. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85868. }
  85869. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85870. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85871. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85872. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85873. this._slerping = true;
  85874. }
  85875. else {
  85876. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85877. this._bone1Mat.copyFrom(mat1);
  85878. this._slerping = false;
  85879. }
  85880. }
  85881. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85882. this._bone2Ang = angC;
  85883. };
  85884. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85885. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85886. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85887. return BoneIKController;
  85888. }());
  85889. BABYLON.BoneIKController = BoneIKController;
  85890. })(BABYLON || (BABYLON = {}));
  85891. //# sourceMappingURL=babylon.boneIKController.js.map
  85892. var BABYLON;
  85893. (function (BABYLON) {
  85894. /**
  85895. * Class used to make a bone look toward a point in space
  85896. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85897. */
  85898. var BoneLookController = /** @class */ (function () {
  85899. /**
  85900. * Create a BoneLookController
  85901. * @param mesh the mesh that the bone belongs to
  85902. * @param bone the bone that will be looking to the target
  85903. * @param target the target Vector3 to look at
  85904. * @param settings optional settings:
  85905. * * maxYaw: the maximum angle the bone will yaw to
  85906. * * minYaw: the minimum angle the bone will yaw to
  85907. * * maxPitch: the maximum angle the bone will pitch to
  85908. * * minPitch: the minimum angle the bone will yaw to
  85909. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85910. * * upAxis: the up axis of the coordinate system
  85911. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85912. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85913. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85914. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85915. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85916. * * adjustRoll: used to make an adjustment to the roll of the bone
  85917. **/
  85918. function BoneLookController(mesh, bone, target, options) {
  85919. /**
  85920. * The up axis of the coordinate system that is used when the bone is rotated
  85921. */
  85922. this.upAxis = BABYLON.Vector3.Up();
  85923. /**
  85924. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85925. */
  85926. this.upAxisSpace = BABYLON.Space.LOCAL;
  85927. /**
  85928. * Used to make an adjustment to the yaw of the bone
  85929. */
  85930. this.adjustYaw = 0;
  85931. /**
  85932. * Used to make an adjustment to the pitch of the bone
  85933. */
  85934. this.adjustPitch = 0;
  85935. /**
  85936. * Used to make an adjustment to the roll of the bone
  85937. */
  85938. this.adjustRoll = 0;
  85939. /**
  85940. * 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)
  85941. */
  85942. this.slerpAmount = 1;
  85943. this._boneQuat = BABYLON.Quaternion.Identity();
  85944. this._slerping = false;
  85945. this._firstFrameSkipped = false;
  85946. this._fowardAxis = BABYLON.Vector3.Forward();
  85947. this.mesh = mesh;
  85948. this.bone = bone;
  85949. this.target = target;
  85950. if (options) {
  85951. if (options.adjustYaw) {
  85952. this.adjustYaw = options.adjustYaw;
  85953. }
  85954. if (options.adjustPitch) {
  85955. this.adjustPitch = options.adjustPitch;
  85956. }
  85957. if (options.adjustRoll) {
  85958. this.adjustRoll = options.adjustRoll;
  85959. }
  85960. if (options.maxYaw != null) {
  85961. this.maxYaw = options.maxYaw;
  85962. }
  85963. else {
  85964. this.maxYaw = Math.PI;
  85965. }
  85966. if (options.minYaw != null) {
  85967. this.minYaw = options.minYaw;
  85968. }
  85969. else {
  85970. this.minYaw = -Math.PI;
  85971. }
  85972. if (options.maxPitch != null) {
  85973. this.maxPitch = options.maxPitch;
  85974. }
  85975. else {
  85976. this.maxPitch = Math.PI;
  85977. }
  85978. if (options.minPitch != null) {
  85979. this.minPitch = options.minPitch;
  85980. }
  85981. else {
  85982. this.minPitch = -Math.PI;
  85983. }
  85984. if (options.slerpAmount != null) {
  85985. this.slerpAmount = options.slerpAmount;
  85986. }
  85987. if (options.upAxis != null) {
  85988. this.upAxis = options.upAxis;
  85989. }
  85990. if (options.upAxisSpace != null) {
  85991. this.upAxisSpace = options.upAxisSpace;
  85992. }
  85993. if (options.yawAxis != null || options.pitchAxis != null) {
  85994. var newYawAxis = BABYLON.Axis.Y;
  85995. var newPitchAxis = BABYLON.Axis.X;
  85996. if (options.yawAxis != null) {
  85997. newYawAxis = options.yawAxis.clone();
  85998. newYawAxis.normalize();
  85999. }
  86000. if (options.pitchAxis != null) {
  86001. newPitchAxis = options.pitchAxis.clone();
  86002. newPitchAxis.normalize();
  86003. }
  86004. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  86005. this._transformYawPitch = BABYLON.Matrix.Identity();
  86006. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  86007. this._transformYawPitchInv = this._transformYawPitch.clone();
  86008. this._transformYawPitch.invert();
  86009. }
  86010. }
  86011. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  86012. this.upAxisSpace = BABYLON.Space.LOCAL;
  86013. }
  86014. }
  86015. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  86016. /**
  86017. * Gets or sets the minimum yaw angle that the bone can look to
  86018. */
  86019. get: function () {
  86020. return this._minYaw;
  86021. },
  86022. set: function (value) {
  86023. this._minYaw = value;
  86024. this._minYawSin = Math.sin(value);
  86025. this._minYawCos = Math.cos(value);
  86026. if (this._maxYaw != null) {
  86027. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  86028. this._yawRange = this._maxYaw - this._minYaw;
  86029. }
  86030. },
  86031. enumerable: true,
  86032. configurable: true
  86033. });
  86034. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  86035. /**
  86036. * Gets or sets the maximum yaw angle that the bone can look to
  86037. */
  86038. get: function () {
  86039. return this._maxYaw;
  86040. },
  86041. set: function (value) {
  86042. this._maxYaw = value;
  86043. this._maxYawSin = Math.sin(value);
  86044. this._maxYawCos = Math.cos(value);
  86045. if (this._minYaw != null) {
  86046. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  86047. this._yawRange = this._maxYaw - this._minYaw;
  86048. }
  86049. },
  86050. enumerable: true,
  86051. configurable: true
  86052. });
  86053. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  86054. /**
  86055. * Gets or sets the minimum pitch angle that the bone can look to
  86056. */
  86057. get: function () {
  86058. return this._minPitch;
  86059. },
  86060. set: function (value) {
  86061. this._minPitch = value;
  86062. this._minPitchTan = Math.tan(value);
  86063. },
  86064. enumerable: true,
  86065. configurable: true
  86066. });
  86067. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  86068. /**
  86069. * Gets or sets the maximum pitch angle that the bone can look to
  86070. */
  86071. get: function () {
  86072. return this._maxPitch;
  86073. },
  86074. set: function (value) {
  86075. this._maxPitch = value;
  86076. this._maxPitchTan = Math.tan(value);
  86077. },
  86078. enumerable: true,
  86079. configurable: true
  86080. });
  86081. /**
  86082. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  86083. */
  86084. BoneLookController.prototype.update = function () {
  86085. //skip the first frame when slerping so that the mesh rotation is correct
  86086. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  86087. this._firstFrameSkipped = true;
  86088. return;
  86089. }
  86090. var bone = this.bone;
  86091. var bonePos = BoneLookController._tmpVecs[0];
  86092. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  86093. var target = this.target;
  86094. var _tmpMat1 = BoneLookController._tmpMats[0];
  86095. var _tmpMat2 = BoneLookController._tmpMats[1];
  86096. var mesh = this.mesh;
  86097. var parentBone = bone.getParent();
  86098. var upAxis = BoneLookController._tmpVecs[1];
  86099. upAxis.copyFrom(this.upAxis);
  86100. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  86101. if (this._transformYawPitch) {
  86102. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  86103. }
  86104. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  86105. }
  86106. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  86107. mesh.getDirectionToRef(upAxis, upAxis);
  86108. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  86109. upAxis.normalize();
  86110. }
  86111. }
  86112. var checkYaw = false;
  86113. var checkPitch = false;
  86114. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  86115. checkYaw = true;
  86116. }
  86117. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  86118. checkPitch = true;
  86119. }
  86120. if (checkYaw || checkPitch) {
  86121. var spaceMat = BoneLookController._tmpMats[2];
  86122. var spaceMatInv = BoneLookController._tmpMats[3];
  86123. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  86124. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  86125. }
  86126. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  86127. spaceMat.copyFrom(mesh.getWorldMatrix());
  86128. }
  86129. else {
  86130. var forwardAxis = BoneLookController._tmpVecs[2];
  86131. forwardAxis.copyFrom(this._fowardAxis);
  86132. if (this._transformYawPitch) {
  86133. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  86134. }
  86135. if (parentBone) {
  86136. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  86137. }
  86138. else {
  86139. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  86140. }
  86141. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  86142. rightAxis.normalize();
  86143. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  86144. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  86145. }
  86146. spaceMat.invertToRef(spaceMatInv);
  86147. var xzlen = null;
  86148. if (checkPitch) {
  86149. var localTarget = BoneLookController._tmpVecs[3];
  86150. target.subtractToRef(bonePos, localTarget);
  86151. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  86152. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86153. var pitch = Math.atan2(localTarget.y, xzlen);
  86154. var newPitch = pitch;
  86155. if (pitch > this._maxPitch) {
  86156. localTarget.y = this._maxPitchTan * xzlen;
  86157. newPitch = this._maxPitch;
  86158. }
  86159. else if (pitch < this._minPitch) {
  86160. localTarget.y = this._minPitchTan * xzlen;
  86161. newPitch = this._minPitch;
  86162. }
  86163. if (pitch != newPitch) {
  86164. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  86165. localTarget.addInPlace(bonePos);
  86166. target = localTarget;
  86167. }
  86168. }
  86169. if (checkYaw) {
  86170. var localTarget = BoneLookController._tmpVecs[4];
  86171. target.subtractToRef(bonePos, localTarget);
  86172. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  86173. var yaw = Math.atan2(localTarget.x, localTarget.z);
  86174. var newYaw = yaw;
  86175. if (yaw > this._maxYaw || yaw < this._minYaw) {
  86176. if (xzlen == null) {
  86177. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86178. }
  86179. if (this._yawRange > Math.PI) {
  86180. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  86181. localTarget.z = this._maxYawCos * xzlen;
  86182. localTarget.x = this._maxYawSin * xzlen;
  86183. newYaw = this._maxYaw;
  86184. }
  86185. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  86186. localTarget.z = this._minYawCos * xzlen;
  86187. localTarget.x = this._minYawSin * xzlen;
  86188. newYaw = this._minYaw;
  86189. }
  86190. }
  86191. else {
  86192. if (yaw > this._maxYaw) {
  86193. localTarget.z = this._maxYawCos * xzlen;
  86194. localTarget.x = this._maxYawSin * xzlen;
  86195. newYaw = this._maxYaw;
  86196. }
  86197. else if (yaw < this._minYaw) {
  86198. localTarget.z = this._minYawCos * xzlen;
  86199. localTarget.x = this._minYawSin * xzlen;
  86200. newYaw = this._minYaw;
  86201. }
  86202. }
  86203. }
  86204. if (this._slerping && this._yawRange > Math.PI) {
  86205. //are we going to be crossing into the min/max region?
  86206. var boneFwd = BoneLookController._tmpVecs[8];
  86207. boneFwd.copyFrom(BABYLON.Axis.Z);
  86208. if (this._transformYawPitch) {
  86209. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  86210. }
  86211. var boneRotMat = BoneLookController._tmpMats[4];
  86212. this._boneQuat.toRotationMatrix(boneRotMat);
  86213. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  86214. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  86215. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  86216. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  86217. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  86218. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  86219. if (angBtwTar > angBtwMidYaw) {
  86220. if (xzlen == null) {
  86221. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  86222. }
  86223. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  86224. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  86225. if (angBtwMin < angBtwMax) {
  86226. newYaw = boneYaw + Math.PI * .75;
  86227. localTarget.z = Math.cos(newYaw) * xzlen;
  86228. localTarget.x = Math.sin(newYaw) * xzlen;
  86229. }
  86230. else {
  86231. newYaw = boneYaw - Math.PI * .75;
  86232. localTarget.z = Math.cos(newYaw) * xzlen;
  86233. localTarget.x = Math.sin(newYaw) * xzlen;
  86234. }
  86235. }
  86236. }
  86237. if (yaw != newYaw) {
  86238. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  86239. localTarget.addInPlace(bonePos);
  86240. target = localTarget;
  86241. }
  86242. }
  86243. }
  86244. var zaxis = BoneLookController._tmpVecs[5];
  86245. var xaxis = BoneLookController._tmpVecs[6];
  86246. var yaxis = BoneLookController._tmpVecs[7];
  86247. var _tmpQuat = BoneLookController._tmpQuat;
  86248. target.subtractToRef(bonePos, zaxis);
  86249. zaxis.normalize();
  86250. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  86251. xaxis.normalize();
  86252. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  86253. yaxis.normalize();
  86254. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  86255. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  86256. return;
  86257. }
  86258. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  86259. return;
  86260. }
  86261. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  86262. return;
  86263. }
  86264. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  86265. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  86266. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  86267. }
  86268. if (this.slerpAmount < 1) {
  86269. if (!this._slerping) {
  86270. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  86271. }
  86272. if (this._transformYawPitch) {
  86273. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  86274. }
  86275. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  86276. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  86277. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  86278. this._slerping = true;
  86279. }
  86280. else {
  86281. if (this._transformYawPitch) {
  86282. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  86283. }
  86284. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  86285. this._slerping = false;
  86286. }
  86287. };
  86288. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  86289. var angDiff = ang2 - ang1;
  86290. angDiff %= Math.PI * 2;
  86291. if (angDiff > Math.PI) {
  86292. angDiff -= Math.PI * 2;
  86293. }
  86294. else if (angDiff < -Math.PI) {
  86295. angDiff += Math.PI * 2;
  86296. }
  86297. return angDiff;
  86298. };
  86299. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  86300. ang1 %= (2 * Math.PI);
  86301. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86302. ang2 %= (2 * Math.PI);
  86303. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86304. var ab = 0;
  86305. if (ang1 < ang2) {
  86306. ab = ang2 - ang1;
  86307. }
  86308. else {
  86309. ab = ang1 - ang2;
  86310. }
  86311. if (ab > Math.PI) {
  86312. ab = Math.PI * 2 - ab;
  86313. }
  86314. return ab;
  86315. };
  86316. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  86317. ang %= (2 * Math.PI);
  86318. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  86319. ang1 %= (2 * Math.PI);
  86320. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86321. ang2 %= (2 * Math.PI);
  86322. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86323. if (ang1 < ang2) {
  86324. if (ang > ang1 && ang < ang2) {
  86325. return true;
  86326. }
  86327. }
  86328. else {
  86329. if (ang > ang2 && ang < ang1) {
  86330. return true;
  86331. }
  86332. }
  86333. return false;
  86334. };
  86335. 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()];
  86336. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  86337. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86338. return BoneLookController;
  86339. }());
  86340. BABYLON.BoneLookController = BoneLookController;
  86341. })(BABYLON || (BABYLON = {}));
  86342. //# sourceMappingURL=babylon.boneLookController.js.map
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. /**
  86346. * Class used to handle skinning animations
  86347. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86348. */
  86349. var Skeleton = /** @class */ (function () {
  86350. /**
  86351. * Creates a new skeleton
  86352. * @param name defines the skeleton name
  86353. * @param id defines the skeleton Id
  86354. * @param scene defines the hosting scene
  86355. */
  86356. function Skeleton(
  86357. /** defines the skeleton name */
  86358. name,
  86359. /** defines the skeleton Id */
  86360. id, scene) {
  86361. this.name = name;
  86362. this.id = id;
  86363. /**
  86364. * Gets the list of child bones
  86365. */
  86366. this.bones = new Array();
  86367. /**
  86368. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  86369. */
  86370. this.needInitialSkinMatrix = false;
  86371. this._isDirty = true;
  86372. this._meshesWithPoseMatrix = new Array();
  86373. this._identity = BABYLON.Matrix.Identity();
  86374. this._ranges = {};
  86375. this._lastAbsoluteTransformsUpdateId = -1;
  86376. /**
  86377. * Specifies if the skeleton should be serialized
  86378. */
  86379. this.doNotSerialize = false;
  86380. this._animationPropertiesOverride = null;
  86381. // Events
  86382. /**
  86383. * An observable triggered before computing the skeleton's matrices
  86384. */
  86385. this.onBeforeComputeObservable = new BABYLON.Observable();
  86386. this.bones = [];
  86387. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86388. scene.skeletons.push(this);
  86389. //make sure it will recalculate the matrix next time prepare is called.
  86390. this._isDirty = true;
  86391. }
  86392. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  86393. /**
  86394. * Gets or sets the animation properties override
  86395. */
  86396. get: function () {
  86397. if (!this._animationPropertiesOverride) {
  86398. return this._scene.animationPropertiesOverride;
  86399. }
  86400. return this._animationPropertiesOverride;
  86401. },
  86402. set: function (value) {
  86403. this._animationPropertiesOverride = value;
  86404. },
  86405. enumerable: true,
  86406. configurable: true
  86407. });
  86408. // Members
  86409. /**
  86410. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  86411. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  86412. * @returns a Float32Array containing matrices data
  86413. */
  86414. Skeleton.prototype.getTransformMatrices = function (mesh) {
  86415. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  86416. return mesh._bonesTransformMatrices;
  86417. }
  86418. if (!this._transformMatrices) {
  86419. this.prepare();
  86420. }
  86421. return this._transformMatrices;
  86422. };
  86423. /**
  86424. * Gets the current hosting scene
  86425. * @returns a scene object
  86426. */
  86427. Skeleton.prototype.getScene = function () {
  86428. return this._scene;
  86429. };
  86430. // Methods
  86431. /**
  86432. * Gets a string representing the current skeleton data
  86433. * @param fullDetails defines a boolean indicating if we want a verbose version
  86434. * @returns a string representing the current skeleton data
  86435. */
  86436. Skeleton.prototype.toString = function (fullDetails) {
  86437. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  86438. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  86439. if (fullDetails) {
  86440. ret += ", Ranges: {";
  86441. var first = true;
  86442. for (var name_1 in this._ranges) {
  86443. if (first) {
  86444. ret += ", ";
  86445. first = false;
  86446. }
  86447. ret += name_1;
  86448. }
  86449. ret += "}";
  86450. }
  86451. return ret;
  86452. };
  86453. /**
  86454. * Get bone's index searching by name
  86455. * @param name defines bone's name to search for
  86456. * @return the indice of the bone. Returns -1 if not found
  86457. */
  86458. Skeleton.prototype.getBoneIndexByName = function (name) {
  86459. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  86460. if (this.bones[boneIndex].name === name) {
  86461. return boneIndex;
  86462. }
  86463. }
  86464. return -1;
  86465. };
  86466. /**
  86467. * Creater a new animation range
  86468. * @param name defines the name of the range
  86469. * @param from defines the start key
  86470. * @param to defines the end key
  86471. */
  86472. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  86473. // check name not already in use
  86474. if (!this._ranges[name]) {
  86475. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  86476. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86477. if (this.bones[i].animations[0]) {
  86478. this.bones[i].animations[0].createRange(name, from, to);
  86479. }
  86480. }
  86481. }
  86482. };
  86483. /**
  86484. * Delete a specific animation range
  86485. * @param name defines the name of the range
  86486. * @param deleteFrames defines if frames must be removed as well
  86487. */
  86488. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  86489. if (deleteFrames === void 0) { deleteFrames = true; }
  86490. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86491. if (this.bones[i].animations[0]) {
  86492. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  86493. }
  86494. }
  86495. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  86496. };
  86497. /**
  86498. * Gets a specific animation range
  86499. * @param name defines the name of the range to look for
  86500. * @returns the requested animation range or null if not found
  86501. */
  86502. Skeleton.prototype.getAnimationRange = function (name) {
  86503. return this._ranges[name];
  86504. };
  86505. /**
  86506. * Gets the list of all animation ranges defined on this skeleton
  86507. * @returns an array
  86508. */
  86509. Skeleton.prototype.getAnimationRanges = function () {
  86510. var animationRanges = [];
  86511. var name;
  86512. var i = 0;
  86513. for (name in this._ranges) {
  86514. animationRanges[i] = this._ranges[name];
  86515. i++;
  86516. }
  86517. return animationRanges;
  86518. };
  86519. /**
  86520. * Copy animation range from a source skeleton.
  86521. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  86522. * @param source defines the source skeleton
  86523. * @param name defines the name of the range to copy
  86524. * @param rescaleAsRequired defines if rescaling must be applied if required
  86525. * @returns true if operation was successful
  86526. */
  86527. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  86528. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86529. if (this._ranges[name] || !source.getAnimationRange(name)) {
  86530. return false;
  86531. }
  86532. var ret = true;
  86533. var frameOffset = this._getHighestAnimationFrame() + 1;
  86534. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  86535. var boneDict = {};
  86536. var sourceBones = source.bones;
  86537. var nBones;
  86538. var i;
  86539. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  86540. boneDict[sourceBones[i].name] = sourceBones[i];
  86541. }
  86542. if (this.bones.length !== sourceBones.length) {
  86543. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  86544. ret = false;
  86545. }
  86546. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  86547. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86548. var boneName = this.bones[i].name;
  86549. var sourceBone = boneDict[boneName];
  86550. if (sourceBone) {
  86551. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86552. }
  86553. else {
  86554. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86555. ret = false;
  86556. }
  86557. }
  86558. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86559. var range = source.getAnimationRange(name);
  86560. if (range) {
  86561. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86562. }
  86563. return ret;
  86564. };
  86565. /**
  86566. * Forces the skeleton to go to rest pose
  86567. */
  86568. Skeleton.prototype.returnToRest = function () {
  86569. for (var index = 0; index < this.bones.length; index++) {
  86570. this.bones[index].returnToRest();
  86571. }
  86572. };
  86573. Skeleton.prototype._getHighestAnimationFrame = function () {
  86574. var ret = 0;
  86575. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86576. if (this.bones[i].animations[0]) {
  86577. var highest = this.bones[i].animations[0].getHighestFrame();
  86578. if (ret < highest) {
  86579. ret = highest;
  86580. }
  86581. }
  86582. }
  86583. return ret;
  86584. };
  86585. /**
  86586. * Begin a specific animation range
  86587. * @param name defines the name of the range to start
  86588. * @param loop defines if looping must be turned on (false by default)
  86589. * @param speedRatio defines the speed ratio to apply (1 by default)
  86590. * @param onAnimationEnd defines a callback which will be called when animation will end
  86591. * @returns a new animatable
  86592. */
  86593. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86594. var range = this.getAnimationRange(name);
  86595. if (!range) {
  86596. return null;
  86597. }
  86598. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86599. };
  86600. /** @hidden */
  86601. Skeleton.prototype._markAsDirty = function () {
  86602. this._isDirty = true;
  86603. };
  86604. /** @hidden */
  86605. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86606. this._meshesWithPoseMatrix.push(mesh);
  86607. };
  86608. /** @hidden */
  86609. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86610. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86611. if (index > -1) {
  86612. this._meshesWithPoseMatrix.splice(index, 1);
  86613. }
  86614. };
  86615. /** @hidden */
  86616. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86617. this.onBeforeComputeObservable.notifyObservers(this);
  86618. for (var index = 0; index < this.bones.length; index++) {
  86619. var bone = this.bones[index];
  86620. var parentBone = bone.getParent();
  86621. if (parentBone) {
  86622. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86623. }
  86624. else {
  86625. if (initialSkinMatrix) {
  86626. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86627. }
  86628. else {
  86629. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86630. }
  86631. }
  86632. if (bone._index !== -1) {
  86633. var mappedIndex = bone._index === null ? index : bone._index;
  86634. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86635. }
  86636. }
  86637. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86638. };
  86639. /**
  86640. * Build all resources required to render a skeleton
  86641. */
  86642. Skeleton.prototype.prepare = function () {
  86643. if (!this._isDirty) {
  86644. return;
  86645. }
  86646. if (this.needInitialSkinMatrix) {
  86647. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86648. var mesh = this._meshesWithPoseMatrix[index];
  86649. var poseMatrix = mesh.getPoseMatrix();
  86650. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86651. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86652. }
  86653. if (this._synchronizedWithMesh !== mesh) {
  86654. this._synchronizedWithMesh = mesh;
  86655. // Prepare bones
  86656. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86657. var bone = this.bones[boneIndex];
  86658. if (!bone.getParent()) {
  86659. var matrix = bone.getBaseMatrix();
  86660. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86661. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86662. }
  86663. }
  86664. }
  86665. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86666. }
  86667. }
  86668. else {
  86669. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86670. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86671. }
  86672. this._computeTransformMatrices(this._transformMatrices, null);
  86673. }
  86674. this._isDirty = false;
  86675. this._scene._activeBones.addCount(this.bones.length, false);
  86676. };
  86677. /**
  86678. * Gets the list of animatables currently running for this skeleton
  86679. * @returns an array of animatables
  86680. */
  86681. Skeleton.prototype.getAnimatables = function () {
  86682. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86683. this._animatables = [];
  86684. for (var index = 0; index < this.bones.length; index++) {
  86685. this._animatables.push(this.bones[index]);
  86686. }
  86687. }
  86688. return this._animatables;
  86689. };
  86690. /**
  86691. * Clone the current skeleton
  86692. * @param name defines the name of the new skeleton
  86693. * @param id defines the id of the enw skeleton
  86694. * @returns the new skeleton
  86695. */
  86696. Skeleton.prototype.clone = function (name, id) {
  86697. var result = new Skeleton(name, id || name, this._scene);
  86698. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86699. for (var index = 0; index < this.bones.length; index++) {
  86700. var source = this.bones[index];
  86701. var parentBone = null;
  86702. var parent_1 = source.getParent();
  86703. if (parent_1) {
  86704. var parentIndex = this.bones.indexOf(parent_1);
  86705. parentBone = result.bones[parentIndex];
  86706. }
  86707. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86708. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86709. }
  86710. if (this._ranges) {
  86711. result._ranges = {};
  86712. for (var rangeName in this._ranges) {
  86713. var range = this._ranges[rangeName];
  86714. if (range) {
  86715. result._ranges[rangeName] = range.clone();
  86716. }
  86717. }
  86718. }
  86719. this._isDirty = true;
  86720. return result;
  86721. };
  86722. /**
  86723. * Enable animation blending for this skeleton
  86724. * @param blendingSpeed defines the blending speed to apply
  86725. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86726. */
  86727. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86728. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86729. this.bones.forEach(function (bone) {
  86730. bone.animations.forEach(function (animation) {
  86731. animation.enableBlending = true;
  86732. animation.blendingSpeed = blendingSpeed;
  86733. });
  86734. });
  86735. };
  86736. /**
  86737. * Releases all resources associated with the current skeleton
  86738. */
  86739. Skeleton.prototype.dispose = function () {
  86740. this._meshesWithPoseMatrix = [];
  86741. // Animations
  86742. this.getScene().stopAnimation(this);
  86743. // Remove from scene
  86744. this.getScene().removeSkeleton(this);
  86745. };
  86746. /**
  86747. * Serialize the skeleton in a JSON object
  86748. * @returns a JSON object
  86749. */
  86750. Skeleton.prototype.serialize = function () {
  86751. var serializationObject = {};
  86752. serializationObject.name = this.name;
  86753. serializationObject.id = this.id;
  86754. if (this.dimensionsAtRest) {
  86755. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86756. }
  86757. serializationObject.bones = [];
  86758. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86759. for (var index = 0; index < this.bones.length; index++) {
  86760. var bone = this.bones[index];
  86761. var parent_2 = bone.getParent();
  86762. var serializedBone = {
  86763. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86764. name: bone.name,
  86765. matrix: bone.getBaseMatrix().toArray(),
  86766. rest: bone.getRestPose().toArray()
  86767. };
  86768. serializationObject.bones.push(serializedBone);
  86769. if (bone.length) {
  86770. serializedBone.length = bone.length;
  86771. }
  86772. if (bone.metadata) {
  86773. serializedBone.metadata = bone.metadata;
  86774. }
  86775. if (bone.animations && bone.animations.length > 0) {
  86776. serializedBone.animation = bone.animations[0].serialize();
  86777. }
  86778. serializationObject.ranges = [];
  86779. for (var name in this._ranges) {
  86780. var source = this._ranges[name];
  86781. if (!source) {
  86782. continue;
  86783. }
  86784. var range = {};
  86785. range.name = name;
  86786. range.from = source.from;
  86787. range.to = source.to;
  86788. serializationObject.ranges.push(range);
  86789. }
  86790. }
  86791. return serializationObject;
  86792. };
  86793. /**
  86794. * Creates a new skeleton from serialized data
  86795. * @param parsedSkeleton defines the serialized data
  86796. * @param scene defines the hosting scene
  86797. * @returns a new skeleton
  86798. */
  86799. Skeleton.Parse = function (parsedSkeleton, scene) {
  86800. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86801. if (parsedSkeleton.dimensionsAtRest) {
  86802. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86803. }
  86804. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86805. var index;
  86806. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86807. var parsedBone = parsedSkeleton.bones[index];
  86808. var parentBone = null;
  86809. if (parsedBone.parentBoneIndex > -1) {
  86810. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86811. }
  86812. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86813. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86814. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86815. bone.id = parsedBone.id;
  86816. }
  86817. if (parsedBone.length) {
  86818. bone.length = parsedBone.length;
  86819. }
  86820. if (parsedBone.metadata) {
  86821. bone.metadata = parsedBone.metadata;
  86822. }
  86823. if (parsedBone.animation) {
  86824. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86825. }
  86826. }
  86827. // placed after bones, so createAnimationRange can cascade down
  86828. if (parsedSkeleton.ranges) {
  86829. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86830. var data = parsedSkeleton.ranges[index];
  86831. skeleton.createAnimationRange(data.name, data.from, data.to);
  86832. }
  86833. }
  86834. return skeleton;
  86835. };
  86836. /**
  86837. * Compute all node absolute transforms
  86838. * @param forceUpdate defines if computation must be done even if cache is up to date
  86839. */
  86840. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86841. if (forceUpdate === void 0) { forceUpdate = false; }
  86842. var renderId = this._scene.getRenderId();
  86843. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86844. this.bones[0].computeAbsoluteTransforms();
  86845. this._lastAbsoluteTransformsUpdateId = renderId;
  86846. }
  86847. };
  86848. /**
  86849. * Gets the root pose matrix
  86850. * @returns a matrix
  86851. */
  86852. Skeleton.prototype.getPoseMatrix = function () {
  86853. var poseMatrix = null;
  86854. if (this._meshesWithPoseMatrix.length > 0) {
  86855. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86856. }
  86857. return poseMatrix;
  86858. };
  86859. /**
  86860. * Sorts bones per internal index
  86861. */
  86862. Skeleton.prototype.sortBones = function () {
  86863. var bones = new Array();
  86864. var visited = new Array(this.bones.length);
  86865. for (var index = 0; index < this.bones.length; index++) {
  86866. this._sortBones(index, bones, visited);
  86867. }
  86868. this.bones = bones;
  86869. };
  86870. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86871. if (visited[index]) {
  86872. return;
  86873. }
  86874. visited[index] = true;
  86875. var bone = this.bones[index];
  86876. if (bone._index === undefined) {
  86877. bone._index = index;
  86878. }
  86879. var parentBone = bone.getParent();
  86880. if (parentBone) {
  86881. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86882. }
  86883. bones.push(bone);
  86884. };
  86885. return Skeleton;
  86886. }());
  86887. BABYLON.Skeleton = Skeleton;
  86888. })(BABYLON || (BABYLON = {}));
  86889. //# sourceMappingURL=babylon.skeleton.js.map
  86890. var BABYLON;
  86891. (function (BABYLON) {
  86892. ;
  86893. /**
  86894. * This groups tools to convert HDR texture to native colors array.
  86895. */
  86896. var HDRTools = /** @class */ (function () {
  86897. function HDRTools() {
  86898. }
  86899. HDRTools.Ldexp = function (mantissa, exponent) {
  86900. if (exponent > 1023) {
  86901. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86902. }
  86903. if (exponent < -1074) {
  86904. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86905. }
  86906. return mantissa * Math.pow(2, exponent);
  86907. };
  86908. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86909. if (exponent > 0) { /*nonzero pixel*/
  86910. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86911. float32array[index + 0] = red * exponent;
  86912. float32array[index + 1] = green * exponent;
  86913. float32array[index + 2] = blue * exponent;
  86914. }
  86915. else {
  86916. float32array[index + 0] = 0;
  86917. float32array[index + 1] = 0;
  86918. float32array[index + 2] = 0;
  86919. }
  86920. };
  86921. HDRTools.readStringLine = function (uint8array, startIndex) {
  86922. var line = "";
  86923. var character = "";
  86924. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86925. character = String.fromCharCode(uint8array[i]);
  86926. if (character == "\n") {
  86927. break;
  86928. }
  86929. line += character;
  86930. }
  86931. return line;
  86932. };
  86933. /**
  86934. * Reads header information from an RGBE texture stored in a native array.
  86935. * More information on this format are available here:
  86936. * https://en.wikipedia.org/wiki/RGBE_image_format
  86937. *
  86938. * @param uint8array The binary file stored in native array.
  86939. * @return The header information.
  86940. */
  86941. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86942. var height = 0;
  86943. var width = 0;
  86944. var line = this.readStringLine(uint8array, 0);
  86945. if (line[0] != '#' || line[1] != '?') {
  86946. throw "Bad HDR Format.";
  86947. }
  86948. var endOfHeader = false;
  86949. var findFormat = false;
  86950. var lineIndex = 0;
  86951. do {
  86952. lineIndex += (line.length + 1);
  86953. line = this.readStringLine(uint8array, lineIndex);
  86954. if (line == "FORMAT=32-bit_rle_rgbe") {
  86955. findFormat = true;
  86956. }
  86957. else if (line.length == 0) {
  86958. endOfHeader = true;
  86959. }
  86960. } while (!endOfHeader);
  86961. if (!findFormat) {
  86962. throw "HDR Bad header format, unsupported FORMAT";
  86963. }
  86964. lineIndex += (line.length + 1);
  86965. line = this.readStringLine(uint8array, lineIndex);
  86966. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86967. var match = sizeRegexp.exec(line);
  86968. // TODO. Support +Y and -X if needed.
  86969. if (!match || match.length < 3) {
  86970. throw "HDR Bad header format, no size";
  86971. }
  86972. width = parseInt(match[2]);
  86973. height = parseInt(match[1]);
  86974. if (width < 8 || width > 0x7fff) {
  86975. throw "HDR Bad header format, unsupported size";
  86976. }
  86977. lineIndex += (line.length + 1);
  86978. return {
  86979. height: height,
  86980. width: width,
  86981. dataPosition: lineIndex
  86982. };
  86983. };
  86984. /**
  86985. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86986. * This RGBE texture needs to store the information as a panorama.
  86987. *
  86988. * More information on this format are available here:
  86989. * https://en.wikipedia.org/wiki/RGBE_image_format
  86990. *
  86991. * @param buffer The binary file stored in an array buffer.
  86992. * @param size The expected size of the extracted cubemap.
  86993. * @return The Cube Map information.
  86994. */
  86995. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86996. var uint8array = new Uint8Array(buffer);
  86997. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86998. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86999. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  87000. return cubeMapData;
  87001. };
  87002. /**
  87003. * Returns the pixels data extracted from an RGBE texture.
  87004. * This pixels will be stored left to right up to down in the R G B order in one array.
  87005. *
  87006. * More information on this format are available here:
  87007. * https://en.wikipedia.org/wiki/RGBE_image_format
  87008. *
  87009. * @param uint8array The binary file stored in an array buffer.
  87010. * @param hdrInfo The header information of the file.
  87011. * @return The pixels data in RGB right to left up to down order.
  87012. */
  87013. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  87014. // Keep for multi format supports.
  87015. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  87016. };
  87017. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  87018. var num_scanlines = hdrInfo.height;
  87019. var scanline_width = hdrInfo.width;
  87020. var a, b, c, d, count;
  87021. var dataIndex = hdrInfo.dataPosition;
  87022. var index = 0, endIndex = 0, i = 0;
  87023. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  87024. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  87025. // 3 channels of 4 bytes per pixel in float.
  87026. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  87027. var resultArray = new Float32Array(resultBuffer);
  87028. // read in each successive scanline
  87029. while (num_scanlines > 0) {
  87030. a = uint8array[dataIndex++];
  87031. b = uint8array[dataIndex++];
  87032. c = uint8array[dataIndex++];
  87033. d = uint8array[dataIndex++];
  87034. if (a != 2 || b != 2 || (c & 0x80)) {
  87035. // this file is not run length encoded
  87036. throw "HDR Bad header format, not RLE";
  87037. }
  87038. if (((c << 8) | d) != scanline_width) {
  87039. throw "HDR Bad header format, wrong scan line width";
  87040. }
  87041. index = 0;
  87042. // read each of the four channels for the scanline into the buffer
  87043. for (i = 0; i < 4; i++) {
  87044. endIndex = (i + 1) * scanline_width;
  87045. while (index < endIndex) {
  87046. a = uint8array[dataIndex++];
  87047. b = uint8array[dataIndex++];
  87048. if (a > 128) {
  87049. // a run of the same value
  87050. count = a - 128;
  87051. if ((count == 0) || (count > endIndex - index)) {
  87052. throw "HDR Bad Format, bad scanline data (run)";
  87053. }
  87054. while (count-- > 0) {
  87055. scanLineArray[index++] = b;
  87056. }
  87057. }
  87058. else {
  87059. // a non-run
  87060. count = a;
  87061. if ((count == 0) || (count > endIndex - index)) {
  87062. throw "HDR Bad Format, bad scanline data (non-run)";
  87063. }
  87064. scanLineArray[index++] = b;
  87065. if (--count > 0) {
  87066. for (var j = 0; j < count; j++) {
  87067. scanLineArray[index++] = uint8array[dataIndex++];
  87068. }
  87069. }
  87070. }
  87071. }
  87072. }
  87073. // now convert data from buffer into floats
  87074. for (i = 0; i < scanline_width; i++) {
  87075. a = scanLineArray[i];
  87076. b = scanLineArray[i + scanline_width];
  87077. c = scanLineArray[i + 2 * scanline_width];
  87078. d = scanLineArray[i + 3 * scanline_width];
  87079. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  87080. }
  87081. num_scanlines--;
  87082. }
  87083. return resultArray;
  87084. };
  87085. return HDRTools;
  87086. }());
  87087. BABYLON.HDRTools = HDRTools;
  87088. })(BABYLON || (BABYLON = {}));
  87089. //# sourceMappingURL=babylon.hdr.js.map
  87090. var BABYLON;
  87091. (function (BABYLON) {
  87092. /**
  87093. * This represents a texture coming from an HDR input.
  87094. *
  87095. * The only supported format is currently panorama picture stored in RGBE format.
  87096. * Example of such files can be found on HDRLib: http://hdrlib.com/
  87097. */
  87098. var HDRCubeTexture = /** @class */ (function (_super) {
  87099. __extends(HDRCubeTexture, _super);
  87100. /**
  87101. * Instantiates an HDRTexture from the following parameters.
  87102. *
  87103. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  87104. * @param scene The scene the texture will be used in
  87105. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  87106. * @param noMipmap Forces to not generate the mipmap if true
  87107. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  87108. * @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)
  87109. * @param reserved Reserved flag for internal use.
  87110. */
  87111. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  87112. if (noMipmap === void 0) { noMipmap = false; }
  87113. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87114. if (gammaSpace === void 0) { gammaSpace = false; }
  87115. if (reserved === void 0) { reserved = false; }
  87116. if (onLoad === void 0) { onLoad = null; }
  87117. if (onError === void 0) { onError = null; }
  87118. var _this = _super.call(this, scene) || this;
  87119. _this._generateHarmonics = true;
  87120. _this._onLoad = null;
  87121. _this._onError = null;
  87122. /**
  87123. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  87124. */
  87125. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  87126. _this._isBlocking = true;
  87127. _this._rotationY = 0;
  87128. /**
  87129. * Gets or sets the center of the bounding box associated with the cube texture
  87130. * It must define where the camera used to render the texture was set
  87131. */
  87132. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  87133. if (!url) {
  87134. return _this;
  87135. }
  87136. _this.name = url;
  87137. _this.url = url;
  87138. _this.hasAlpha = false;
  87139. _this.isCube = true;
  87140. _this._textureMatrix = BABYLON.Matrix.Identity();
  87141. _this._onLoad = onLoad;
  87142. _this._onError = onError;
  87143. _this.gammaSpace = gammaSpace;
  87144. _this._noMipmap = noMipmap;
  87145. _this._size = size;
  87146. _this._texture = _this._getFromCache(url, _this._noMipmap);
  87147. if (!_this._texture) {
  87148. if (!scene.useDelayedTextureLoading) {
  87149. _this.loadTexture();
  87150. }
  87151. else {
  87152. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  87153. }
  87154. }
  87155. return _this;
  87156. }
  87157. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  87158. /**
  87159. * Gets wether or not the texture is blocking during loading.
  87160. */
  87161. get: function () {
  87162. return this._isBlocking;
  87163. },
  87164. /**
  87165. * Sets wether or not the texture is blocking during loading.
  87166. */
  87167. set: function (value) {
  87168. this._isBlocking = value;
  87169. },
  87170. enumerable: true,
  87171. configurable: true
  87172. });
  87173. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  87174. /**
  87175. * Gets texture matrix rotation angle around Y axis radians.
  87176. */
  87177. get: function () {
  87178. return this._rotationY;
  87179. },
  87180. /**
  87181. * Sets texture matrix rotation angle around Y axis in radians.
  87182. */
  87183. set: function (value) {
  87184. this._rotationY = value;
  87185. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  87186. },
  87187. enumerable: true,
  87188. configurable: true
  87189. });
  87190. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  87191. get: function () {
  87192. return this._boundingBoxSize;
  87193. },
  87194. /**
  87195. * Gets or sets the size of the bounding box associated with the cube texture
  87196. * When defined, the cubemap will switch to local mode
  87197. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  87198. * @example https://www.babylonjs-playground.com/#RNASML
  87199. */
  87200. set: function (value) {
  87201. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  87202. return;
  87203. }
  87204. this._boundingBoxSize = value;
  87205. var scene = this.getScene();
  87206. if (scene) {
  87207. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  87208. }
  87209. },
  87210. enumerable: true,
  87211. configurable: true
  87212. });
  87213. /**
  87214. * Occurs when the file is raw .hdr file.
  87215. */
  87216. HDRCubeTexture.prototype.loadTexture = function () {
  87217. var _this = this;
  87218. var callback = function (buffer) {
  87219. _this.lodGenerationOffset = 0.0;
  87220. _this.lodGenerationScale = 0.8;
  87221. var scene = _this.getScene();
  87222. if (!scene) {
  87223. return null;
  87224. }
  87225. // Extract the raw linear data.
  87226. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  87227. // Generate harmonics if needed.
  87228. if (_this._generateHarmonics) {
  87229. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  87230. _this.sphericalPolynomial = sphericalPolynomial;
  87231. }
  87232. var results = [];
  87233. var byteArray = null;
  87234. // Push each faces.
  87235. for (var j = 0; j < 6; j++) {
  87236. // Create uintarray fallback.
  87237. if (!scene.getEngine().getCaps().textureFloat) {
  87238. // 3 channels of 1 bytes per pixel in bytes.
  87239. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  87240. byteArray = new Uint8Array(byteBuffer);
  87241. }
  87242. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  87243. // If special cases.
  87244. if (_this.gammaSpace || byteArray) {
  87245. for (var i = 0; i < _this._size * _this._size; i++) {
  87246. // Put in gamma space if requested.
  87247. if (_this.gammaSpace) {
  87248. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  87249. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  87250. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  87251. }
  87252. // Convert to int texture for fallback.
  87253. if (byteArray) {
  87254. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  87255. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  87256. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  87257. // May use luminance instead if the result is not accurate.
  87258. var max = Math.max(Math.max(r, g), b);
  87259. if (max > 255) {
  87260. var scale = 255 / max;
  87261. r *= scale;
  87262. g *= scale;
  87263. b *= scale;
  87264. }
  87265. byteArray[(i * 3) + 0] = r;
  87266. byteArray[(i * 3) + 1] = g;
  87267. byteArray[(i * 3) + 2] = b;
  87268. }
  87269. }
  87270. }
  87271. if (byteArray) {
  87272. results.push(byteArray);
  87273. }
  87274. else {
  87275. results.push(dataFace);
  87276. }
  87277. }
  87278. return results;
  87279. };
  87280. var scene = this.getScene();
  87281. if (scene) {
  87282. 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);
  87283. }
  87284. };
  87285. HDRCubeTexture.prototype.clone = function () {
  87286. var scene = this.getScene();
  87287. if (!scene) {
  87288. return this;
  87289. }
  87290. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  87291. // Base texture
  87292. newTexture.level = this.level;
  87293. newTexture.wrapU = this.wrapU;
  87294. newTexture.wrapV = this.wrapV;
  87295. newTexture.coordinatesIndex = this.coordinatesIndex;
  87296. newTexture.coordinatesMode = this.coordinatesMode;
  87297. return newTexture;
  87298. };
  87299. // Methods
  87300. HDRCubeTexture.prototype.delayLoad = function () {
  87301. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87302. return;
  87303. }
  87304. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87305. this._texture = this._getFromCache(this.url, this._noMipmap);
  87306. if (!this._texture) {
  87307. this.loadTexture();
  87308. }
  87309. };
  87310. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  87311. return this._textureMatrix;
  87312. };
  87313. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  87314. this._textureMatrix = value;
  87315. };
  87316. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87317. var texture = null;
  87318. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87319. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  87320. texture.name = parsedTexture.name;
  87321. texture.hasAlpha = parsedTexture.hasAlpha;
  87322. texture.level = parsedTexture.level;
  87323. texture.coordinatesMode = parsedTexture.coordinatesMode;
  87324. texture.isBlocking = parsedTexture.isBlocking;
  87325. }
  87326. if (texture) {
  87327. if (parsedTexture.boundingBoxPosition) {
  87328. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  87329. }
  87330. if (parsedTexture.boundingBoxSize) {
  87331. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  87332. }
  87333. if (parsedTexture.rotationY) {
  87334. texture.rotationY = parsedTexture.rotationY;
  87335. }
  87336. }
  87337. return texture;
  87338. };
  87339. HDRCubeTexture.prototype.serialize = function () {
  87340. if (!this.name) {
  87341. return null;
  87342. }
  87343. var serializationObject = {};
  87344. serializationObject.name = this.name;
  87345. serializationObject.hasAlpha = this.hasAlpha;
  87346. serializationObject.isCube = true;
  87347. serializationObject.level = this.level;
  87348. serializationObject.size = this._size;
  87349. serializationObject.coordinatesMode = this.coordinatesMode;
  87350. serializationObject.useInGammaSpace = this.gammaSpace;
  87351. serializationObject.generateHarmonics = this._generateHarmonics;
  87352. serializationObject.customType = "BABYLON.HDRCubeTexture";
  87353. serializationObject.noMipmap = this._noMipmap;
  87354. serializationObject.isBlocking = this._isBlocking;
  87355. serializationObject.rotationY = this._rotationY;
  87356. return serializationObject;
  87357. };
  87358. HDRCubeTexture._facesMapping = [
  87359. "right",
  87360. "left",
  87361. "up",
  87362. "down",
  87363. "front",
  87364. "back"
  87365. ];
  87366. return HDRCubeTexture;
  87367. }(BABYLON.BaseTexture));
  87368. BABYLON.HDRCubeTexture = HDRCubeTexture;
  87369. })(BABYLON || (BABYLON = {}));
  87370. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  87371. var BABYLON;
  87372. (function (BABYLON) {
  87373. /**
  87374. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  87375. */
  87376. var PanoramaToCubeMapTools = /** @class */ (function () {
  87377. function PanoramaToCubeMapTools() {
  87378. }
  87379. /**
  87380. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  87381. *
  87382. * @param float32Array The source data.
  87383. * @param inputWidth The width of the input panorama.
  87384. * @param inputhHeight The height of the input panorama.
  87385. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  87386. * @return The cubemap data
  87387. */
  87388. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  87389. if (!float32Array) {
  87390. throw "ConvertPanoramaToCubemap: input cannot be null";
  87391. }
  87392. if (float32Array.length != inputWidth * inputHeight * 3) {
  87393. throw "ConvertPanoramaToCubemap: input size is wrong";
  87394. }
  87395. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  87396. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  87397. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  87398. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  87399. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  87400. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  87401. return {
  87402. front: textureFront,
  87403. back: textureBack,
  87404. left: textureLeft,
  87405. right: textureRight,
  87406. up: textureUp,
  87407. down: textureDown,
  87408. size: size,
  87409. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87410. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  87411. gammaSpace: false,
  87412. };
  87413. };
  87414. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  87415. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  87416. var textureArray = new Float32Array(buffer);
  87417. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  87418. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  87419. var dy = 1 / texSize;
  87420. var fy = 0;
  87421. for (var y = 0; y < texSize; y++) {
  87422. var xv1 = faceData[0];
  87423. var xv2 = faceData[2];
  87424. for (var x = 0; x < texSize; x++) {
  87425. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  87426. v.normalize();
  87427. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  87428. // 3 channels per pixels
  87429. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  87430. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  87431. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  87432. xv1 = xv1.add(rotDX1);
  87433. xv2 = xv2.add(rotDX2);
  87434. }
  87435. fy += dy;
  87436. }
  87437. return textureArray;
  87438. };
  87439. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  87440. var theta = Math.atan2(vDir.z, vDir.x);
  87441. var phi = Math.acos(vDir.y);
  87442. while (theta < -Math.PI)
  87443. theta += 2 * Math.PI;
  87444. while (theta > Math.PI)
  87445. theta -= 2 * Math.PI;
  87446. var dx = theta / Math.PI;
  87447. var dy = phi / Math.PI;
  87448. // recenter.
  87449. dx = dx * 0.5 + 0.5;
  87450. var px = Math.round(dx * inputWidth);
  87451. if (px < 0)
  87452. px = 0;
  87453. else if (px >= inputWidth)
  87454. px = inputWidth - 1;
  87455. var py = Math.round(dy * inputHeight);
  87456. if (py < 0)
  87457. py = 0;
  87458. else if (py >= inputHeight)
  87459. py = inputHeight - 1;
  87460. var inputY = (inputHeight - py - 1);
  87461. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  87462. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  87463. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  87464. return {
  87465. r: r,
  87466. g: g,
  87467. b: b
  87468. };
  87469. };
  87470. PanoramaToCubeMapTools.FACE_FRONT = [
  87471. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87472. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87473. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87474. new BABYLON.Vector3(1.0, 1.0, -1.0)
  87475. ];
  87476. PanoramaToCubeMapTools.FACE_BACK = [
  87477. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87478. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87479. new BABYLON.Vector3(1.0, 1.0, 1.0),
  87480. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  87481. ];
  87482. PanoramaToCubeMapTools.FACE_RIGHT = [
  87483. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87484. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87485. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87486. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87487. ];
  87488. PanoramaToCubeMapTools.FACE_LEFT = [
  87489. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87490. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87491. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87492. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  87493. ];
  87494. PanoramaToCubeMapTools.FACE_DOWN = [
  87495. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87496. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87497. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87498. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87499. ];
  87500. PanoramaToCubeMapTools.FACE_UP = [
  87501. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87502. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87503. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87504. new BABYLON.Vector3(1.0, -1.0, -1.0)
  87505. ];
  87506. return PanoramaToCubeMapTools;
  87507. }());
  87508. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  87509. })(BABYLON || (BABYLON = {}));
  87510. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  87511. var BABYLON;
  87512. (function (BABYLON) {
  87513. var IndexedVector2 = /** @class */ (function (_super) {
  87514. __extends(IndexedVector2, _super);
  87515. function IndexedVector2(original, index) {
  87516. var _this = _super.call(this, original.x, original.y) || this;
  87517. _this.index = index;
  87518. return _this;
  87519. }
  87520. return IndexedVector2;
  87521. }(BABYLON.Vector2));
  87522. var PolygonPoints = /** @class */ (function () {
  87523. function PolygonPoints() {
  87524. this.elements = new Array();
  87525. }
  87526. PolygonPoints.prototype.add = function (originalPoints) {
  87527. var _this = this;
  87528. var result = new Array();
  87529. originalPoints.forEach(function (point) {
  87530. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  87531. var newPoint = new IndexedVector2(point, _this.elements.length);
  87532. result.push(newPoint);
  87533. _this.elements.push(newPoint);
  87534. }
  87535. });
  87536. return result;
  87537. };
  87538. PolygonPoints.prototype.computeBounds = function () {
  87539. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87540. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87541. this.elements.forEach(function (point) {
  87542. // x
  87543. if (point.x < lmin.x) {
  87544. lmin.x = point.x;
  87545. }
  87546. else if (point.x > lmax.x) {
  87547. lmax.x = point.x;
  87548. }
  87549. // y
  87550. if (point.y < lmin.y) {
  87551. lmin.y = point.y;
  87552. }
  87553. else if (point.y > lmax.y) {
  87554. lmax.y = point.y;
  87555. }
  87556. });
  87557. return {
  87558. min: lmin,
  87559. max: lmax,
  87560. width: lmax.x - lmin.x,
  87561. height: lmax.y - lmin.y
  87562. };
  87563. };
  87564. return PolygonPoints;
  87565. }());
  87566. var Polygon = /** @class */ (function () {
  87567. function Polygon() {
  87568. }
  87569. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87570. return [
  87571. new BABYLON.Vector2(xmin, ymin),
  87572. new BABYLON.Vector2(xmax, ymin),
  87573. new BABYLON.Vector2(xmax, ymax),
  87574. new BABYLON.Vector2(xmin, ymax)
  87575. ];
  87576. };
  87577. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87578. if (cx === void 0) { cx = 0; }
  87579. if (cy === void 0) { cy = 0; }
  87580. if (numberOfSides === void 0) { numberOfSides = 32; }
  87581. var result = new Array();
  87582. var angle = 0;
  87583. var increment = (Math.PI * 2) / numberOfSides;
  87584. for (var i = 0; i < numberOfSides; i++) {
  87585. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87586. angle -= increment;
  87587. }
  87588. return result;
  87589. };
  87590. Polygon.Parse = function (input) {
  87591. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87592. var i, result = [];
  87593. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87594. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87595. }
  87596. return result;
  87597. };
  87598. Polygon.StartingAt = function (x, y) {
  87599. return BABYLON.Path2.StartingAt(x, y);
  87600. };
  87601. return Polygon;
  87602. }());
  87603. BABYLON.Polygon = Polygon;
  87604. var PolygonMeshBuilder = /** @class */ (function () {
  87605. function PolygonMeshBuilder(name, contours, scene) {
  87606. this._points = new PolygonPoints();
  87607. this._outlinepoints = new PolygonPoints();
  87608. this._holes = new Array();
  87609. this._epoints = new Array();
  87610. this._eholes = new Array();
  87611. this._name = name;
  87612. this._scene = scene;
  87613. var points;
  87614. if (contours instanceof BABYLON.Path2) {
  87615. points = contours.getPoints();
  87616. }
  87617. else {
  87618. points = contours;
  87619. }
  87620. this._addToepoint(points);
  87621. this._points.add(points);
  87622. this._outlinepoints.add(points);
  87623. if (typeof earcut === 'undefined') {
  87624. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87625. }
  87626. }
  87627. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87628. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87629. var p = points_1[_i];
  87630. this._epoints.push(p.x, p.y);
  87631. }
  87632. };
  87633. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87634. this._points.add(hole);
  87635. var holepoints = new PolygonPoints();
  87636. holepoints.add(hole);
  87637. this._holes.push(holepoints);
  87638. this._eholes.push(this._epoints.length / 2);
  87639. this._addToepoint(hole);
  87640. return this;
  87641. };
  87642. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87643. var _this = this;
  87644. if (updatable === void 0) { updatable = false; }
  87645. if (depth === void 0) { depth = 0; }
  87646. var result = new BABYLON.Mesh(this._name, this._scene);
  87647. var normals = new Array();
  87648. var positions = new Array();
  87649. var uvs = new Array();
  87650. var bounds = this._points.computeBounds();
  87651. this._points.elements.forEach(function (p) {
  87652. normals.push(0, 1.0, 0);
  87653. positions.push(p.x, 0, p.y);
  87654. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87655. });
  87656. var indices = new Array();
  87657. var res = earcut(this._epoints, this._eholes, 2);
  87658. for (var i = 0; i < res.length; i++) {
  87659. indices.push(res[i]);
  87660. }
  87661. if (depth > 0) {
  87662. var positionscount = (positions.length / 3); //get the current pointcount
  87663. this._points.elements.forEach(function (p) {
  87664. normals.push(0, -1.0, 0);
  87665. positions.push(p.x, -depth, p.y);
  87666. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87667. });
  87668. var totalCount = indices.length;
  87669. for (var i = 0; i < totalCount; i += 3) {
  87670. var i0 = indices[i + 0];
  87671. var i1 = indices[i + 1];
  87672. var i2 = indices[i + 2];
  87673. indices.push(i2 + positionscount);
  87674. indices.push(i1 + positionscount);
  87675. indices.push(i0 + positionscount);
  87676. }
  87677. //Add the sides
  87678. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87679. this._holes.forEach(function (hole) {
  87680. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87681. });
  87682. }
  87683. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87684. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87685. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87686. result.setIndices(indices);
  87687. return result;
  87688. };
  87689. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87690. var StartIndex = positions.length / 3;
  87691. var ulength = 0;
  87692. for (var i = 0; i < points.elements.length; i++) {
  87693. var p = points.elements[i];
  87694. var p1;
  87695. if ((i + 1) > points.elements.length - 1) {
  87696. p1 = points.elements[0];
  87697. }
  87698. else {
  87699. p1 = points.elements[i + 1];
  87700. }
  87701. positions.push(p.x, 0, p.y);
  87702. positions.push(p.x, -depth, p.y);
  87703. positions.push(p1.x, 0, p1.y);
  87704. positions.push(p1.x, -depth, p1.y);
  87705. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87706. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87707. var v3 = v2.subtract(v1);
  87708. var v4 = new BABYLON.Vector3(0, 1, 0);
  87709. var vn = BABYLON.Vector3.Cross(v3, v4);
  87710. vn = vn.normalize();
  87711. uvs.push(ulength / bounds.width, 0);
  87712. uvs.push(ulength / bounds.width, 1);
  87713. ulength += v3.length();
  87714. uvs.push((ulength / bounds.width), 0);
  87715. uvs.push((ulength / bounds.width), 1);
  87716. if (!flip) {
  87717. normals.push(-vn.x, -vn.y, -vn.z);
  87718. normals.push(-vn.x, -vn.y, -vn.z);
  87719. normals.push(-vn.x, -vn.y, -vn.z);
  87720. normals.push(-vn.x, -vn.y, -vn.z);
  87721. indices.push(StartIndex);
  87722. indices.push(StartIndex + 1);
  87723. indices.push(StartIndex + 2);
  87724. indices.push(StartIndex + 1);
  87725. indices.push(StartIndex + 3);
  87726. indices.push(StartIndex + 2);
  87727. }
  87728. else {
  87729. normals.push(vn.x, vn.y, vn.z);
  87730. normals.push(vn.x, vn.y, vn.z);
  87731. normals.push(vn.x, vn.y, vn.z);
  87732. normals.push(vn.x, vn.y, vn.z);
  87733. indices.push(StartIndex);
  87734. indices.push(StartIndex + 2);
  87735. indices.push(StartIndex + 1);
  87736. indices.push(StartIndex + 1);
  87737. indices.push(StartIndex + 2);
  87738. indices.push(StartIndex + 3);
  87739. }
  87740. StartIndex += 4;
  87741. }
  87742. ;
  87743. };
  87744. return PolygonMeshBuilder;
  87745. }());
  87746. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87747. })(BABYLON || (BABYLON = {}));
  87748. //# sourceMappingURL=babylon.polygonMesh.js.map
  87749. var BABYLON;
  87750. (function (BABYLON) {
  87751. // Unique ID when we import meshes from Babylon to CSG
  87752. var currentCSGMeshId = 0;
  87753. // # class Vertex
  87754. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87755. // one to provide additional features like texture coordinates and vertex
  87756. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87757. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87758. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87759. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87760. // is not used anywhere else.
  87761. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87762. var Vertex = /** @class */ (function () {
  87763. function Vertex(pos, normal, uv) {
  87764. this.pos = pos;
  87765. this.normal = normal;
  87766. this.uv = uv;
  87767. }
  87768. Vertex.prototype.clone = function () {
  87769. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87770. };
  87771. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87772. // orientation of a polygon is flipped.
  87773. Vertex.prototype.flip = function () {
  87774. this.normal = this.normal.scale(-1);
  87775. };
  87776. // Create a new vertex between this vertex and `other` by linearly
  87777. // interpolating all properties using a parameter of `t`. Subclasses should
  87778. // override this to interpolate additional properties.
  87779. Vertex.prototype.interpolate = function (other, t) {
  87780. 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));
  87781. };
  87782. return Vertex;
  87783. }());
  87784. // # class Plane
  87785. // Represents a plane in 3D space.
  87786. var Plane = /** @class */ (function () {
  87787. function Plane(normal, w) {
  87788. this.normal = normal;
  87789. this.w = w;
  87790. }
  87791. Plane.FromPoints = function (a, b, c) {
  87792. var v0 = c.subtract(a);
  87793. var v1 = b.subtract(a);
  87794. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87795. return null;
  87796. }
  87797. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87798. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87799. };
  87800. Plane.prototype.clone = function () {
  87801. return new Plane(this.normal.clone(), this.w);
  87802. };
  87803. Plane.prototype.flip = function () {
  87804. this.normal.scaleInPlace(-1);
  87805. this.w = -this.w;
  87806. };
  87807. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87808. // fragments in the appropriate lists. Coplanar polygons go into either
  87809. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87810. // respect to this plane. Polygons in front or in back of this plane go into
  87811. // either `front` or `back`.
  87812. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87813. var COPLANAR = 0;
  87814. var FRONT = 1;
  87815. var BACK = 2;
  87816. var SPANNING = 3;
  87817. // Classify each point as well as the entire polygon into one of the above
  87818. // four classes.
  87819. var polygonType = 0;
  87820. var types = [];
  87821. var i;
  87822. var t;
  87823. for (i = 0; i < polygon.vertices.length; i++) {
  87824. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87825. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87826. polygonType |= type;
  87827. types.push(type);
  87828. }
  87829. // Put the polygon in the correct list, splitting it when necessary.
  87830. switch (polygonType) {
  87831. case COPLANAR:
  87832. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87833. break;
  87834. case FRONT:
  87835. front.push(polygon);
  87836. break;
  87837. case BACK:
  87838. back.push(polygon);
  87839. break;
  87840. case SPANNING:
  87841. var f = [], b = [];
  87842. for (i = 0; i < polygon.vertices.length; i++) {
  87843. var j = (i + 1) % polygon.vertices.length;
  87844. var ti = types[i], tj = types[j];
  87845. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87846. if (ti !== BACK)
  87847. f.push(vi);
  87848. if (ti !== FRONT)
  87849. b.push(ti !== BACK ? vi.clone() : vi);
  87850. if ((ti | tj) === SPANNING) {
  87851. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87852. var v = vi.interpolate(vj, t);
  87853. f.push(v);
  87854. b.push(v.clone());
  87855. }
  87856. }
  87857. var poly;
  87858. if (f.length >= 3) {
  87859. poly = new Polygon(f, polygon.shared);
  87860. if (poly.plane)
  87861. front.push(poly);
  87862. }
  87863. if (b.length >= 3) {
  87864. poly = new Polygon(b, polygon.shared);
  87865. if (poly.plane)
  87866. back.push(poly);
  87867. }
  87868. break;
  87869. }
  87870. };
  87871. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87872. // point is on the plane.
  87873. Plane.EPSILON = 1e-5;
  87874. return Plane;
  87875. }());
  87876. // # class Polygon
  87877. // Represents a convex polygon. The vertices used to initialize a polygon must
  87878. // be coplanar and form a convex loop.
  87879. //
  87880. // Each convex polygon has a `shared` property, which is shared between all
  87881. // polygons that are clones of each other or were split from the same polygon.
  87882. // This can be used to define per-polygon properties (such as surface color).
  87883. var Polygon = /** @class */ (function () {
  87884. function Polygon(vertices, shared) {
  87885. this.vertices = vertices;
  87886. this.shared = shared;
  87887. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87888. }
  87889. Polygon.prototype.clone = function () {
  87890. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87891. return new Polygon(vertices, this.shared);
  87892. };
  87893. Polygon.prototype.flip = function () {
  87894. this.vertices.reverse().map(function (v) { v.flip(); });
  87895. this.plane.flip();
  87896. };
  87897. return Polygon;
  87898. }());
  87899. // # class Node
  87900. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87901. // by picking a polygon to split along. That polygon (and all other coplanar
  87902. // polygons) are added directly to that node and the other polygons are added to
  87903. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87904. // no distinction between internal and leaf nodes.
  87905. var Node = /** @class */ (function () {
  87906. function Node(polygons) {
  87907. this.plane = null;
  87908. this.front = null;
  87909. this.back = null;
  87910. this.polygons = new Array();
  87911. if (polygons) {
  87912. this.build(polygons);
  87913. }
  87914. }
  87915. Node.prototype.clone = function () {
  87916. var node = new Node();
  87917. node.plane = this.plane && this.plane.clone();
  87918. node.front = this.front && this.front.clone();
  87919. node.back = this.back && this.back.clone();
  87920. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87921. return node;
  87922. };
  87923. // Convert solid space to empty space and empty space to solid space.
  87924. Node.prototype.invert = function () {
  87925. for (var i = 0; i < this.polygons.length; i++) {
  87926. this.polygons[i].flip();
  87927. }
  87928. if (this.plane) {
  87929. this.plane.flip();
  87930. }
  87931. if (this.front) {
  87932. this.front.invert();
  87933. }
  87934. if (this.back) {
  87935. this.back.invert();
  87936. }
  87937. var temp = this.front;
  87938. this.front = this.back;
  87939. this.back = temp;
  87940. };
  87941. // Recursively remove all polygons in `polygons` that are inside this BSP
  87942. // tree.
  87943. Node.prototype.clipPolygons = function (polygons) {
  87944. if (!this.plane)
  87945. return polygons.slice();
  87946. var front = new Array(), back = new Array();
  87947. for (var i = 0; i < polygons.length; i++) {
  87948. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87949. }
  87950. if (this.front) {
  87951. front = this.front.clipPolygons(front);
  87952. }
  87953. if (this.back) {
  87954. back = this.back.clipPolygons(back);
  87955. }
  87956. else {
  87957. back = [];
  87958. }
  87959. return front.concat(back);
  87960. };
  87961. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87962. // `bsp`.
  87963. Node.prototype.clipTo = function (bsp) {
  87964. this.polygons = bsp.clipPolygons(this.polygons);
  87965. if (this.front)
  87966. this.front.clipTo(bsp);
  87967. if (this.back)
  87968. this.back.clipTo(bsp);
  87969. };
  87970. // Return a list of all polygons in this BSP tree.
  87971. Node.prototype.allPolygons = function () {
  87972. var polygons = this.polygons.slice();
  87973. if (this.front)
  87974. polygons = polygons.concat(this.front.allPolygons());
  87975. if (this.back)
  87976. polygons = polygons.concat(this.back.allPolygons());
  87977. return polygons;
  87978. };
  87979. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87980. // new polygons are filtered down to the bottom of the tree and become new
  87981. // nodes there. Each set of polygons is partitioned using the first polygon
  87982. // (no heuristic is used to pick a good split).
  87983. Node.prototype.build = function (polygons) {
  87984. if (!polygons.length)
  87985. return;
  87986. if (!this.plane)
  87987. this.plane = polygons[0].plane.clone();
  87988. var front = new Array(), back = new Array();
  87989. for (var i = 0; i < polygons.length; i++) {
  87990. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87991. }
  87992. if (front.length) {
  87993. if (!this.front)
  87994. this.front = new Node();
  87995. this.front.build(front);
  87996. }
  87997. if (back.length) {
  87998. if (!this.back)
  87999. this.back = new Node();
  88000. this.back.build(back);
  88001. }
  88002. };
  88003. return Node;
  88004. }());
  88005. var CSG = /** @class */ (function () {
  88006. function CSG() {
  88007. this.polygons = new Array();
  88008. }
  88009. // Convert BABYLON.Mesh to BABYLON.CSG
  88010. CSG.FromMesh = function (mesh) {
  88011. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  88012. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  88013. if (mesh instanceof BABYLON.Mesh) {
  88014. mesh.computeWorldMatrix(true);
  88015. matrix = mesh.getWorldMatrix();
  88016. meshPosition = mesh.position.clone();
  88017. meshRotation = mesh.rotation.clone();
  88018. if (mesh.rotationQuaternion) {
  88019. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  88020. }
  88021. meshScaling = mesh.scaling.clone();
  88022. }
  88023. else {
  88024. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  88025. }
  88026. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88027. var subMeshes = mesh.subMeshes;
  88028. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  88029. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  88030. vertices = [];
  88031. for (var j = 0; j < 3; j++) {
  88032. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  88033. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  88034. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  88035. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  88036. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  88037. vertex = new Vertex(position, normal, uv);
  88038. vertices.push(vertex);
  88039. }
  88040. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  88041. // To handle the case of degenerated triangle
  88042. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  88043. if (polygon.plane)
  88044. polygons.push(polygon);
  88045. }
  88046. }
  88047. var csg = CSG.FromPolygons(polygons);
  88048. csg.matrix = matrix;
  88049. csg.position = meshPosition;
  88050. csg.rotation = meshRotation;
  88051. csg.scaling = meshScaling;
  88052. csg.rotationQuaternion = meshRotationQuaternion;
  88053. currentCSGMeshId++;
  88054. return csg;
  88055. };
  88056. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  88057. CSG.FromPolygons = function (polygons) {
  88058. var csg = new CSG();
  88059. csg.polygons = polygons;
  88060. return csg;
  88061. };
  88062. CSG.prototype.clone = function () {
  88063. var csg = new CSG();
  88064. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  88065. csg.copyTransformAttributes(this);
  88066. return csg;
  88067. };
  88068. CSG.prototype.union = function (csg) {
  88069. var a = new Node(this.clone().polygons);
  88070. var b = new Node(csg.clone().polygons);
  88071. a.clipTo(b);
  88072. b.clipTo(a);
  88073. b.invert();
  88074. b.clipTo(a);
  88075. b.invert();
  88076. a.build(b.allPolygons());
  88077. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88078. };
  88079. CSG.prototype.unionInPlace = function (csg) {
  88080. var a = new Node(this.polygons);
  88081. var b = new Node(csg.polygons);
  88082. a.clipTo(b);
  88083. b.clipTo(a);
  88084. b.invert();
  88085. b.clipTo(a);
  88086. b.invert();
  88087. a.build(b.allPolygons());
  88088. this.polygons = a.allPolygons();
  88089. };
  88090. CSG.prototype.subtract = function (csg) {
  88091. var a = new Node(this.clone().polygons);
  88092. var b = new Node(csg.clone().polygons);
  88093. a.invert();
  88094. a.clipTo(b);
  88095. b.clipTo(a);
  88096. b.invert();
  88097. b.clipTo(a);
  88098. b.invert();
  88099. a.build(b.allPolygons());
  88100. a.invert();
  88101. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88102. };
  88103. CSG.prototype.subtractInPlace = function (csg) {
  88104. var a = new Node(this.polygons);
  88105. var b = new Node(csg.polygons);
  88106. a.invert();
  88107. a.clipTo(b);
  88108. b.clipTo(a);
  88109. b.invert();
  88110. b.clipTo(a);
  88111. b.invert();
  88112. a.build(b.allPolygons());
  88113. a.invert();
  88114. this.polygons = a.allPolygons();
  88115. };
  88116. CSG.prototype.intersect = function (csg) {
  88117. var a = new Node(this.clone().polygons);
  88118. var b = new Node(csg.clone().polygons);
  88119. a.invert();
  88120. b.clipTo(a);
  88121. b.invert();
  88122. a.clipTo(b);
  88123. b.clipTo(a);
  88124. a.build(b.allPolygons());
  88125. a.invert();
  88126. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  88127. };
  88128. CSG.prototype.intersectInPlace = function (csg) {
  88129. var a = new Node(this.polygons);
  88130. var b = new Node(csg.polygons);
  88131. a.invert();
  88132. b.clipTo(a);
  88133. b.invert();
  88134. a.clipTo(b);
  88135. b.clipTo(a);
  88136. a.build(b.allPolygons());
  88137. a.invert();
  88138. this.polygons = a.allPolygons();
  88139. };
  88140. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  88141. // not modified.
  88142. CSG.prototype.inverse = function () {
  88143. var csg = this.clone();
  88144. csg.inverseInPlace();
  88145. return csg;
  88146. };
  88147. CSG.prototype.inverseInPlace = function () {
  88148. this.polygons.map(function (p) { p.flip(); });
  88149. };
  88150. // This is used to keep meshes transformations so they can be restored
  88151. // when we build back a Babylon Mesh
  88152. // NB : All CSG operations are performed in world coordinates
  88153. CSG.prototype.copyTransformAttributes = function (csg) {
  88154. this.matrix = csg.matrix;
  88155. this.position = csg.position;
  88156. this.rotation = csg.rotation;
  88157. this.scaling = csg.scaling;
  88158. this.rotationQuaternion = csg.rotationQuaternion;
  88159. return this;
  88160. };
  88161. // Build Raw mesh from CSG
  88162. // Coordinates here are in world space
  88163. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  88164. var matrix = this.matrix.clone();
  88165. matrix.invert();
  88166. 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;
  88167. if (keepSubMeshes) {
  88168. // Sort Polygons, since subMeshes are indices range
  88169. polygons.sort(function (a, b) {
  88170. if (a.shared.meshId === b.shared.meshId) {
  88171. return a.shared.subMeshId - b.shared.subMeshId;
  88172. }
  88173. else {
  88174. return a.shared.meshId - b.shared.meshId;
  88175. }
  88176. });
  88177. }
  88178. for (var i = 0, il = polygons.length; i < il; i++) {
  88179. polygon = polygons[i];
  88180. // Building SubMeshes
  88181. if (!subMesh_dict[polygon.shared.meshId]) {
  88182. subMesh_dict[polygon.shared.meshId] = {};
  88183. }
  88184. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  88185. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  88186. indexStart: +Infinity,
  88187. indexEnd: -Infinity,
  88188. materialIndex: polygon.shared.materialIndex
  88189. };
  88190. }
  88191. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  88192. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  88193. polygonIndices[0] = 0;
  88194. polygonIndices[1] = j - 1;
  88195. polygonIndices[2] = j;
  88196. for (var k = 0; k < 3; k++) {
  88197. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  88198. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  88199. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  88200. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  88201. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  88202. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  88203. // Check if 2 points can be merged
  88204. if (!(typeof vertex_idx !== 'undefined' &&
  88205. normals[vertex_idx * 3] === localNormal.x &&
  88206. normals[vertex_idx * 3 + 1] === localNormal.y &&
  88207. normals[vertex_idx * 3 + 2] === localNormal.z &&
  88208. uvs[vertex_idx * 2] === uv.x &&
  88209. uvs[vertex_idx * 2 + 1] === uv.y)) {
  88210. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  88211. uvs.push(uv.x, uv.y);
  88212. normals.push(normal.x, normal.y, normal.z);
  88213. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  88214. }
  88215. indices.push(vertex_idx);
  88216. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  88217. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  88218. currentIndex++;
  88219. }
  88220. }
  88221. }
  88222. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  88223. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  88224. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  88225. mesh.setIndices(indices, null);
  88226. if (keepSubMeshes) {
  88227. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  88228. var materialIndexOffset = 0, materialMaxIndex;
  88229. mesh.subMeshes = new Array();
  88230. for (var m in subMesh_dict) {
  88231. materialMaxIndex = -1;
  88232. for (var sm in subMesh_dict[m]) {
  88233. subMesh_obj = subMesh_dict[m][sm];
  88234. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  88235. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  88236. }
  88237. materialIndexOffset += ++materialMaxIndex;
  88238. }
  88239. }
  88240. return mesh;
  88241. };
  88242. // Build Mesh from CSG taking material and transforms into account
  88243. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  88244. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  88245. mesh.material = material;
  88246. mesh.position.copyFrom(this.position);
  88247. mesh.rotation.copyFrom(this.rotation);
  88248. if (this.rotationQuaternion) {
  88249. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  88250. }
  88251. mesh.scaling.copyFrom(this.scaling);
  88252. mesh.computeWorldMatrix(true);
  88253. return mesh;
  88254. };
  88255. return CSG;
  88256. }());
  88257. BABYLON.CSG = CSG;
  88258. })(BABYLON || (BABYLON = {}));
  88259. //# sourceMappingURL=babylon.csg.js.map
  88260. var BABYLON;
  88261. (function (BABYLON) {
  88262. var LensFlare = /** @class */ (function () {
  88263. function LensFlare(size, position, color, imgUrl, system) {
  88264. this.size = size;
  88265. this.position = position;
  88266. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  88267. this.color = color || new BABYLON.Color3(1, 1, 1);
  88268. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  88269. this._system = system;
  88270. system.lensFlares.push(this);
  88271. }
  88272. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  88273. return new LensFlare(size, position, color, imgUrl, system);
  88274. };
  88275. LensFlare.prototype.dispose = function () {
  88276. if (this.texture) {
  88277. this.texture.dispose();
  88278. }
  88279. // Remove from scene
  88280. var index = this._system.lensFlares.indexOf(this);
  88281. this._system.lensFlares.splice(index, 1);
  88282. };
  88283. ;
  88284. return LensFlare;
  88285. }());
  88286. BABYLON.LensFlare = LensFlare;
  88287. })(BABYLON || (BABYLON = {}));
  88288. //# sourceMappingURL=babylon.lensFlare.js.map
  88289. var BABYLON;
  88290. (function (BABYLON) {
  88291. // Adds the parser to the scene parsers.
  88292. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  88293. // Lens flares
  88294. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  88295. if (!container.lensFlareSystems) {
  88296. container.lensFlareSystems = new Array();
  88297. }
  88298. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  88299. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  88300. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  88301. container.lensFlareSystems.push(lf);
  88302. }
  88303. }
  88304. });
  88305. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  88306. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88307. if (this.lensFlareSystems[index].name === name) {
  88308. return this.lensFlareSystems[index];
  88309. }
  88310. }
  88311. return null;
  88312. };
  88313. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  88314. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88315. if (this.lensFlareSystems[index].id === id) {
  88316. return this.lensFlareSystems[index];
  88317. }
  88318. }
  88319. return null;
  88320. };
  88321. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  88322. var index = this.lensFlareSystems.indexOf(toRemove);
  88323. if (index !== -1) {
  88324. this.lensFlareSystems.splice(index, 1);
  88325. }
  88326. return index;
  88327. };
  88328. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  88329. this.lensFlareSystems.push(newLensFlareSystem);
  88330. };
  88331. /**
  88332. * Defines the lens flare scene component responsible to manage any lens flares
  88333. * in a given scene.
  88334. */
  88335. var LensFlareSystemSceneComponent = /** @class */ (function () {
  88336. /**
  88337. * Creates a new instance of the component for the given scene
  88338. * @param scene Defines the scene to register the component in
  88339. */
  88340. function LensFlareSystemSceneComponent(scene) {
  88341. /**
  88342. * The component name helpfull to identify the component in the list of scene components.
  88343. */
  88344. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  88345. this.scene = scene;
  88346. scene.lensFlareSystems = new Array();
  88347. }
  88348. /**
  88349. * Registers the component in a given scene
  88350. */
  88351. LensFlareSystemSceneComponent.prototype.register = function () {
  88352. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  88353. };
  88354. /**
  88355. * Rebuilds the elements related to this component in case of
  88356. * context lost for instance.
  88357. */
  88358. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  88359. // Nothing to do for lens flare
  88360. };
  88361. /**
  88362. * Adds all the element from the container to the scene
  88363. * @param container the container holding the elements
  88364. */
  88365. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  88366. var _this = this;
  88367. if (!container.lensFlareSystems) {
  88368. return;
  88369. }
  88370. container.lensFlareSystems.forEach(function (o) {
  88371. _this.scene.addLensFlareSystem(o);
  88372. });
  88373. };
  88374. /**
  88375. * Removes all the elements in the container from the scene
  88376. * @param container contains the elements to remove
  88377. */
  88378. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  88379. var _this = this;
  88380. if (!container.lensFlareSystems) {
  88381. return;
  88382. }
  88383. container.lensFlareSystems.forEach(function (o) {
  88384. _this.scene.removeLensFlareSystem(o);
  88385. });
  88386. };
  88387. /**
  88388. * Serializes the component data to the specified json object
  88389. * @param serializationObject The object to serialize to
  88390. */
  88391. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  88392. // Lens flares
  88393. serializationObject.lensFlareSystems = [];
  88394. var lensFlareSystems = this.scene.lensFlareSystems;
  88395. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  88396. var lensFlareSystem = lensFlareSystems_1[_i];
  88397. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  88398. }
  88399. };
  88400. /**
  88401. * Disposes the component and the associated ressources.
  88402. */
  88403. LensFlareSystemSceneComponent.prototype.dispose = function () {
  88404. var lensFlareSystems = this.scene.lensFlareSystems;
  88405. while (lensFlareSystems.length) {
  88406. lensFlareSystems[0].dispose();
  88407. }
  88408. };
  88409. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  88410. // Lens flares
  88411. if (this.scene.lensFlaresEnabled) {
  88412. var lensFlareSystems = this.scene.lensFlareSystems;
  88413. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88414. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  88415. var lensFlareSystem = lensFlareSystems_2[_i];
  88416. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  88417. lensFlareSystem.render();
  88418. }
  88419. }
  88420. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88421. }
  88422. };
  88423. return LensFlareSystemSceneComponent;
  88424. }());
  88425. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  88426. })(BABYLON || (BABYLON = {}));
  88427. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  88428. var BABYLON;
  88429. (function (BABYLON) {
  88430. var LensFlareSystem = /** @class */ (function () {
  88431. function LensFlareSystem(name, emitter, scene) {
  88432. this.name = name;
  88433. this.lensFlares = new Array();
  88434. this.borderLimit = 300;
  88435. this.viewportBorder = 0;
  88436. this.layerMask = 0x0FFFFFFF;
  88437. this._vertexBuffers = {};
  88438. this._isEnabled = true;
  88439. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88440. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  88441. if (!component) {
  88442. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  88443. scene._addComponent(component);
  88444. }
  88445. this._emitter = emitter;
  88446. this.id = name;
  88447. scene.lensFlareSystems.push(this);
  88448. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  88449. var engine = scene.getEngine();
  88450. // VBO
  88451. var vertices = [];
  88452. vertices.push(1, 1);
  88453. vertices.push(-1, 1);
  88454. vertices.push(-1, -1);
  88455. vertices.push(1, -1);
  88456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88457. // Indices
  88458. var indices = [];
  88459. indices.push(0);
  88460. indices.push(1);
  88461. indices.push(2);
  88462. indices.push(0);
  88463. indices.push(2);
  88464. indices.push(3);
  88465. this._indexBuffer = engine.createIndexBuffer(indices);
  88466. // Effects
  88467. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  88468. }
  88469. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  88470. get: function () {
  88471. return this._isEnabled;
  88472. },
  88473. set: function (value) {
  88474. this._isEnabled = value;
  88475. },
  88476. enumerable: true,
  88477. configurable: true
  88478. });
  88479. LensFlareSystem.prototype.getScene = function () {
  88480. return this._scene;
  88481. };
  88482. LensFlareSystem.prototype.getEmitter = function () {
  88483. return this._emitter;
  88484. };
  88485. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  88486. this._emitter = newEmitter;
  88487. };
  88488. LensFlareSystem.prototype.getEmitterPosition = function () {
  88489. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  88490. };
  88491. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  88492. var position = this.getEmitterPosition();
  88493. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  88494. this._positionX = position.x;
  88495. this._positionY = position.y;
  88496. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  88497. if (this.viewportBorder > 0) {
  88498. globalViewport.x -= this.viewportBorder;
  88499. globalViewport.y -= this.viewportBorder;
  88500. globalViewport.width += this.viewportBorder * 2;
  88501. globalViewport.height += this.viewportBorder * 2;
  88502. position.x += this.viewportBorder;
  88503. position.y += this.viewportBorder;
  88504. this._positionX += this.viewportBorder;
  88505. this._positionY += this.viewportBorder;
  88506. }
  88507. if (position.z > 0) {
  88508. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  88509. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  88510. return true;
  88511. }
  88512. return true;
  88513. }
  88514. return false;
  88515. };
  88516. /** @hidden */
  88517. LensFlareSystem.prototype._isVisible = function () {
  88518. if (!this._isEnabled || !this._scene.activeCamera) {
  88519. return false;
  88520. }
  88521. var emitterPosition = this.getEmitterPosition();
  88522. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  88523. var distance = direction.length();
  88524. direction.normalize();
  88525. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  88526. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  88527. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  88528. };
  88529. LensFlareSystem.prototype.render = function () {
  88530. if (!this._effect.isReady() || !this._scene.activeCamera)
  88531. return false;
  88532. var engine = this._scene.getEngine();
  88533. var viewport = this._scene.activeCamera.viewport;
  88534. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  88535. // Position
  88536. if (!this.computeEffectivePosition(globalViewport)) {
  88537. return false;
  88538. }
  88539. // Visibility
  88540. if (!this._isVisible()) {
  88541. return false;
  88542. }
  88543. // Intensity
  88544. var awayX;
  88545. var awayY;
  88546. if (this._positionX < this.borderLimit + globalViewport.x) {
  88547. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88548. }
  88549. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88550. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88551. }
  88552. else {
  88553. awayX = 0;
  88554. }
  88555. if (this._positionY < this.borderLimit + globalViewport.y) {
  88556. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88557. }
  88558. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88559. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88560. }
  88561. else {
  88562. awayY = 0;
  88563. }
  88564. var away = (awayX > awayY) ? awayX : awayY;
  88565. away -= this.viewportBorder;
  88566. if (away > this.borderLimit) {
  88567. away = this.borderLimit;
  88568. }
  88569. var intensity = 1.0 - (away / this.borderLimit);
  88570. if (intensity < 0) {
  88571. return false;
  88572. }
  88573. if (intensity > 1.0) {
  88574. intensity = 1.0;
  88575. }
  88576. if (this.viewportBorder > 0) {
  88577. globalViewport.x += this.viewportBorder;
  88578. globalViewport.y += this.viewportBorder;
  88579. globalViewport.width -= this.viewportBorder * 2;
  88580. globalViewport.height -= this.viewportBorder * 2;
  88581. this._positionX -= this.viewportBorder;
  88582. this._positionY -= this.viewportBorder;
  88583. }
  88584. // Position
  88585. var centerX = globalViewport.x + globalViewport.width / 2;
  88586. var centerY = globalViewport.y + globalViewport.height / 2;
  88587. var distX = centerX - this._positionX;
  88588. var distY = centerY - this._positionY;
  88589. // Effects
  88590. engine.enableEffect(this._effect);
  88591. engine.setState(false);
  88592. engine.setDepthBuffer(false);
  88593. // VBOs
  88594. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88595. // Flares
  88596. for (var index = 0; index < this.lensFlares.length; index++) {
  88597. var flare = this.lensFlares[index];
  88598. engine.setAlphaMode(flare.alphaMode);
  88599. var x = centerX - (distX * flare.position);
  88600. var y = centerY - (distY * flare.position);
  88601. var cw = flare.size;
  88602. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88603. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88604. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88605. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88606. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88607. // Texture
  88608. this._effect.setTexture("textureSampler", flare.texture);
  88609. // Color
  88610. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88611. // Draw order
  88612. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88613. }
  88614. engine.setDepthBuffer(true);
  88615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88616. return true;
  88617. };
  88618. LensFlareSystem.prototype.dispose = function () {
  88619. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88620. if (vertexBuffer) {
  88621. vertexBuffer.dispose();
  88622. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88623. }
  88624. if (this._indexBuffer) {
  88625. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88626. this._indexBuffer = null;
  88627. }
  88628. while (this.lensFlares.length) {
  88629. this.lensFlares[0].dispose();
  88630. }
  88631. // Remove from scene
  88632. var index = this._scene.lensFlareSystems.indexOf(this);
  88633. this._scene.lensFlareSystems.splice(index, 1);
  88634. };
  88635. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88636. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88637. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88638. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88639. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88640. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88641. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88642. var parsedFlare = parsedLensFlareSystem.flares[index];
  88643. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88644. }
  88645. return lensFlareSystem;
  88646. };
  88647. LensFlareSystem.prototype.serialize = function () {
  88648. var serializationObject = {};
  88649. serializationObject.id = this.id;
  88650. serializationObject.name = this.name;
  88651. serializationObject.emitterId = this.getEmitter().id;
  88652. serializationObject.borderLimit = this.borderLimit;
  88653. serializationObject.flares = [];
  88654. for (var index = 0; index < this.lensFlares.length; index++) {
  88655. var flare = this.lensFlares[index];
  88656. serializationObject.flares.push({
  88657. size: flare.size,
  88658. position: flare.position,
  88659. color: flare.color.asArray(),
  88660. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88661. });
  88662. }
  88663. return serializationObject;
  88664. };
  88665. return LensFlareSystem;
  88666. }());
  88667. BABYLON.LensFlareSystem = LensFlareSystem;
  88668. })(BABYLON || (BABYLON = {}));
  88669. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88670. var BABYLON;
  88671. (function (BABYLON) {
  88672. /**
  88673. * This is a holder class for the physics joint created by the physics plugin.
  88674. * It holds a set of functions to control the underlying joint.
  88675. */
  88676. var PhysicsJoint = /** @class */ (function () {
  88677. function PhysicsJoint(type, jointData) {
  88678. this.type = type;
  88679. this.jointData = jointData;
  88680. jointData.nativeParams = jointData.nativeParams || {};
  88681. }
  88682. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88683. get: function () {
  88684. return this._physicsJoint;
  88685. },
  88686. set: function (newJoint) {
  88687. if (this._physicsJoint) {
  88688. //remove from the wolrd
  88689. }
  88690. this._physicsJoint = newJoint;
  88691. },
  88692. enumerable: true,
  88693. configurable: true
  88694. });
  88695. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88696. set: function (physicsPlugin) {
  88697. this._physicsPlugin = physicsPlugin;
  88698. },
  88699. enumerable: true,
  88700. configurable: true
  88701. });
  88702. /**
  88703. * Execute a function that is physics-plugin specific.
  88704. * @param {Function} func the function that will be executed.
  88705. * It accepts two parameters: the physics world and the physics joint.
  88706. */
  88707. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88708. func(this._physicsPlugin.world, this._physicsJoint);
  88709. };
  88710. //TODO check if the native joints are the same
  88711. //Joint Types
  88712. PhysicsJoint.DistanceJoint = 0;
  88713. PhysicsJoint.HingeJoint = 1;
  88714. PhysicsJoint.BallAndSocketJoint = 2;
  88715. PhysicsJoint.WheelJoint = 3;
  88716. PhysicsJoint.SliderJoint = 4;
  88717. //OIMO
  88718. PhysicsJoint.PrismaticJoint = 5;
  88719. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88720. PhysicsJoint.UniversalJoint = 6;
  88721. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88722. //Cannon
  88723. //Similar to a Ball-Joint. Different in params
  88724. PhysicsJoint.PointToPointJoint = 8;
  88725. //Cannon only at the moment
  88726. PhysicsJoint.SpringJoint = 9;
  88727. PhysicsJoint.LockJoint = 10;
  88728. return PhysicsJoint;
  88729. }());
  88730. BABYLON.PhysicsJoint = PhysicsJoint;
  88731. /**
  88732. * A class representing a physics distance joint.
  88733. */
  88734. var DistanceJoint = /** @class */ (function (_super) {
  88735. __extends(DistanceJoint, _super);
  88736. function DistanceJoint(jointData) {
  88737. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88738. }
  88739. /**
  88740. * Update the predefined distance.
  88741. */
  88742. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88743. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88744. };
  88745. return DistanceJoint;
  88746. }(PhysicsJoint));
  88747. BABYLON.DistanceJoint = DistanceJoint;
  88748. var MotorEnabledJoint = /** @class */ (function (_super) {
  88749. __extends(MotorEnabledJoint, _super);
  88750. function MotorEnabledJoint(type, jointData) {
  88751. return _super.call(this, type, jointData) || this;
  88752. }
  88753. /**
  88754. * Set the motor values.
  88755. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88756. * @param {number} force the force to apply
  88757. * @param {number} maxForce max force for this motor.
  88758. */
  88759. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88760. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88761. };
  88762. /**
  88763. * Set the motor's limits.
  88764. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88765. */
  88766. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88767. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88768. };
  88769. return MotorEnabledJoint;
  88770. }(PhysicsJoint));
  88771. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88772. /**
  88773. * This class represents a single hinge physics joint
  88774. */
  88775. var HingeJoint = /** @class */ (function (_super) {
  88776. __extends(HingeJoint, _super);
  88777. function HingeJoint(jointData) {
  88778. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88779. }
  88780. /**
  88781. * Set the motor values.
  88782. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88783. * @param {number} force the force to apply
  88784. * @param {number} maxForce max force for this motor.
  88785. */
  88786. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88787. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88788. };
  88789. /**
  88790. * Set the motor's limits.
  88791. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88792. */
  88793. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88794. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88795. };
  88796. return HingeJoint;
  88797. }(MotorEnabledJoint));
  88798. BABYLON.HingeJoint = HingeJoint;
  88799. /**
  88800. * This class represents a dual hinge physics joint (same as wheel joint)
  88801. */
  88802. var Hinge2Joint = /** @class */ (function (_super) {
  88803. __extends(Hinge2Joint, _super);
  88804. function Hinge2Joint(jointData) {
  88805. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88806. }
  88807. /**
  88808. * Set the motor values.
  88809. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88810. * @param {number} force the force to apply
  88811. * @param {number} maxForce max force for this motor.
  88812. * @param {motorIndex} the motor's index, 0 or 1.
  88813. */
  88814. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88815. if (motorIndex === void 0) { motorIndex = 0; }
  88816. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88817. };
  88818. /**
  88819. * Set the motor limits.
  88820. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88821. * @param {number} upperLimit the upper limit
  88822. * @param {number} lowerLimit lower limit
  88823. * @param {motorIndex} the motor's index, 0 or 1.
  88824. */
  88825. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88826. if (motorIndex === void 0) { motorIndex = 0; }
  88827. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88828. };
  88829. return Hinge2Joint;
  88830. }(MotorEnabledJoint));
  88831. BABYLON.Hinge2Joint = Hinge2Joint;
  88832. })(BABYLON || (BABYLON = {}));
  88833. //# sourceMappingURL=babylon.physicsJoint.js.map
  88834. var BABYLON;
  88835. (function (BABYLON) {
  88836. var PhysicsImpostor = /** @class */ (function () {
  88837. function PhysicsImpostor(object, type, _options, _scene) {
  88838. if (_options === void 0) { _options = { mass: 0 }; }
  88839. var _this = this;
  88840. this.object = object;
  88841. this.type = type;
  88842. this._options = _options;
  88843. this._scene = _scene;
  88844. this._bodyUpdateRequired = false;
  88845. this._onBeforePhysicsStepCallbacks = new Array();
  88846. this._onAfterPhysicsStepCallbacks = new Array();
  88847. this._onPhysicsCollideCallbacks = [];
  88848. this._deltaPosition = BABYLON.Vector3.Zero();
  88849. this._isDisposed = false;
  88850. //temp variables for parent rotation calculations
  88851. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88852. this._tmpQuat = new BABYLON.Quaternion();
  88853. this._tmpQuat2 = new BABYLON.Quaternion();
  88854. /**
  88855. * this function is executed by the physics engine.
  88856. */
  88857. this.beforeStep = function () {
  88858. if (!_this._physicsEngine) {
  88859. return;
  88860. }
  88861. _this.object.translate(_this._deltaPosition, -1);
  88862. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88863. _this.object.computeWorldMatrix(false);
  88864. if (_this.object.parent && _this.object.rotationQuaternion) {
  88865. _this.getParentsRotation();
  88866. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88867. }
  88868. else {
  88869. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88870. }
  88871. if (!_this._options.disableBidirectionalTransformation) {
  88872. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88873. }
  88874. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88875. func(_this);
  88876. });
  88877. };
  88878. /**
  88879. * this function is executed by the physics engine.
  88880. */
  88881. this.afterStep = function () {
  88882. if (!_this._physicsEngine) {
  88883. return;
  88884. }
  88885. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88886. func(_this);
  88887. });
  88888. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88889. // object has now its world rotation. needs to be converted to local.
  88890. if (_this.object.parent && _this.object.rotationQuaternion) {
  88891. _this.getParentsRotation();
  88892. _this._tmpQuat.conjugateInPlace();
  88893. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88894. }
  88895. // take the position set and make it the absolute position of this object.
  88896. _this.object.setAbsolutePosition(_this.object.position);
  88897. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88898. _this.object.translate(_this._deltaPosition, 1);
  88899. };
  88900. /**
  88901. * Legacy collision detection event support
  88902. */
  88903. this.onCollideEvent = null;
  88904. //event and body object due to cannon's event-based architecture.
  88905. this.onCollide = function (e) {
  88906. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88907. return;
  88908. }
  88909. if (!_this._physicsEngine) {
  88910. return;
  88911. }
  88912. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88913. if (otherImpostor) {
  88914. // Legacy collision detection event support
  88915. if (_this.onCollideEvent) {
  88916. _this.onCollideEvent(_this, otherImpostor);
  88917. }
  88918. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88919. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88920. }).forEach(function (obj) {
  88921. obj.callback(_this, otherImpostor);
  88922. });
  88923. }
  88924. };
  88925. //sanity check!
  88926. if (!this.object) {
  88927. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88928. return;
  88929. }
  88930. //legacy support for old syntax.
  88931. if (!this._scene && object.getScene) {
  88932. this._scene = object.getScene();
  88933. }
  88934. if (!this._scene) {
  88935. return;
  88936. }
  88937. this._physicsEngine = this._scene.getPhysicsEngine();
  88938. if (!this._physicsEngine) {
  88939. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88940. }
  88941. else {
  88942. //set the object's quaternion, if not set
  88943. if (!this.object.rotationQuaternion) {
  88944. if (this.object.rotation) {
  88945. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88946. }
  88947. else {
  88948. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88949. }
  88950. }
  88951. //default options params
  88952. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88953. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88954. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88955. this._joints = [];
  88956. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88957. if (!this.object.parent || this._options.ignoreParent) {
  88958. this._init();
  88959. }
  88960. else if (this.object.parent.physicsImpostor) {
  88961. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88962. }
  88963. }
  88964. }
  88965. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88966. get: function () {
  88967. return this._isDisposed;
  88968. },
  88969. enumerable: true,
  88970. configurable: true
  88971. });
  88972. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88973. get: function () {
  88974. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88975. },
  88976. set: function (value) {
  88977. this.setMass(value);
  88978. },
  88979. enumerable: true,
  88980. configurable: true
  88981. });
  88982. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88983. get: function () {
  88984. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88985. },
  88986. set: function (value) {
  88987. if (!this._physicsEngine) {
  88988. return;
  88989. }
  88990. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88991. },
  88992. enumerable: true,
  88993. configurable: true
  88994. });
  88995. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88996. get: function () {
  88997. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88998. },
  88999. set: function (value) {
  89000. if (!this._physicsEngine) {
  89001. return;
  89002. }
  89003. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  89004. },
  89005. enumerable: true,
  89006. configurable: true
  89007. });
  89008. /**
  89009. * This function will completly initialize this impostor.
  89010. * It will create a new body - but only if this mesh has no parent.
  89011. * If it has, this impostor will not be used other than to define the impostor
  89012. * of the child mesh.
  89013. * @hidden
  89014. */
  89015. PhysicsImpostor.prototype._init = function () {
  89016. if (!this._physicsEngine) {
  89017. return;
  89018. }
  89019. this._physicsEngine.removeImpostor(this);
  89020. this.physicsBody = null;
  89021. this._parent = this._parent || this._getPhysicsParent();
  89022. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  89023. this._physicsEngine.addImpostor(this);
  89024. }
  89025. };
  89026. PhysicsImpostor.prototype._getPhysicsParent = function () {
  89027. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  89028. var parentMesh = this.object.parent;
  89029. return parentMesh.physicsImpostor;
  89030. }
  89031. return null;
  89032. };
  89033. /**
  89034. * Should a new body be generated.
  89035. */
  89036. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  89037. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  89038. };
  89039. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  89040. this.forceUpdate();
  89041. };
  89042. /**
  89043. * Force a regeneration of this or the parent's impostor's body.
  89044. * Use under cautious - This will remove all joints already implemented.
  89045. */
  89046. PhysicsImpostor.prototype.forceUpdate = function () {
  89047. this._init();
  89048. if (this.parent && !this._options.ignoreParent) {
  89049. this.parent.forceUpdate();
  89050. }
  89051. };
  89052. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  89053. /*public get mesh(): AbstractMesh {
  89054. return this._mesh;
  89055. }*/
  89056. /**
  89057. * Gets the body that holds this impostor. Either its own, or its parent.
  89058. */
  89059. get: function () {
  89060. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  89061. },
  89062. /**
  89063. * Set the physics body. Used mainly by the physics engine/plugin
  89064. */
  89065. set: function (physicsBody) {
  89066. if (this._physicsBody && this._physicsEngine) {
  89067. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  89068. }
  89069. this._physicsBody = physicsBody;
  89070. this.resetUpdateFlags();
  89071. },
  89072. enumerable: true,
  89073. configurable: true
  89074. });
  89075. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  89076. get: function () {
  89077. return !this._options.ignoreParent && this._parent ? this._parent : null;
  89078. },
  89079. set: function (value) {
  89080. this._parent = value;
  89081. },
  89082. enumerable: true,
  89083. configurable: true
  89084. });
  89085. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  89086. this._bodyUpdateRequired = false;
  89087. };
  89088. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  89089. if (this.object.getBoundingInfo) {
  89090. var q = this.object.rotationQuaternion;
  89091. //reset rotation
  89092. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  89093. //calculate the world matrix with no rotation
  89094. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  89095. var boundingInfo = this.object.getBoundingInfo();
  89096. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  89097. //bring back the rotation
  89098. this.object.rotationQuaternion = q;
  89099. //calculate the world matrix with the new rotation
  89100. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  89101. return size;
  89102. }
  89103. else {
  89104. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  89105. }
  89106. };
  89107. PhysicsImpostor.prototype.getObjectCenter = function () {
  89108. if (this.object.getBoundingInfo) {
  89109. var boundingInfo = this.object.getBoundingInfo();
  89110. return boundingInfo.boundingBox.centerWorld;
  89111. }
  89112. else {
  89113. return this.object.position;
  89114. }
  89115. };
  89116. /**
  89117. * Get a specific parametes from the options parameter.
  89118. */
  89119. PhysicsImpostor.prototype.getParam = function (paramName) {
  89120. return this._options[paramName];
  89121. };
  89122. /**
  89123. * Sets a specific parameter in the options given to the physics plugin
  89124. */
  89125. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  89126. this._options[paramName] = value;
  89127. this._bodyUpdateRequired = true;
  89128. };
  89129. /**
  89130. * Specifically change the body's mass option. Won't recreate the physics body object
  89131. */
  89132. PhysicsImpostor.prototype.setMass = function (mass) {
  89133. if (this.getParam("mass") !== mass) {
  89134. this.setParam("mass", mass);
  89135. }
  89136. if (this._physicsEngine) {
  89137. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  89138. }
  89139. };
  89140. PhysicsImpostor.prototype.getLinearVelocity = function () {
  89141. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  89142. };
  89143. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  89144. if (this._physicsEngine) {
  89145. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  89146. }
  89147. };
  89148. PhysicsImpostor.prototype.getAngularVelocity = function () {
  89149. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  89150. };
  89151. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  89152. if (this._physicsEngine) {
  89153. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  89154. }
  89155. };
  89156. /**
  89157. * Execute a function with the physics plugin native code.
  89158. * Provide a function the will have two variables - the world object and the physics body object.
  89159. */
  89160. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  89161. if (this._physicsEngine) {
  89162. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  89163. }
  89164. };
  89165. /**
  89166. * Register a function that will be executed before the physics world is stepping forward.
  89167. */
  89168. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  89169. this._onBeforePhysicsStepCallbacks.push(func);
  89170. };
  89171. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  89172. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  89173. if (index > -1) {
  89174. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  89175. }
  89176. else {
  89177. BABYLON.Tools.Warn("Function to remove was not found");
  89178. }
  89179. };
  89180. /**
  89181. * Register a function that will be executed after the physics step
  89182. */
  89183. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  89184. this._onAfterPhysicsStepCallbacks.push(func);
  89185. };
  89186. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  89187. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  89188. if (index > -1) {
  89189. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  89190. }
  89191. else {
  89192. BABYLON.Tools.Warn("Function to remove was not found");
  89193. }
  89194. };
  89195. /**
  89196. * register a function that will be executed when this impostor collides against a different body.
  89197. */
  89198. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  89199. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  89200. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  89201. };
  89202. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  89203. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  89204. var index = -1;
  89205. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  89206. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  89207. // chcek the arrays match
  89208. var sameList = cbDef.otherImpostors.every(function (impostor) {
  89209. return collidedAgainstList.indexOf(impostor) > -1;
  89210. });
  89211. if (sameList) {
  89212. index = idx;
  89213. }
  89214. return sameList;
  89215. }
  89216. return false;
  89217. });
  89218. if (found) {
  89219. this._onPhysicsCollideCallbacks.splice(index, 1);
  89220. }
  89221. else {
  89222. BABYLON.Tools.Warn("Function to remove was not found");
  89223. }
  89224. };
  89225. PhysicsImpostor.prototype.getParentsRotation = function () {
  89226. var parent = this.object.parent;
  89227. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  89228. while (parent) {
  89229. if (parent.rotationQuaternion) {
  89230. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  89231. }
  89232. else {
  89233. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  89234. }
  89235. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  89236. parent = parent.parent;
  89237. }
  89238. return this._tmpQuat;
  89239. };
  89240. /**
  89241. * Apply a force
  89242. */
  89243. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  89244. if (this._physicsEngine) {
  89245. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  89246. }
  89247. return this;
  89248. };
  89249. /**
  89250. * Apply an impulse
  89251. */
  89252. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  89253. if (this._physicsEngine) {
  89254. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  89255. }
  89256. return this;
  89257. };
  89258. /**
  89259. * A help function to create a joint.
  89260. */
  89261. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  89262. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  89263. this.addJoint(otherImpostor, joint);
  89264. return this;
  89265. };
  89266. /**
  89267. * Add a joint to this impostor with a different impostor.
  89268. */
  89269. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  89270. this._joints.push({
  89271. otherImpostor: otherImpostor,
  89272. joint: joint
  89273. });
  89274. if (this._physicsEngine) {
  89275. this._physicsEngine.addJoint(this, otherImpostor, joint);
  89276. }
  89277. return this;
  89278. };
  89279. /**
  89280. * Will keep this body still, in a sleep mode.
  89281. */
  89282. PhysicsImpostor.prototype.sleep = function () {
  89283. if (this._physicsEngine) {
  89284. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  89285. }
  89286. return this;
  89287. };
  89288. /**
  89289. * Wake the body up.
  89290. */
  89291. PhysicsImpostor.prototype.wakeUp = function () {
  89292. if (this._physicsEngine) {
  89293. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  89294. }
  89295. return this;
  89296. };
  89297. PhysicsImpostor.prototype.clone = function (newObject) {
  89298. if (!newObject)
  89299. return null;
  89300. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  89301. };
  89302. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  89303. var _this = this;
  89304. //no dispose if no physics engine is available.
  89305. if (!this._physicsEngine) {
  89306. return;
  89307. }
  89308. this._joints.forEach(function (j) {
  89309. if (_this._physicsEngine) {
  89310. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  89311. }
  89312. });
  89313. //dispose the physics body
  89314. this._physicsEngine.removeImpostor(this);
  89315. if (this.parent) {
  89316. this.parent.forceUpdate();
  89317. }
  89318. else {
  89319. /*this._object.getChildMeshes().forEach(function(mesh) {
  89320. if (mesh.physicsImpostor) {
  89321. if (disposeChildren) {
  89322. mesh.physicsImpostor.dispose();
  89323. mesh.physicsImpostor = null;
  89324. }
  89325. }
  89326. })*/
  89327. }
  89328. this._isDisposed = true;
  89329. };
  89330. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  89331. this._deltaPosition.copyFrom(position);
  89332. };
  89333. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  89334. if (!this._deltaRotation) {
  89335. this._deltaRotation = new BABYLON.Quaternion();
  89336. }
  89337. this._deltaRotation.copyFrom(rotation);
  89338. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  89339. };
  89340. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  89341. if (this._physicsEngine) {
  89342. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  89343. }
  89344. return this;
  89345. };
  89346. PhysicsImpostor.prototype.getRadius = function () {
  89347. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  89348. };
  89349. /**
  89350. * Sync a bone with this impostor
  89351. * @param bone The bone to sync to the impostor.
  89352. * @param boneMesh The mesh that the bone is influencing.
  89353. * @param jointPivot The pivot of the joint / bone in local space.
  89354. * @param distToJoint Optional distance from the impostor to the joint.
  89355. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89356. */
  89357. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  89358. var tempVec = PhysicsImpostor._tmpVecs[0];
  89359. var mesh = this.object;
  89360. if (mesh.rotationQuaternion) {
  89361. if (adjustRotation) {
  89362. var tempQuat = PhysicsImpostor._tmpQuat;
  89363. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  89364. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  89365. }
  89366. else {
  89367. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  89368. }
  89369. }
  89370. tempVec.x = 0;
  89371. tempVec.y = 0;
  89372. tempVec.z = 0;
  89373. if (jointPivot) {
  89374. tempVec.x = jointPivot.x;
  89375. tempVec.y = jointPivot.y;
  89376. tempVec.z = jointPivot.z;
  89377. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  89378. if (distToJoint === undefined || distToJoint === null) {
  89379. distToJoint = jointPivot.length();
  89380. }
  89381. tempVec.x *= distToJoint;
  89382. tempVec.y *= distToJoint;
  89383. tempVec.z *= distToJoint;
  89384. }
  89385. if (bone.getParent()) {
  89386. tempVec.addInPlace(mesh.getAbsolutePosition());
  89387. bone.setAbsolutePosition(tempVec, boneMesh);
  89388. }
  89389. else {
  89390. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  89391. boneMesh.position.x -= tempVec.x;
  89392. boneMesh.position.y -= tempVec.y;
  89393. boneMesh.position.z -= tempVec.z;
  89394. }
  89395. };
  89396. /**
  89397. * Sync impostor to a bone
  89398. * @param bone The bone that the impostor will be synced to.
  89399. * @param boneMesh The mesh that the bone is influencing.
  89400. * @param jointPivot The pivot of the joint / bone in local space.
  89401. * @param distToJoint Optional distance from the impostor to the joint.
  89402. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89403. * @param boneAxis Optional vector3 axis the bone is aligned with
  89404. */
  89405. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  89406. var mesh = this.object;
  89407. if (mesh.rotationQuaternion) {
  89408. if (adjustRotation) {
  89409. var tempQuat = PhysicsImpostor._tmpQuat;
  89410. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  89411. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  89412. }
  89413. else {
  89414. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  89415. }
  89416. }
  89417. var pos = PhysicsImpostor._tmpVecs[0];
  89418. var boneDir = PhysicsImpostor._tmpVecs[1];
  89419. if (!boneAxis) {
  89420. boneAxis = PhysicsImpostor._tmpVecs[2];
  89421. boneAxis.x = 0;
  89422. boneAxis.y = 1;
  89423. boneAxis.z = 0;
  89424. }
  89425. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  89426. bone.getAbsolutePositionToRef(boneMesh, pos);
  89427. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  89428. distToJoint = jointPivot.length();
  89429. }
  89430. if (distToJoint !== undefined && distToJoint !== null) {
  89431. pos.x += boneDir.x * distToJoint;
  89432. pos.y += boneDir.y * distToJoint;
  89433. pos.z += boneDir.z * distToJoint;
  89434. }
  89435. mesh.setAbsolutePosition(pos);
  89436. };
  89437. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  89438. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  89439. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89440. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  89441. //Impostor types
  89442. PhysicsImpostor.NoImpostor = 0;
  89443. PhysicsImpostor.SphereImpostor = 1;
  89444. PhysicsImpostor.BoxImpostor = 2;
  89445. PhysicsImpostor.PlaneImpostor = 3;
  89446. PhysicsImpostor.MeshImpostor = 4;
  89447. PhysicsImpostor.CylinderImpostor = 7;
  89448. PhysicsImpostor.ParticleImpostor = 8;
  89449. PhysicsImpostor.HeightmapImpostor = 9;
  89450. return PhysicsImpostor;
  89451. }());
  89452. BABYLON.PhysicsImpostor = PhysicsImpostor;
  89453. })(BABYLON || (BABYLON = {}));
  89454. //# sourceMappingURL=babylon.physicsImpostor.js.map
  89455. var BABYLON;
  89456. (function (BABYLON) {
  89457. /**
  89458. * Class used to control physics engine
  89459. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  89460. */
  89461. var PhysicsEngine = /** @class */ (function () {
  89462. /**
  89463. * Creates a new Physics Engine
  89464. * @param gravity defines the gravity vector used by the simulation
  89465. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  89466. */
  89467. function PhysicsEngine(gravity, _physicsPlugin) {
  89468. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  89469. this._physicsPlugin = _physicsPlugin;
  89470. this._impostors = [];
  89471. this._joints = [];
  89472. if (!this._physicsPlugin.isSupported()) {
  89473. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  89474. + "Please make sure it is included.");
  89475. }
  89476. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  89477. this.setGravity(gravity);
  89478. this.setTimeStep();
  89479. }
  89480. /**
  89481. * Sets the gravity vector used by the simulation
  89482. * @param gravity defines the gravity vector to use
  89483. */
  89484. PhysicsEngine.prototype.setGravity = function (gravity) {
  89485. this.gravity = gravity;
  89486. this._physicsPlugin.setGravity(this.gravity);
  89487. };
  89488. /**
  89489. * Set the time step of the physics engine.
  89490. * Default is 1/60.
  89491. * To slow it down, enter 1/600 for example.
  89492. * To speed it up, 1/30
  89493. * @param newTimeStep defines the new timestep to apply to this world.
  89494. */
  89495. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  89496. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  89497. this._physicsPlugin.setTimeStep(newTimeStep);
  89498. };
  89499. /**
  89500. * Get the time step of the physics engine.
  89501. * @returns the current time step
  89502. */
  89503. PhysicsEngine.prototype.getTimeStep = function () {
  89504. return this._physicsPlugin.getTimeStep();
  89505. };
  89506. /**
  89507. * Release all resources
  89508. */
  89509. PhysicsEngine.prototype.dispose = function () {
  89510. this._impostors.forEach(function (impostor) {
  89511. impostor.dispose();
  89512. });
  89513. this._physicsPlugin.dispose();
  89514. };
  89515. /**
  89516. * Gets the name of the current physics plugin
  89517. * @returns the name of the plugin
  89518. */
  89519. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  89520. return this._physicsPlugin.name;
  89521. };
  89522. /**
  89523. * Adding a new impostor for the impostor tracking.
  89524. * This will be done by the impostor itself.
  89525. * @param impostor the impostor to add
  89526. */
  89527. PhysicsEngine.prototype.addImpostor = function (impostor) {
  89528. impostor.uniqueId = this._impostors.push(impostor);
  89529. //if no parent, generate the body
  89530. if (!impostor.parent) {
  89531. this._physicsPlugin.generatePhysicsBody(impostor);
  89532. }
  89533. };
  89534. /**
  89535. * Remove an impostor from the engine.
  89536. * This impostor and its mesh will not longer be updated by the physics engine.
  89537. * @param impostor the impostor to remove
  89538. */
  89539. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  89540. var index = this._impostors.indexOf(impostor);
  89541. if (index > -1) {
  89542. var removed = this._impostors.splice(index, 1);
  89543. //Is it needed?
  89544. if (removed.length) {
  89545. //this will also remove it from the world.
  89546. removed[0].physicsBody = null;
  89547. }
  89548. }
  89549. };
  89550. /**
  89551. * Add a joint to the physics engine
  89552. * @param mainImpostor defines the main impostor to which the joint is added.
  89553. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  89554. * @param joint defines the joint that will connect both impostors.
  89555. */
  89556. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  89557. var impostorJoint = {
  89558. mainImpostor: mainImpostor,
  89559. connectedImpostor: connectedImpostor,
  89560. joint: joint
  89561. };
  89562. joint.physicsPlugin = this._physicsPlugin;
  89563. this._joints.push(impostorJoint);
  89564. this._physicsPlugin.generateJoint(impostorJoint);
  89565. };
  89566. /**
  89567. * Removes a joint from the simulation
  89568. * @param mainImpostor defines the impostor used with the joint
  89569. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  89570. * @param joint defines the joint to remove
  89571. */
  89572. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  89573. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89574. return (impostorJoint.connectedImpostor === connectedImpostor
  89575. && impostorJoint.joint === joint
  89576. && impostorJoint.mainImpostor === mainImpostor);
  89577. });
  89578. if (matchingJoints.length) {
  89579. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89580. //TODO remove it from the list as well
  89581. }
  89582. };
  89583. /**
  89584. * Called by the scene. No need to call it.
  89585. * @param delta defines the timespam between frames
  89586. */
  89587. PhysicsEngine.prototype._step = function (delta) {
  89588. var _this = this;
  89589. //check if any mesh has no body / requires an update
  89590. this._impostors.forEach(function (impostor) {
  89591. if (impostor.isBodyInitRequired()) {
  89592. _this._physicsPlugin.generatePhysicsBody(impostor);
  89593. }
  89594. });
  89595. if (delta > 0.1) {
  89596. delta = 0.1;
  89597. }
  89598. else if (delta <= 0) {
  89599. delta = 1.0 / 60.0;
  89600. }
  89601. this._physicsPlugin.executeStep(delta, this._impostors);
  89602. };
  89603. /**
  89604. * Gets the current plugin used to run the simulation
  89605. * @returns current plugin
  89606. */
  89607. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89608. return this._physicsPlugin;
  89609. };
  89610. /**
  89611. * Gets the list of physic impostors
  89612. * @returns an array of PhysicsImpostor
  89613. */
  89614. PhysicsEngine.prototype.getImpostors = function () {
  89615. return this._impostors;
  89616. };
  89617. /**
  89618. * Gets the impostor for a physics enabled object
  89619. * @param object defines the object impersonated by the impostor
  89620. * @returns the PhysicsImpostor or null if not found
  89621. */
  89622. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89623. for (var i = 0; i < this._impostors.length; ++i) {
  89624. if (this._impostors[i].object === object) {
  89625. return this._impostors[i];
  89626. }
  89627. }
  89628. return null;
  89629. };
  89630. /**
  89631. * Gets the impostor for a physics body object
  89632. * @param body defines physics body used by the impostor
  89633. * @returns the PhysicsImpostor or null if not found
  89634. */
  89635. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89636. for (var i = 0; i < this._impostors.length; ++i) {
  89637. if (this._impostors[i].physicsBody === body) {
  89638. return this._impostors[i];
  89639. }
  89640. }
  89641. return null;
  89642. };
  89643. /**
  89644. * Global value used to control the smallest number supported by the simulation
  89645. */
  89646. PhysicsEngine.Epsilon = 0.001;
  89647. return PhysicsEngine;
  89648. }());
  89649. BABYLON.PhysicsEngine = PhysicsEngine;
  89650. })(BABYLON || (BABYLON = {}));
  89651. //# sourceMappingURL=babylon.physicsEngine.js.map
  89652. var BABYLON;
  89653. (function (BABYLON) {
  89654. var PhysicsHelper = /** @class */ (function () {
  89655. function PhysicsHelper(scene) {
  89656. this._scene = scene;
  89657. this._physicsEngine = this._scene.getPhysicsEngine();
  89658. if (!this._physicsEngine) {
  89659. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89660. }
  89661. }
  89662. /**
  89663. * @param {Vector3} origin the origin of the explosion
  89664. * @param {number} radius the explosion radius
  89665. * @param {number} strength the explosion strength
  89666. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89667. */
  89668. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89669. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89670. if (!this._physicsEngine) {
  89671. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89672. return null;
  89673. }
  89674. var impostors = this._physicsEngine.getImpostors();
  89675. if (impostors.length === 0) {
  89676. return null;
  89677. }
  89678. var event = new PhysicsRadialExplosionEvent(this._scene);
  89679. impostors.forEach(function (impostor) {
  89680. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89681. if (!impostorForceAndContactPoint) {
  89682. return;
  89683. }
  89684. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89685. });
  89686. event.dispose(false);
  89687. return event;
  89688. };
  89689. /**
  89690. * @param {Vector3} origin the origin of the explosion
  89691. * @param {number} radius the explosion radius
  89692. * @param {number} strength the explosion strength
  89693. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89694. */
  89695. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89696. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89697. if (!this._physicsEngine) {
  89698. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89699. return null;
  89700. }
  89701. var impostors = this._physicsEngine.getImpostors();
  89702. if (impostors.length === 0) {
  89703. return null;
  89704. }
  89705. var event = new PhysicsRadialExplosionEvent(this._scene);
  89706. impostors.forEach(function (impostor) {
  89707. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89708. if (!impostorForceAndContactPoint) {
  89709. return;
  89710. }
  89711. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89712. });
  89713. event.dispose(false);
  89714. return event;
  89715. };
  89716. /**
  89717. * @param {Vector3} origin the origin of the explosion
  89718. * @param {number} radius the explosion radius
  89719. * @param {number} strength the explosion strength
  89720. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89721. */
  89722. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89723. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89724. if (!this._physicsEngine) {
  89725. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89726. return null;
  89727. }
  89728. var impostors = this._physicsEngine.getImpostors();
  89729. if (impostors.length === 0) {
  89730. return null;
  89731. }
  89732. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89733. event.dispose(false);
  89734. return event;
  89735. };
  89736. /**
  89737. * @param {Vector3} origin the origin of the updraft
  89738. * @param {number} radius the radius of the updraft
  89739. * @param {number} strength the strength of the updraft
  89740. * @param {number} height the height of the updraft
  89741. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89742. */
  89743. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89744. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89745. if (!this._physicsEngine) {
  89746. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89747. return null;
  89748. }
  89749. if (this._physicsEngine.getImpostors().length === 0) {
  89750. return null;
  89751. }
  89752. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89753. event.dispose(false);
  89754. return event;
  89755. };
  89756. /**
  89757. * @param {Vector3} origin the of the vortex
  89758. * @param {number} radius the radius of the vortex
  89759. * @param {number} strength the strength of the vortex
  89760. * @param {number} height the height of the vortex
  89761. */
  89762. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89763. if (!this._physicsEngine) {
  89764. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89765. return null;
  89766. }
  89767. if (this._physicsEngine.getImpostors().length === 0) {
  89768. return null;
  89769. }
  89770. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89771. event.dispose(false);
  89772. return event;
  89773. };
  89774. return PhysicsHelper;
  89775. }());
  89776. BABYLON.PhysicsHelper = PhysicsHelper;
  89777. /***** Radial explosion *****/
  89778. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89779. function PhysicsRadialExplosionEvent(scene) {
  89780. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89781. this._rays = [];
  89782. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89783. this._scene = scene;
  89784. }
  89785. /**
  89786. * Returns the data related to the radial explosion event (sphere & rays).
  89787. * @returns {PhysicsRadialExplosionEventData}
  89788. */
  89789. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89790. this._dataFetched = true;
  89791. return {
  89792. sphere: this._sphere,
  89793. rays: this._rays,
  89794. };
  89795. };
  89796. /**
  89797. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89798. * @param impostor
  89799. * @param {Vector3} origin the origin of the explosion
  89800. * @param {number} radius the explosion radius
  89801. * @param {number} strength the explosion strength
  89802. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89803. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89804. */
  89805. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89806. if (impostor.mass === 0) {
  89807. return null;
  89808. }
  89809. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89810. return null;
  89811. }
  89812. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89813. return null;
  89814. }
  89815. var impostorObjectCenter = impostor.getObjectCenter();
  89816. var direction = impostorObjectCenter.subtract(origin);
  89817. var ray = new BABYLON.Ray(origin, direction, radius);
  89818. this._rays.push(ray);
  89819. var hit = ray.intersectsMesh(impostor.object);
  89820. var contactPoint = hit.pickedPoint;
  89821. if (!contactPoint) {
  89822. return null;
  89823. }
  89824. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89825. if (distanceFromOrigin > radius) {
  89826. return null;
  89827. }
  89828. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89829. ? strength
  89830. : strength * (1 - (distanceFromOrigin / radius));
  89831. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89832. return { force: force, contactPoint: contactPoint };
  89833. };
  89834. /**
  89835. * Disposes the sphere.
  89836. * @param {bolean} force
  89837. */
  89838. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89839. var _this = this;
  89840. if (force === void 0) { force = true; }
  89841. if (force) {
  89842. this._sphere.dispose();
  89843. }
  89844. else {
  89845. setTimeout(function () {
  89846. if (!_this._dataFetched) {
  89847. _this._sphere.dispose();
  89848. }
  89849. }, 0);
  89850. }
  89851. };
  89852. /*** Helpers ***/
  89853. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89854. if (!this._sphere) {
  89855. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89856. this._sphere.isVisible = false;
  89857. }
  89858. };
  89859. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89860. var impostorObject = impostor.object;
  89861. this._prepareSphere();
  89862. this._sphere.position = origin;
  89863. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89864. this._sphere._updateBoundingInfo();
  89865. this._sphere.computeWorldMatrix(true);
  89866. return this._sphere.intersectsMesh(impostorObject, true);
  89867. };
  89868. return PhysicsRadialExplosionEvent;
  89869. }());
  89870. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89871. /***** Gravitational Field *****/
  89872. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89873. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89874. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89875. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89876. this._physicsHelper = physicsHelper;
  89877. this._scene = scene;
  89878. this._origin = origin;
  89879. this._radius = radius;
  89880. this._strength = strength;
  89881. this._falloff = falloff;
  89882. this._tickCallback = this._tick.bind(this);
  89883. }
  89884. /**
  89885. * Returns the data related to the gravitational field event (sphere).
  89886. * @returns {PhysicsGravitationalFieldEventData}
  89887. */
  89888. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89889. this._dataFetched = true;
  89890. return {
  89891. sphere: this._sphere,
  89892. };
  89893. };
  89894. /**
  89895. * Enables the gravitational field.
  89896. */
  89897. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89898. this._tickCallback.call(this);
  89899. this._scene.registerBeforeRender(this._tickCallback);
  89900. };
  89901. /**
  89902. * Disables the gravitational field.
  89903. */
  89904. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89905. this._scene.unregisterBeforeRender(this._tickCallback);
  89906. };
  89907. /**
  89908. * Disposes the sphere.
  89909. * @param {bolean} force
  89910. */
  89911. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89912. var _this = this;
  89913. if (force === void 0) { force = true; }
  89914. if (force) {
  89915. this._sphere.dispose();
  89916. }
  89917. else {
  89918. setTimeout(function () {
  89919. if (!_this._dataFetched) {
  89920. _this._sphere.dispose();
  89921. }
  89922. }, 0);
  89923. }
  89924. };
  89925. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89926. // Since the params won't change, we fetch the event only once
  89927. if (this._sphere) {
  89928. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89929. }
  89930. else {
  89931. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89932. if (radialExplosionEvent) {
  89933. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89934. }
  89935. }
  89936. };
  89937. return PhysicsGravitationalFieldEvent;
  89938. }());
  89939. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89940. /***** Updraft *****/
  89941. var PhysicsUpdraftEvent = /** @class */ (function () {
  89942. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89943. this._scene = _scene;
  89944. this._origin = _origin;
  89945. this._radius = _radius;
  89946. this._strength = _strength;
  89947. this._height = _height;
  89948. this._updraftMode = _updraftMode;
  89949. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89950. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89951. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89952. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89953. this._physicsEngine = this._scene.getPhysicsEngine();
  89954. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89955. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89956. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89957. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89958. }
  89959. this._tickCallback = this._tick.bind(this);
  89960. }
  89961. /**
  89962. * Returns the data related to the updraft event (cylinder).
  89963. * @returns {PhysicsUpdraftEventData}
  89964. */
  89965. PhysicsUpdraftEvent.prototype.getData = function () {
  89966. this._dataFetched = true;
  89967. return {
  89968. cylinder: this._cylinder,
  89969. };
  89970. };
  89971. /**
  89972. * Enables the updraft.
  89973. */
  89974. PhysicsUpdraftEvent.prototype.enable = function () {
  89975. this._tickCallback.call(this);
  89976. this._scene.registerBeforeRender(this._tickCallback);
  89977. };
  89978. /**
  89979. * Disables the cortex.
  89980. */
  89981. PhysicsUpdraftEvent.prototype.disable = function () {
  89982. this._scene.unregisterBeforeRender(this._tickCallback);
  89983. };
  89984. /**
  89985. * Disposes the sphere.
  89986. * @param {bolean} force
  89987. */
  89988. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89989. var _this = this;
  89990. if (force === void 0) { force = true; }
  89991. if (force) {
  89992. this._cylinder.dispose();
  89993. }
  89994. else {
  89995. setTimeout(function () {
  89996. if (!_this._dataFetched) {
  89997. _this._cylinder.dispose();
  89998. }
  89999. }, 0);
  90000. }
  90001. };
  90002. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  90003. if (impostor.mass === 0) {
  90004. return null;
  90005. }
  90006. if (!this._intersectsWithCylinder(impostor)) {
  90007. return null;
  90008. }
  90009. var impostorObjectCenter = impostor.getObjectCenter();
  90010. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  90011. var direction = this._originDirection;
  90012. }
  90013. else {
  90014. var direction = impostorObjectCenter.subtract(this._originTop);
  90015. }
  90016. var multiplier = this._strength * -1;
  90017. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  90018. return { force: force, contactPoint: impostorObjectCenter };
  90019. };
  90020. PhysicsUpdraftEvent.prototype._tick = function () {
  90021. var _this = this;
  90022. this._physicsEngine.getImpostors().forEach(function (impostor) {
  90023. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  90024. if (!impostorForceAndContactPoint) {
  90025. return;
  90026. }
  90027. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90028. });
  90029. };
  90030. /*** Helpers ***/
  90031. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  90032. if (!this._cylinder) {
  90033. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  90034. height: this._height,
  90035. diameter: this._radius * 2,
  90036. }, this._scene);
  90037. this._cylinder.isVisible = false;
  90038. }
  90039. };
  90040. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  90041. var impostorObject = impostor.object;
  90042. this._prepareCylinder();
  90043. this._cylinder.position = this._cylinderPosition;
  90044. return this._cylinder.intersectsMesh(impostorObject, true);
  90045. };
  90046. return PhysicsUpdraftEvent;
  90047. }());
  90048. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  90049. /***** Vortex *****/
  90050. var PhysicsVortexEvent = /** @class */ (function () {
  90051. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  90052. this._scene = _scene;
  90053. this._origin = _origin;
  90054. this._radius = _radius;
  90055. this._strength = _strength;
  90056. this._height = _height;
  90057. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  90058. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  90059. this._updraftMultiplier = 0.02;
  90060. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  90061. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  90062. this._physicsEngine = this._scene.getPhysicsEngine();
  90063. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  90064. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  90065. this._tickCallback = this._tick.bind(this);
  90066. }
  90067. /**
  90068. * Returns the data related to the vortex event (cylinder).
  90069. * @returns {PhysicsVortexEventData}
  90070. */
  90071. PhysicsVortexEvent.prototype.getData = function () {
  90072. this._dataFetched = true;
  90073. return {
  90074. cylinder: this._cylinder,
  90075. };
  90076. };
  90077. /**
  90078. * Enables the vortex.
  90079. */
  90080. PhysicsVortexEvent.prototype.enable = function () {
  90081. this._tickCallback.call(this);
  90082. this._scene.registerBeforeRender(this._tickCallback);
  90083. };
  90084. /**
  90085. * Disables the cortex.
  90086. */
  90087. PhysicsVortexEvent.prototype.disable = function () {
  90088. this._scene.unregisterBeforeRender(this._tickCallback);
  90089. };
  90090. /**
  90091. * Disposes the sphere.
  90092. * @param {bolean} force
  90093. */
  90094. PhysicsVortexEvent.prototype.dispose = function (force) {
  90095. var _this = this;
  90096. if (force === void 0) { force = true; }
  90097. if (force) {
  90098. this._cylinder.dispose();
  90099. }
  90100. else {
  90101. setTimeout(function () {
  90102. if (!_this._dataFetched) {
  90103. _this._cylinder.dispose();
  90104. }
  90105. }, 0);
  90106. }
  90107. };
  90108. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  90109. if (impostor.mass === 0) {
  90110. return null;
  90111. }
  90112. if (!this._intersectsWithCylinder(impostor)) {
  90113. return null;
  90114. }
  90115. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  90116. return null;
  90117. }
  90118. var impostorObjectCenter = impostor.getObjectCenter();
  90119. 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)
  90120. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  90121. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  90122. var hit = ray.intersectsMesh(impostor.object);
  90123. var contactPoint = hit.pickedPoint;
  90124. if (!contactPoint) {
  90125. return null;
  90126. }
  90127. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  90128. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  90129. var directionToOrigin = contactPoint.normalize();
  90130. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  90131. directionToOrigin = directionToOrigin.negate();
  90132. }
  90133. // TODO: find a more physically based solution
  90134. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  90135. var forceX = directionToOrigin.x * this._strength / 8;
  90136. var forceY = directionToOrigin.y * this._updraftMultiplier;
  90137. var forceZ = directionToOrigin.z * this._strength / 8;
  90138. }
  90139. else {
  90140. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  90141. var forceY = this._originTop.y * this._updraftMultiplier;
  90142. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  90143. }
  90144. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  90145. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  90146. return { force: force, contactPoint: impostorObjectCenter };
  90147. };
  90148. PhysicsVortexEvent.prototype._tick = function () {
  90149. var _this = this;
  90150. this._physicsEngine.getImpostors().forEach(function (impostor) {
  90151. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  90152. if (!impostorForceAndContactPoint) {
  90153. return;
  90154. }
  90155. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90156. });
  90157. };
  90158. /*** Helpers ***/
  90159. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  90160. if (!this._cylinder) {
  90161. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  90162. height: this._height,
  90163. diameter: this._radius * 2,
  90164. }, this._scene);
  90165. this._cylinder.isVisible = false;
  90166. }
  90167. };
  90168. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  90169. var impostorObject = impostor.object;
  90170. this._prepareCylinder();
  90171. this._cylinder.position = this._cylinderPosition;
  90172. return this._cylinder.intersectsMesh(impostorObject, true);
  90173. };
  90174. return PhysicsVortexEvent;
  90175. }());
  90176. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  90177. /***** Enums *****/
  90178. /**
  90179. * The strenght of the force in correspondence to the distance of the affected object
  90180. */
  90181. var PhysicsRadialImpulseFalloff;
  90182. (function (PhysicsRadialImpulseFalloff) {
  90183. /** Defines that impulse is constant in strength across it's whole radius */
  90184. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  90185. /** DEfines that impulse gets weaker if it's further from the origin */
  90186. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  90187. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  90188. /**
  90189. * The strenght of the force in correspondence to the distance of the affected object
  90190. */
  90191. var PhysicsUpdraftMode;
  90192. (function (PhysicsUpdraftMode) {
  90193. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  90194. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  90195. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  90196. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  90197. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  90198. })(BABYLON || (BABYLON = {}));
  90199. //# sourceMappingURL=babylon.physicsHelper.js.map
  90200. var BABYLON;
  90201. (function (BABYLON) {
  90202. var CannonJSPlugin = /** @class */ (function () {
  90203. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  90204. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  90205. if (iterations === void 0) { iterations = 10; }
  90206. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  90207. this.name = "CannonJSPlugin";
  90208. this._physicsMaterials = new Array();
  90209. this._fixedTimeStep = 1 / 60;
  90210. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  90211. this.BJSCANNON = CANNON;
  90212. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  90213. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  90214. this._tmpPosition = BABYLON.Vector3.Zero();
  90215. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  90216. this._tmpUnityRotation = new BABYLON.Quaternion();
  90217. if (!this.isSupported()) {
  90218. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  90219. return;
  90220. }
  90221. this._extendNamespace();
  90222. this.world = new this.BJSCANNON.World();
  90223. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  90224. this.world.solver.iterations = iterations;
  90225. }
  90226. CannonJSPlugin.prototype.setGravity = function (gravity) {
  90227. this.world.gravity.copy(gravity);
  90228. };
  90229. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  90230. this._fixedTimeStep = timeStep;
  90231. };
  90232. CannonJSPlugin.prototype.getTimeStep = function () {
  90233. return this._fixedTimeStep;
  90234. };
  90235. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  90236. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  90237. };
  90238. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90239. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  90240. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  90241. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  90242. };
  90243. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90244. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  90245. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  90246. impostor.physicsBody.applyForce(impulse, worldPoint);
  90247. };
  90248. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90249. //parent-child relationship. Does this impostor has a parent impostor?
  90250. if (impostor.parent) {
  90251. if (impostor.physicsBody) {
  90252. this.removePhysicsBody(impostor);
  90253. //TODO is that needed?
  90254. impostor.forceUpdate();
  90255. }
  90256. return;
  90257. }
  90258. //should a new body be created for this impostor?
  90259. if (impostor.isBodyInitRequired()) {
  90260. var shape = this._createShape(impostor);
  90261. //unregister events, if body is being changed
  90262. var oldBody = impostor.physicsBody;
  90263. if (oldBody) {
  90264. this.removePhysicsBody(impostor);
  90265. }
  90266. //create the body and material
  90267. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  90268. var bodyCreationObject = {
  90269. mass: impostor.getParam("mass"),
  90270. material: material
  90271. };
  90272. // A simple extend, in case native options were used.
  90273. var nativeOptions = impostor.getParam("nativeOptions");
  90274. for (var key in nativeOptions) {
  90275. if (nativeOptions.hasOwnProperty(key)) {
  90276. bodyCreationObject[key] = nativeOptions[key];
  90277. }
  90278. }
  90279. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  90280. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  90281. this.world.addEventListener("preStep", impostor.beforeStep);
  90282. this.world.addEventListener("postStep", impostor.afterStep);
  90283. impostor.physicsBody.addShape(shape);
  90284. this.world.add(impostor.physicsBody);
  90285. //try to keep the body moving in the right direction by taking old properties.
  90286. //Should be tested!
  90287. if (oldBody) {
  90288. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  90289. impostor.physicsBody[param].copy(oldBody[param]);
  90290. });
  90291. }
  90292. this._processChildMeshes(impostor);
  90293. }
  90294. //now update the body's transformation
  90295. this._updatePhysicsBodyTransformation(impostor);
  90296. };
  90297. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  90298. var _this = this;
  90299. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  90300. var currentRotation = mainImpostor.object.rotationQuaternion;
  90301. if (meshChildren.length) {
  90302. var processMesh = function (localPosition, mesh) {
  90303. if (!currentRotation || !mesh.rotationQuaternion) {
  90304. return;
  90305. }
  90306. var childImpostor = mesh.getPhysicsImpostor();
  90307. if (childImpostor) {
  90308. var parent = childImpostor.parent;
  90309. if (parent !== mainImpostor) {
  90310. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  90311. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  90312. if (childImpostor.physicsBody) {
  90313. _this.removePhysicsBody(childImpostor);
  90314. childImpostor.physicsBody = null;
  90315. }
  90316. childImpostor.parent = mainImpostor;
  90317. childImpostor.resetUpdateFlags();
  90318. 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));
  90319. //Add the mass of the children.
  90320. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  90321. }
  90322. }
  90323. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  90324. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  90325. };
  90326. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  90327. }
  90328. };
  90329. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90330. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  90331. this.world.removeEventListener("preStep", impostor.beforeStep);
  90332. this.world.removeEventListener("postStep", impostor.afterStep);
  90333. this.world.remove(impostor.physicsBody);
  90334. };
  90335. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90336. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90337. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90338. if (!mainBody || !connectedBody) {
  90339. return;
  90340. }
  90341. var constraint;
  90342. var jointData = impostorJoint.joint.jointData;
  90343. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  90344. var constraintData = {
  90345. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  90346. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  90347. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  90348. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  90349. maxForce: jointData.nativeParams.maxForce,
  90350. collideConnected: !!jointData.collision
  90351. };
  90352. switch (impostorJoint.joint.type) {
  90353. case BABYLON.PhysicsJoint.HingeJoint:
  90354. case BABYLON.PhysicsJoint.Hinge2Joint:
  90355. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  90356. break;
  90357. case BABYLON.PhysicsJoint.DistanceJoint:
  90358. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  90359. break;
  90360. case BABYLON.PhysicsJoint.SpringJoint:
  90361. var springData = jointData;
  90362. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  90363. restLength: springData.length,
  90364. stiffness: springData.stiffness,
  90365. damping: springData.damping,
  90366. localAnchorA: constraintData.pivotA,
  90367. localAnchorB: constraintData.pivotB
  90368. });
  90369. break;
  90370. case BABYLON.PhysicsJoint.LockJoint:
  90371. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  90372. break;
  90373. case BABYLON.PhysicsJoint.PointToPointJoint:
  90374. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90375. default:
  90376. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  90377. break;
  90378. }
  90379. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  90380. constraint.collideConnected = !!jointData.collision;
  90381. impostorJoint.joint.physicsJoint = constraint;
  90382. //don't add spring as constraint, as it is not one.
  90383. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90384. this.world.addConstraint(constraint);
  90385. }
  90386. else {
  90387. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  90388. constraint.applyForce();
  90389. };
  90390. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90391. }
  90392. };
  90393. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90394. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90395. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  90396. }
  90397. else {
  90398. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90399. }
  90400. };
  90401. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  90402. var index;
  90403. var mat;
  90404. for (index = 0; index < this._physicsMaterials.length; index++) {
  90405. mat = this._physicsMaterials[index];
  90406. if (mat.friction === friction && mat.restitution === restitution) {
  90407. return mat;
  90408. }
  90409. }
  90410. var currentMat = new this.BJSCANNON.Material(name);
  90411. currentMat.friction = friction;
  90412. currentMat.restitution = restitution;
  90413. this._physicsMaterials.push(currentMat);
  90414. return currentMat;
  90415. };
  90416. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  90417. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  90418. };
  90419. CannonJSPlugin.prototype._createShape = function (impostor) {
  90420. var object = impostor.object;
  90421. var returnValue;
  90422. var extendSize = impostor.getObjectExtendSize();
  90423. switch (impostor.type) {
  90424. case BABYLON.PhysicsImpostor.SphereImpostor:
  90425. var radiusX = extendSize.x;
  90426. var radiusY = extendSize.y;
  90427. var radiusZ = extendSize.z;
  90428. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90429. break;
  90430. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  90431. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90432. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  90433. break;
  90434. case BABYLON.PhysicsImpostor.BoxImpostor:
  90435. var box = extendSize.scale(0.5);
  90436. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  90437. break;
  90438. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90439. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  90440. returnValue = new this.BJSCANNON.Plane();
  90441. break;
  90442. case BABYLON.PhysicsImpostor.MeshImpostor:
  90443. // should transform the vertex data to world coordinates!!
  90444. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  90445. var rawFaces = object.getIndices ? object.getIndices() : [];
  90446. if (!rawVerts)
  90447. return;
  90448. // get only scale! so the object could transform correctly.
  90449. var oldPosition = object.position.clone();
  90450. var oldRotation = object.rotation && object.rotation.clone();
  90451. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  90452. object.position.copyFromFloats(0, 0, 0);
  90453. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90454. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90455. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90456. var transform = object.computeWorldMatrix(true);
  90457. // convert rawVerts to object space
  90458. var temp = new Array();
  90459. var index;
  90460. for (index = 0; index < rawVerts.length; index += 3) {
  90461. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  90462. }
  90463. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  90464. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  90465. //now set back the transformation!
  90466. object.position.copyFrom(oldPosition);
  90467. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  90468. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  90469. break;
  90470. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  90471. var oldPosition2 = object.position.clone();
  90472. var oldRotation2 = object.rotation && object.rotation.clone();
  90473. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  90474. object.position.copyFromFloats(0, 0, 0);
  90475. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90476. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90477. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90478. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  90479. returnValue = this._createHeightmap(object);
  90480. object.position.copyFrom(oldPosition2);
  90481. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  90482. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  90483. object.computeWorldMatrix(true);
  90484. break;
  90485. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90486. returnValue = new this.BJSCANNON.Particle();
  90487. break;
  90488. }
  90489. return returnValue;
  90490. };
  90491. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  90492. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90493. var transform = object.computeWorldMatrix(true);
  90494. // convert rawVerts to object space
  90495. var temp = new Array();
  90496. var index;
  90497. for (index = 0; index < pos.length; index += 3) {
  90498. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  90499. }
  90500. pos = temp;
  90501. var matrix = new Array();
  90502. //For now pointDepth will not be used and will be automatically calculated.
  90503. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  90504. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  90505. var boundingInfo = object.getBoundingInfo();
  90506. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  90507. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  90508. var elementSize = dim * 2 / arraySize;
  90509. for (var i = 0; i < pos.length; i = i + 3) {
  90510. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  90511. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  90512. var y = -pos[i + 2] + minY;
  90513. if (!matrix[x]) {
  90514. matrix[x] = [];
  90515. }
  90516. if (!matrix[x][z]) {
  90517. matrix[x][z] = y;
  90518. }
  90519. matrix[x][z] = Math.max(y, matrix[x][z]);
  90520. }
  90521. for (var x = 0; x <= arraySize; ++x) {
  90522. if (!matrix[x]) {
  90523. var loc = 1;
  90524. while (!matrix[(x + loc) % arraySize]) {
  90525. loc++;
  90526. }
  90527. matrix[x] = matrix[(x + loc) % arraySize].slice();
  90528. //console.log("missing x", x);
  90529. }
  90530. for (var z = 0; z <= arraySize; ++z) {
  90531. if (!matrix[x][z]) {
  90532. var loc = 1;
  90533. var newValue;
  90534. while (newValue === undefined) {
  90535. newValue = matrix[x][(z + loc++) % arraySize];
  90536. }
  90537. matrix[x][z] = newValue;
  90538. }
  90539. }
  90540. }
  90541. var shape = new this.BJSCANNON.Heightfield(matrix, {
  90542. elementSize: elementSize
  90543. });
  90544. //For future reference, needed for body transformation
  90545. shape.minY = minY;
  90546. return shape;
  90547. };
  90548. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  90549. var object = impostor.object;
  90550. //make sure it is updated...
  90551. object.computeWorldMatrix && object.computeWorldMatrix(true);
  90552. // The delta between the mesh position and the mesh bounding box center
  90553. var bInfo = object.getBoundingInfo();
  90554. if (!bInfo)
  90555. return;
  90556. var center = impostor.getObjectCenter();
  90557. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  90558. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  90559. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  90560. this._tmpPosition.copyFrom(center);
  90561. var quaternion = object.rotationQuaternion;
  90562. if (!quaternion) {
  90563. return;
  90564. }
  90565. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  90566. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  90567. //-90 DEG in X, precalculated
  90568. quaternion = quaternion.multiply(this._minus90X);
  90569. //Invert! (Precalculated, 90 deg in X)
  90570. //No need to clone. this will never change.
  90571. impostor.setDeltaRotation(this._plus90X);
  90572. }
  90573. //If it is a heightfield, if should be centered.
  90574. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  90575. var mesh = object;
  90576. var boundingInfo = mesh.getBoundingInfo();
  90577. //calculate the correct body position:
  90578. var rotationQuaternion = mesh.rotationQuaternion;
  90579. mesh.rotationQuaternion = this._tmpUnityRotation;
  90580. mesh.computeWorldMatrix(true);
  90581. //get original center with no rotation
  90582. var c = center.clone();
  90583. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  90584. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  90585. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  90586. mesh.setPreTransformMatrix(p);
  90587. mesh.computeWorldMatrix(true);
  90588. //calculate the translation
  90589. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  90590. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  90591. //add it inverted to the delta
  90592. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  90593. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90594. //rotation is back
  90595. mesh.rotationQuaternion = rotationQuaternion;
  90596. mesh.setPreTransformMatrix(oldPivot);
  90597. mesh.computeWorldMatrix(true);
  90598. }
  90599. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90600. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90601. //this._tmpPosition.copyFrom(object.position);
  90602. }
  90603. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90604. //Now update the impostor object
  90605. impostor.physicsBody.position.copy(this._tmpPosition);
  90606. impostor.physicsBody.quaternion.copy(quaternion);
  90607. };
  90608. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90609. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90610. if (impostor.object.rotationQuaternion) {
  90611. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90612. }
  90613. };
  90614. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90615. impostor.physicsBody.position.copy(newPosition);
  90616. impostor.physicsBody.quaternion.copy(newRotation);
  90617. };
  90618. CannonJSPlugin.prototype.isSupported = function () {
  90619. return this.BJSCANNON !== undefined;
  90620. };
  90621. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90622. impostor.physicsBody.velocity.copy(velocity);
  90623. };
  90624. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90625. impostor.physicsBody.angularVelocity.copy(velocity);
  90626. };
  90627. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90628. var v = impostor.physicsBody.velocity;
  90629. if (!v) {
  90630. return null;
  90631. }
  90632. return new BABYLON.Vector3(v.x, v.y, v.z);
  90633. };
  90634. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90635. var v = impostor.physicsBody.angularVelocity;
  90636. if (!v) {
  90637. return null;
  90638. }
  90639. return new BABYLON.Vector3(v.x, v.y, v.z);
  90640. };
  90641. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90642. impostor.physicsBody.mass = mass;
  90643. impostor.physicsBody.updateMassProperties();
  90644. };
  90645. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90646. return impostor.physicsBody.mass;
  90647. };
  90648. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90649. return impostor.physicsBody.material.friction;
  90650. };
  90651. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90652. impostor.physicsBody.material.friction = friction;
  90653. };
  90654. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90655. return impostor.physicsBody.material.restitution;
  90656. };
  90657. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90658. impostor.physicsBody.material.restitution = restitution;
  90659. };
  90660. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90661. impostor.physicsBody.sleep();
  90662. };
  90663. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90664. impostor.physicsBody.wakeUp();
  90665. };
  90666. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90667. joint.physicsJoint.distance = maxDistance;
  90668. };
  90669. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90670. // if (!motorIndex) {
  90671. // joint.physicsJoint.enableMotor();
  90672. // }
  90673. // }
  90674. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90675. // if (!motorIndex) {
  90676. // joint.physicsJoint.disableMotor();
  90677. // }
  90678. // }
  90679. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90680. if (!motorIndex) {
  90681. joint.physicsJoint.enableMotor();
  90682. joint.physicsJoint.setMotorSpeed(speed);
  90683. if (maxForce) {
  90684. this.setLimit(joint, maxForce);
  90685. }
  90686. }
  90687. };
  90688. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90689. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90690. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90691. };
  90692. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90693. var body = impostor.physicsBody;
  90694. mesh.position.x = body.position.x;
  90695. mesh.position.y = body.position.y;
  90696. mesh.position.z = body.position.z;
  90697. if (mesh.rotationQuaternion) {
  90698. mesh.rotationQuaternion.x = body.quaternion.x;
  90699. mesh.rotationQuaternion.y = body.quaternion.y;
  90700. mesh.rotationQuaternion.z = body.quaternion.z;
  90701. mesh.rotationQuaternion.w = body.quaternion.w;
  90702. }
  90703. };
  90704. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90705. var shape = impostor.physicsBody.shapes[0];
  90706. return shape.boundingSphereRadius;
  90707. };
  90708. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90709. var shape = impostor.physicsBody.shapes[0];
  90710. result.x = shape.halfExtents.x * 2;
  90711. result.y = shape.halfExtents.y * 2;
  90712. result.z = shape.halfExtents.z * 2;
  90713. };
  90714. CannonJSPlugin.prototype.dispose = function () {
  90715. };
  90716. CannonJSPlugin.prototype._extendNamespace = function () {
  90717. //this will force cannon to execute at least one step when using interpolation
  90718. var step_tmp1 = new this.BJSCANNON.Vec3();
  90719. var Engine = this.BJSCANNON;
  90720. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90721. maxSubSteps = maxSubSteps || 10;
  90722. timeSinceLastCalled = timeSinceLastCalled || 0;
  90723. if (timeSinceLastCalled === 0) {
  90724. this.internalStep(dt);
  90725. this.time += dt;
  90726. }
  90727. else {
  90728. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90729. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90730. var t0 = performance.now();
  90731. for (var i = 0; i !== internalSteps; i++) {
  90732. this.internalStep(dt);
  90733. if (performance.now() - t0 > dt * 1000) {
  90734. break;
  90735. }
  90736. }
  90737. this.time += timeSinceLastCalled;
  90738. var h = this.time % dt;
  90739. var h_div_dt = h / dt;
  90740. var interpvelo = step_tmp1;
  90741. var bodies = this.bodies;
  90742. for (var j = 0; j !== bodies.length; j++) {
  90743. var b = bodies[j];
  90744. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90745. b.position.vsub(b.previousPosition, interpvelo);
  90746. interpvelo.scale(h_div_dt, interpvelo);
  90747. b.position.vadd(interpvelo, b.interpolatedPosition);
  90748. }
  90749. else {
  90750. b.interpolatedPosition.copy(b.position);
  90751. b.interpolatedQuaternion.copy(b.quaternion);
  90752. }
  90753. }
  90754. }
  90755. };
  90756. };
  90757. return CannonJSPlugin;
  90758. }());
  90759. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90760. })(BABYLON || (BABYLON = {}));
  90761. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90762. var BABYLON;
  90763. (function (BABYLON) {
  90764. var OimoJSPlugin = /** @class */ (function () {
  90765. function OimoJSPlugin(iterations) {
  90766. this.name = "OimoJSPlugin";
  90767. this._tmpImpostorsArray = [];
  90768. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90769. this.BJSOIMO = OIMO;
  90770. this.world = new this.BJSOIMO.World({
  90771. iterations: iterations
  90772. });
  90773. this.world.clear();
  90774. }
  90775. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90776. this.world.gravity.copy(gravity);
  90777. };
  90778. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90779. this.world.timeStep = timeStep;
  90780. };
  90781. OimoJSPlugin.prototype.getTimeStep = function () {
  90782. return this.world.timeStep;
  90783. };
  90784. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90785. var _this = this;
  90786. impostors.forEach(function (impostor) {
  90787. impostor.beforeStep();
  90788. });
  90789. this.world.step();
  90790. impostors.forEach(function (impostor) {
  90791. impostor.afterStep();
  90792. //update the ordered impostors array
  90793. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90794. });
  90795. //check for collisions
  90796. var contact = this.world.contacts;
  90797. while (contact !== null) {
  90798. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90799. contact = contact.next;
  90800. continue;
  90801. }
  90802. //is this body colliding with any other? get the impostor
  90803. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90804. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90805. if (!mainImpostor || !collidingImpostor) {
  90806. contact = contact.next;
  90807. continue;
  90808. }
  90809. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90810. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90811. contact = contact.next;
  90812. }
  90813. };
  90814. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90815. var mass = impostor.physicsBody.mass;
  90816. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90817. };
  90818. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90819. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90820. this.applyImpulse(impostor, force, contactPoint);
  90821. };
  90822. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90823. var _this = this;
  90824. //parent-child relationship. Does this impostor has a parent impostor?
  90825. if (impostor.parent) {
  90826. if (impostor.physicsBody) {
  90827. this.removePhysicsBody(impostor);
  90828. //TODO is that needed?
  90829. impostor.forceUpdate();
  90830. }
  90831. return;
  90832. }
  90833. if (impostor.isBodyInitRequired()) {
  90834. var bodyConfig = {
  90835. name: impostor.uniqueId,
  90836. //Oimo must have mass, also for static objects.
  90837. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90838. size: [],
  90839. type: [],
  90840. pos: [],
  90841. posShape: [],
  90842. rot: [],
  90843. rotShape: [],
  90844. move: impostor.getParam("mass") !== 0,
  90845. density: impostor.getParam("mass"),
  90846. friction: impostor.getParam("friction"),
  90847. restitution: impostor.getParam("restitution"),
  90848. //Supporting older versions of Oimo
  90849. world: this.world
  90850. };
  90851. var impostors = [impostor];
  90852. var addToArray = function (parent) {
  90853. if (!parent.getChildMeshes)
  90854. return;
  90855. parent.getChildMeshes().forEach(function (m) {
  90856. if (m.physicsImpostor) {
  90857. impostors.push(m.physicsImpostor);
  90858. //m.physicsImpostor._init();
  90859. }
  90860. });
  90861. };
  90862. addToArray(impostor.object);
  90863. var checkWithEpsilon_1 = function (value) {
  90864. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90865. };
  90866. var globalQuaternion_1 = new BABYLON.Quaternion();
  90867. impostors.forEach(function (i) {
  90868. if (!i.object.rotationQuaternion) {
  90869. return;
  90870. }
  90871. //get the correct bounding box
  90872. var oldQuaternion = i.object.rotationQuaternion;
  90873. globalQuaternion_1 = oldQuaternion.clone();
  90874. var rot = oldQuaternion.toEulerAngles();
  90875. var extendSize = i.getObjectExtendSize();
  90876. var radToDeg = 57.295779513082320876;
  90877. if (i === impostor) {
  90878. var center = impostor.getObjectCenter();
  90879. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90880. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90881. //Can also use Array.prototype.push.apply
  90882. bodyConfig.pos.push(center.x);
  90883. bodyConfig.pos.push(center.y);
  90884. bodyConfig.pos.push(center.z);
  90885. bodyConfig.posShape.push(0, 0, 0);
  90886. //tmp solution
  90887. bodyConfig.rot.push(0);
  90888. bodyConfig.rot.push(0);
  90889. bodyConfig.rot.push(0);
  90890. bodyConfig.rotShape.push(0, 0, 0);
  90891. }
  90892. else {
  90893. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90894. bodyConfig.posShape.push(localPosition.x);
  90895. bodyConfig.posShape.push(localPosition.y);
  90896. bodyConfig.posShape.push(localPosition.z);
  90897. bodyConfig.pos.push(0, 0, 0);
  90898. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90899. bodyConfig.rot.push(0);
  90900. bodyConfig.rot.push(0);
  90901. bodyConfig.rot.push(0);
  90902. bodyConfig.rotShape.push(rot.x * radToDeg);
  90903. bodyConfig.rotShape.push(rot.y * radToDeg);
  90904. bodyConfig.rotShape.push(rot.z * radToDeg);
  90905. }
  90906. // register mesh
  90907. switch (i.type) {
  90908. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90909. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90910. case BABYLON.PhysicsImpostor.SphereImpostor:
  90911. var radiusX = extendSize.x;
  90912. var radiusY = extendSize.y;
  90913. var radiusZ = extendSize.z;
  90914. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90915. bodyConfig.type.push('sphere');
  90916. //due to the way oimo works with compounds, add 3 times
  90917. bodyConfig.size.push(size);
  90918. bodyConfig.size.push(size);
  90919. bodyConfig.size.push(size);
  90920. break;
  90921. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90922. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90923. var sizeY = checkWithEpsilon_1(extendSize.y);
  90924. bodyConfig.type.push('cylinder');
  90925. bodyConfig.size.push(sizeX);
  90926. bodyConfig.size.push(sizeY);
  90927. //due to the way oimo works with compounds, add one more value.
  90928. bodyConfig.size.push(sizeY);
  90929. break;
  90930. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90931. case BABYLON.PhysicsImpostor.BoxImpostor:
  90932. default:
  90933. var sizeX = checkWithEpsilon_1(extendSize.x);
  90934. var sizeY = checkWithEpsilon_1(extendSize.y);
  90935. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90936. bodyConfig.type.push('box');
  90937. //if (i === impostor) {
  90938. bodyConfig.size.push(sizeX);
  90939. bodyConfig.size.push(sizeY);
  90940. bodyConfig.size.push(sizeZ);
  90941. //} else {
  90942. // bodyConfig.size.push(0,0,0);
  90943. //}
  90944. break;
  90945. }
  90946. //actually not needed, but hey...
  90947. i.object.rotationQuaternion = oldQuaternion;
  90948. });
  90949. impostor.physicsBody = this.world.add(bodyConfig);
  90950. // set the quaternion, ignoring the previously defined (euler) rotation
  90951. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90952. // update with delta 0, so the body will reveive the new rotation.
  90953. impostor.physicsBody.updatePosition(0);
  90954. }
  90955. else {
  90956. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90957. }
  90958. impostor.setDeltaPosition(this._tmpPositionVector);
  90959. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90960. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90961. };
  90962. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90963. //impostor.physicsBody.dispose();
  90964. //Same as : (older oimo versions)
  90965. this.world.removeRigidBody(impostor.physicsBody);
  90966. };
  90967. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90968. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90969. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90970. if (!mainBody || !connectedBody) {
  90971. return;
  90972. }
  90973. var jointData = impostorJoint.joint.jointData;
  90974. var options = jointData.nativeParams || {};
  90975. var type;
  90976. var nativeJointData = {
  90977. body1: mainBody,
  90978. body2: connectedBody,
  90979. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90980. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90981. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90982. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90983. min: options.min,
  90984. max: options.max,
  90985. collision: options.collision || jointData.collision,
  90986. spring: options.spring,
  90987. //supporting older version of Oimo
  90988. world: this.world
  90989. };
  90990. switch (impostorJoint.joint.type) {
  90991. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90992. type = "jointBall";
  90993. break;
  90994. case BABYLON.PhysicsJoint.SpringJoint:
  90995. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90996. var springData = jointData;
  90997. nativeJointData.min = springData.length || nativeJointData.min;
  90998. //Max should also be set, just make sure it is at least min
  90999. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  91000. case BABYLON.PhysicsJoint.DistanceJoint:
  91001. type = "jointDistance";
  91002. nativeJointData.max = jointData.maxDistance;
  91003. break;
  91004. case BABYLON.PhysicsJoint.PrismaticJoint:
  91005. type = "jointPrisme";
  91006. break;
  91007. case BABYLON.PhysicsJoint.SliderJoint:
  91008. type = "jointSlide";
  91009. break;
  91010. case BABYLON.PhysicsJoint.WheelJoint:
  91011. type = "jointWheel";
  91012. break;
  91013. case BABYLON.PhysicsJoint.HingeJoint:
  91014. default:
  91015. type = "jointHinge";
  91016. break;
  91017. }
  91018. nativeJointData.type = type;
  91019. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  91020. };
  91021. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  91022. //Bug in Oimo prevents us from disposing a joint in the playground
  91023. //joint.joint.physicsJoint.dispose();
  91024. //So we will bruteforce it!
  91025. try {
  91026. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  91027. }
  91028. catch (e) {
  91029. BABYLON.Tools.Warn(e);
  91030. }
  91031. };
  91032. OimoJSPlugin.prototype.isSupported = function () {
  91033. return this.BJSOIMO !== undefined;
  91034. };
  91035. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  91036. if (!impostor.physicsBody.sleeping) {
  91037. //TODO check that
  91038. /*if (impostor.physicsBody.shapes.next) {
  91039. var parentShape = this._getLastShape(impostor.physicsBody);
  91040. impostor.object.position.copyFrom(parentShape.position);
  91041. console.log(parentShape.position);
  91042. } else {*/
  91043. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  91044. //}
  91045. if (impostor.object.rotationQuaternion) {
  91046. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  91047. }
  91048. }
  91049. };
  91050. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  91051. var body = impostor.physicsBody;
  91052. body.position.copy(newPosition);
  91053. body.orientation.copy(newRotation);
  91054. body.syncShapes();
  91055. body.awake();
  91056. };
  91057. /*private _getLastShape(body: any): any {
  91058. var lastShape = body.shapes;
  91059. while (lastShape.next) {
  91060. lastShape = lastShape.next;
  91061. }
  91062. return lastShape;
  91063. }*/
  91064. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  91065. impostor.physicsBody.linearVelocity.copy(velocity);
  91066. };
  91067. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  91068. impostor.physicsBody.angularVelocity.copy(velocity);
  91069. };
  91070. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  91071. var v = impostor.physicsBody.linearVelocity;
  91072. if (!v) {
  91073. return null;
  91074. }
  91075. return new BABYLON.Vector3(v.x, v.y, v.z);
  91076. };
  91077. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  91078. var v = impostor.physicsBody.angularVelocity;
  91079. if (!v) {
  91080. return null;
  91081. }
  91082. return new BABYLON.Vector3(v.x, v.y, v.z);
  91083. };
  91084. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  91085. var staticBody = mass === 0;
  91086. //this will actually set the body's density and not its mass.
  91087. //But this is how oimo treats the mass variable.
  91088. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  91089. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  91090. };
  91091. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  91092. return impostor.physicsBody.shapes.density;
  91093. };
  91094. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  91095. return impostor.physicsBody.shapes.friction;
  91096. };
  91097. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  91098. impostor.physicsBody.shapes.friction = friction;
  91099. };
  91100. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  91101. return impostor.physicsBody.shapes.restitution;
  91102. };
  91103. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  91104. impostor.physicsBody.shapes.restitution = restitution;
  91105. };
  91106. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  91107. impostor.physicsBody.sleep();
  91108. };
  91109. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  91110. impostor.physicsBody.awake();
  91111. };
  91112. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  91113. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  91114. if (minDistance !== void 0) {
  91115. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  91116. }
  91117. };
  91118. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  91119. //TODO separate rotational and transational motors.
  91120. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  91121. if (motor) {
  91122. motor.setMotor(speed, maxForce);
  91123. }
  91124. };
  91125. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  91126. //TODO separate rotational and transational motors.
  91127. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  91128. if (motor) {
  91129. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  91130. }
  91131. };
  91132. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  91133. var body = impostor.physicsBody;
  91134. mesh.position.x = body.position.x;
  91135. mesh.position.y = body.position.y;
  91136. mesh.position.z = body.position.z;
  91137. if (mesh.rotationQuaternion) {
  91138. mesh.rotationQuaternion.x = body.orientation.x;
  91139. mesh.rotationQuaternion.y = body.orientation.y;
  91140. mesh.rotationQuaternion.z = body.orientation.z;
  91141. mesh.rotationQuaternion.w = body.orientation.s;
  91142. }
  91143. };
  91144. OimoJSPlugin.prototype.getRadius = function (impostor) {
  91145. return impostor.physicsBody.shapes.radius;
  91146. };
  91147. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  91148. var shape = impostor.physicsBody.shapes;
  91149. result.x = shape.halfWidth * 2;
  91150. result.y = shape.halfHeight * 2;
  91151. result.z = shape.halfDepth * 2;
  91152. };
  91153. OimoJSPlugin.prototype.dispose = function () {
  91154. this.world.clear();
  91155. };
  91156. return OimoJSPlugin;
  91157. }());
  91158. BABYLON.OimoJSPlugin = OimoJSPlugin;
  91159. })(BABYLON || (BABYLON = {}));
  91160. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  91161. var BABYLON;
  91162. (function (BABYLON) {
  91163. /**
  91164. * Gets the current physics engine
  91165. * @returns a IPhysicsEngine or null if none attached
  91166. */
  91167. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  91168. return this._physicsEngine;
  91169. };
  91170. /**
  91171. * Enables physics to the current scene
  91172. * @param gravity defines the scene's gravity for the physics engine
  91173. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  91174. * @return a boolean indicating if the physics engine was initialized
  91175. */
  91176. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  91177. if (gravity === void 0) { gravity = null; }
  91178. if (this._physicsEngine) {
  91179. return true;
  91180. }
  91181. // Register the component to the scene
  91182. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  91183. if (!component) {
  91184. component = new PhysicsEngineSceneComponent(this);
  91185. this._addComponent(component);
  91186. }
  91187. try {
  91188. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  91189. return true;
  91190. }
  91191. catch (e) {
  91192. BABYLON.Tools.Error(e.message);
  91193. return false;
  91194. }
  91195. };
  91196. /**
  91197. * Disables and disposes the physics engine associated with the scene
  91198. */
  91199. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  91200. if (!this._physicsEngine) {
  91201. return;
  91202. }
  91203. this._physicsEngine.dispose();
  91204. this._physicsEngine = null;
  91205. };
  91206. /**
  91207. * Gets a boolean indicating if there is an active physics engine
  91208. * @returns a boolean indicating if there is an active physics engine
  91209. */
  91210. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  91211. return this._physicsEngine !== undefined;
  91212. };
  91213. /**
  91214. * Deletes a physics compound impostor
  91215. * @param compound defines the compound to delete
  91216. */
  91217. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  91218. var mesh = compound.parts[0].mesh;
  91219. if (mesh.physicsImpostor) {
  91220. mesh.physicsImpostor.dispose( /*true*/);
  91221. mesh.physicsImpostor = null;
  91222. }
  91223. };
  91224. /** @hidden */
  91225. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  91226. if (this._physicsEngine) {
  91227. this.onBeforePhysicsObservable.notifyObservers(this);
  91228. this._physicsEngine._step(step / 1000);
  91229. this.onAfterPhysicsObservable.notifyObservers(this);
  91230. }
  91231. };
  91232. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  91233. get: function () {
  91234. return this._physicsImpostor;
  91235. },
  91236. set: function (value) {
  91237. var _this = this;
  91238. if (this._physicsImpostor === value) {
  91239. return;
  91240. }
  91241. if (this._disposePhysicsObserver) {
  91242. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  91243. }
  91244. this._physicsImpostor = value;
  91245. if (value) {
  91246. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  91247. // Physics
  91248. if (_this.physicsImpostor) {
  91249. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  91250. _this.physicsImpostor = null;
  91251. }
  91252. });
  91253. }
  91254. },
  91255. enumerable: true,
  91256. configurable: true
  91257. });
  91258. /**
  91259. * Gets the current physics impostor
  91260. * @see http://doc.babylonjs.com/features/physics_engine
  91261. * @returns a physics impostor or null
  91262. */
  91263. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  91264. return this.physicsImpostor;
  91265. };
  91266. /**
  91267. * Apply a physic impulse to the mesh
  91268. * @param force defines the force to apply
  91269. * @param contactPoint defines where to apply the force
  91270. * @returns the current mesh
  91271. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91272. */
  91273. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  91274. if (!this.physicsImpostor) {
  91275. return this;
  91276. }
  91277. this.physicsImpostor.applyImpulse(force, contactPoint);
  91278. return this;
  91279. };
  91280. /**
  91281. * Creates a physic joint between two meshes
  91282. * @param otherMesh defines the other mesh to use
  91283. * @param pivot1 defines the pivot to use on this mesh
  91284. * @param pivot2 defines the pivot to use on the other mesh
  91285. * @param options defines additional options (can be plugin dependent)
  91286. * @returns the current mesh
  91287. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  91288. */
  91289. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  91290. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  91291. return this;
  91292. }
  91293. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  91294. mainPivot: pivot1,
  91295. connectedPivot: pivot2,
  91296. nativeParams: options
  91297. });
  91298. return this;
  91299. };
  91300. /**
  91301. * Defines the physics engine scene component responsible to manage a physics engine
  91302. */
  91303. var PhysicsEngineSceneComponent = /** @class */ (function () {
  91304. /**
  91305. * Creates a new instance of the component for the given scene
  91306. * @param scene Defines the scene to register the component in
  91307. */
  91308. function PhysicsEngineSceneComponent(scene) {
  91309. var _this = this;
  91310. /**
  91311. * The component name helpful to identify the component in the list of scene components.
  91312. */
  91313. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  91314. this.scene = scene;
  91315. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  91316. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  91317. // Replace the function used to get the deterministic frame time
  91318. this.scene.getDeterministicFrameTime = function () {
  91319. if (_this.scene._physicsEngine) {
  91320. return _this.scene._physicsEngine.getTimeStep() * 1000;
  91321. }
  91322. return 1000.0 / 60.0;
  91323. };
  91324. }
  91325. /**
  91326. * Registers the component in a given scene
  91327. */
  91328. PhysicsEngineSceneComponent.prototype.register = function () {
  91329. };
  91330. /**
  91331. * Rebuilds the elements related to this component in case of
  91332. * context lost for instance.
  91333. */
  91334. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  91335. // Nothing to do for this component
  91336. };
  91337. /**
  91338. * Disposes the component and the associated ressources
  91339. */
  91340. PhysicsEngineSceneComponent.prototype.dispose = function () {
  91341. this.scene.onBeforePhysicsObservable.clear();
  91342. this.scene.onAfterPhysicsObservable.clear();
  91343. if (this.scene._physicsEngine) {
  91344. this.scene.disablePhysicsEngine();
  91345. }
  91346. };
  91347. return PhysicsEngineSceneComponent;
  91348. }());
  91349. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  91350. })(BABYLON || (BABYLON = {}));
  91351. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  91352. var BABYLON;
  91353. (function (BABYLON) {
  91354. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  91355. // All values and structures referenced from:
  91356. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  91357. var DDS_MAGIC = 0x20534444;
  91358. var
  91359. //DDSD_CAPS = 0x1,
  91360. //DDSD_HEIGHT = 0x2,
  91361. //DDSD_WIDTH = 0x4,
  91362. //DDSD_PITCH = 0x8,
  91363. //DDSD_PIXELFORMAT = 0x1000,
  91364. DDSD_MIPMAPCOUNT = 0x20000;
  91365. //DDSD_LINEARSIZE = 0x80000,
  91366. //DDSD_DEPTH = 0x800000;
  91367. // var DDSCAPS_COMPLEX = 0x8,
  91368. // DDSCAPS_MIPMAP = 0x400000,
  91369. // DDSCAPS_TEXTURE = 0x1000;
  91370. var DDSCAPS2_CUBEMAP = 0x200;
  91371. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  91372. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  91373. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  91374. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  91375. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  91376. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  91377. // DDSCAPS2_VOLUME = 0x200000;
  91378. var
  91379. //DDPF_ALPHAPIXELS = 0x1,
  91380. //DDPF_ALPHA = 0x2,
  91381. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  91382. //DDPF_YUV = 0x200,
  91383. DDPF_LUMINANCE = 0x20000;
  91384. function FourCCToInt32(value) {
  91385. return value.charCodeAt(0) +
  91386. (value.charCodeAt(1) << 8) +
  91387. (value.charCodeAt(2) << 16) +
  91388. (value.charCodeAt(3) << 24);
  91389. }
  91390. function Int32ToFourCC(value) {
  91391. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  91392. }
  91393. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  91394. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  91395. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  91396. var FOURCC_DX10 = FourCCToInt32("DX10");
  91397. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  91398. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  91399. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  91400. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  91401. var headerLengthInt = 31; // The header length in 32 bit ints
  91402. // Offsets into the header array
  91403. var off_magic = 0;
  91404. var off_size = 1;
  91405. var off_flags = 2;
  91406. var off_height = 3;
  91407. var off_width = 4;
  91408. var off_mipmapCount = 7;
  91409. var off_pfFlags = 20;
  91410. var off_pfFourCC = 21;
  91411. var off_RGBbpp = 22;
  91412. var off_RMask = 23;
  91413. var off_GMask = 24;
  91414. var off_BMask = 25;
  91415. var off_AMask = 26;
  91416. // var off_caps1 = 27;
  91417. var off_caps2 = 28;
  91418. // var off_caps3 = 29;
  91419. // var off_caps4 = 30;
  91420. var off_dxgiFormat = 32;
  91421. ;
  91422. var DDSTools = /** @class */ (function () {
  91423. function DDSTools() {
  91424. }
  91425. DDSTools.GetDDSInfo = function (arrayBuffer) {
  91426. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91427. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  91428. var mipmapCount = 1;
  91429. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  91430. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91431. }
  91432. var fourCC = header[off_pfFourCC];
  91433. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  91434. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91435. switch (fourCC) {
  91436. case FOURCC_D3DFMT_R16G16B16A16F:
  91437. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91438. break;
  91439. case FOURCC_D3DFMT_R32G32B32A32F:
  91440. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91441. break;
  91442. case FOURCC_DX10:
  91443. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  91444. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91445. break;
  91446. }
  91447. }
  91448. return {
  91449. width: header[off_width],
  91450. height: header[off_height],
  91451. mipmapCount: mipmapCount,
  91452. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  91453. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  91454. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  91455. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  91456. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  91457. dxgiFormat: dxgiFormat,
  91458. textureType: textureType
  91459. };
  91460. };
  91461. DDSTools._ToHalfFloat = function (value) {
  91462. if (!DDSTools._FloatView) {
  91463. DDSTools._FloatView = new Float32Array(1);
  91464. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  91465. }
  91466. DDSTools._FloatView[0] = value;
  91467. var x = DDSTools._Int32View[0];
  91468. var bits = (x >> 16) & 0x8000; /* Get the sign */
  91469. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  91470. var e = (x >> 23) & 0xff; /* Using int is faster here */
  91471. /* If zero, or denormal, or exponent underflows too much for a denormal
  91472. * half, return signed zero. */
  91473. if (e < 103) {
  91474. return bits;
  91475. }
  91476. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  91477. if (e > 142) {
  91478. bits |= 0x7c00;
  91479. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  91480. * not Inf, so make sure we set one mantissa bit too. */
  91481. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  91482. return bits;
  91483. }
  91484. /* If exponent underflows but not too much, return a denormal */
  91485. if (e < 113) {
  91486. m |= 0x0800;
  91487. /* Extra rounding may overflow and set mantissa to 0 and exponent
  91488. * to 1, which is OK. */
  91489. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  91490. return bits;
  91491. }
  91492. bits |= ((e - 112) << 10) | (m >> 1);
  91493. bits += m & 1;
  91494. return bits;
  91495. };
  91496. DDSTools._FromHalfFloat = function (value) {
  91497. var s = (value & 0x8000) >> 15;
  91498. var e = (value & 0x7C00) >> 10;
  91499. var f = value & 0x03FF;
  91500. if (e === 0) {
  91501. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  91502. }
  91503. else if (e == 0x1F) {
  91504. return f ? NaN : ((s ? -1 : 1) * Infinity);
  91505. }
  91506. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  91507. };
  91508. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91509. var destArray = new Float32Array(dataLength);
  91510. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91511. var index = 0;
  91512. for (var y = 0; y < height; y++) {
  91513. for (var x = 0; x < width; x++) {
  91514. var srcPos = (x + y * width) * 4;
  91515. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  91516. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  91517. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  91518. if (DDSTools.StoreLODInAlphaChannel) {
  91519. destArray[index + 3] = lod;
  91520. }
  91521. else {
  91522. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  91523. }
  91524. index += 4;
  91525. }
  91526. }
  91527. return destArray;
  91528. };
  91529. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91530. if (DDSTools.StoreLODInAlphaChannel) {
  91531. var destArray = new Uint16Array(dataLength);
  91532. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91533. var index = 0;
  91534. for (var y = 0; y < height; y++) {
  91535. for (var x = 0; x < width; x++) {
  91536. var srcPos = (x + y * width) * 4;
  91537. destArray[index] = srcData[srcPos];
  91538. destArray[index + 1] = srcData[srcPos + 1];
  91539. destArray[index + 2] = srcData[srcPos + 2];
  91540. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  91541. index += 4;
  91542. }
  91543. }
  91544. return destArray;
  91545. }
  91546. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  91547. };
  91548. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91549. if (DDSTools.StoreLODInAlphaChannel) {
  91550. var destArray = new Float32Array(dataLength);
  91551. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91552. var index = 0;
  91553. for (var y = 0; y < height; y++) {
  91554. for (var x = 0; x < width; x++) {
  91555. var srcPos = (x + y * width) * 4;
  91556. destArray[index] = srcData[srcPos];
  91557. destArray[index + 1] = srcData[srcPos + 1];
  91558. destArray[index + 2] = srcData[srcPos + 2];
  91559. destArray[index + 3] = lod;
  91560. index += 4;
  91561. }
  91562. }
  91563. return destArray;
  91564. }
  91565. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  91566. };
  91567. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91568. var destArray = new Uint8Array(dataLength);
  91569. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91570. var index = 0;
  91571. for (var y = 0; y < height; y++) {
  91572. for (var x = 0; x < width; x++) {
  91573. var srcPos = (x + y * width) * 4;
  91574. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  91575. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  91576. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  91577. if (DDSTools.StoreLODInAlphaChannel) {
  91578. destArray[index + 3] = lod;
  91579. }
  91580. else {
  91581. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  91582. }
  91583. index += 4;
  91584. }
  91585. }
  91586. return destArray;
  91587. };
  91588. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91589. var destArray = new Uint8Array(dataLength);
  91590. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91591. var index = 0;
  91592. for (var y = 0; y < height; y++) {
  91593. for (var x = 0; x < width; x++) {
  91594. var srcPos = (x + y * width) * 4;
  91595. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  91596. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  91597. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  91598. if (DDSTools.StoreLODInAlphaChannel) {
  91599. destArray[index + 3] = lod;
  91600. }
  91601. else {
  91602. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  91603. }
  91604. index += 4;
  91605. }
  91606. }
  91607. return destArray;
  91608. };
  91609. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  91610. var byteArray = new Uint8Array(dataLength);
  91611. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91612. var index = 0;
  91613. for (var y = 0; y < height; y++) {
  91614. for (var x = 0; x < width; x++) {
  91615. var srcPos = (x + y * width) * 4;
  91616. byteArray[index] = srcData[srcPos + rOffset];
  91617. byteArray[index + 1] = srcData[srcPos + gOffset];
  91618. byteArray[index + 2] = srcData[srcPos + bOffset];
  91619. byteArray[index + 3] = srcData[srcPos + aOffset];
  91620. index += 4;
  91621. }
  91622. }
  91623. return byteArray;
  91624. };
  91625. DDSTools._ExtractLongWordOrder = function (value) {
  91626. if (value === 0 || value === 255 || value === -16777216) {
  91627. return 0;
  91628. }
  91629. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  91630. };
  91631. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  91632. var byteArray = new Uint8Array(dataLength);
  91633. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91634. var index = 0;
  91635. for (var y = 0; y < height; y++) {
  91636. for (var x = 0; x < width; x++) {
  91637. var srcPos = (x + y * width) * 3;
  91638. byteArray[index] = srcData[srcPos + rOffset];
  91639. byteArray[index + 1] = srcData[srcPos + gOffset];
  91640. byteArray[index + 2] = srcData[srcPos + bOffset];
  91641. index += 3;
  91642. }
  91643. }
  91644. return byteArray;
  91645. };
  91646. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  91647. var byteArray = new Uint8Array(dataLength);
  91648. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91649. var index = 0;
  91650. for (var y = 0; y < height; y++) {
  91651. for (var x = 0; x < width; x++) {
  91652. var srcPos = (x + y * width);
  91653. byteArray[index] = srcData[srcPos];
  91654. index++;
  91655. }
  91656. }
  91657. return byteArray;
  91658. };
  91659. /**
  91660. * Uploads DDS Levels to a Babylon Texture
  91661. * @hidden
  91662. */
  91663. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  91664. if (lodIndex === void 0) { lodIndex = -1; }
  91665. var sphericalPolynomialFaces = null;
  91666. if (info.sphericalPolynomial) {
  91667. sphericalPolynomialFaces = new Array();
  91668. }
  91669. var ext = engine.getCaps().s3tc;
  91670. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91671. var fourCC, width, height, dataLength = 0, dataOffset;
  91672. var byteArray, mipmapCount, mip;
  91673. var internalCompressedFormat = 0;
  91674. var blockBytes = 1;
  91675. if (header[off_magic] !== DDS_MAGIC) {
  91676. BABYLON.Tools.Error("Invalid magic number in DDS header");
  91677. return;
  91678. }
  91679. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  91680. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  91681. return;
  91682. }
  91683. if (info.isCompressed && !ext) {
  91684. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  91685. return;
  91686. }
  91687. var bpp = header[off_RGBbpp];
  91688. dataOffset = header[off_size] + 4;
  91689. var computeFormats = false;
  91690. if (info.isFourCC) {
  91691. fourCC = header[off_pfFourCC];
  91692. switch (fourCC) {
  91693. case FOURCC_DXT1:
  91694. blockBytes = 8;
  91695. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  91696. break;
  91697. case FOURCC_DXT3:
  91698. blockBytes = 16;
  91699. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  91700. break;
  91701. case FOURCC_DXT5:
  91702. blockBytes = 16;
  91703. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  91704. break;
  91705. case FOURCC_D3DFMT_R16G16B16A16F:
  91706. computeFormats = true;
  91707. break;
  91708. case FOURCC_D3DFMT_R32G32B32A32F:
  91709. computeFormats = true;
  91710. break;
  91711. case FOURCC_DX10:
  91712. // There is an additionnal header so dataOffset need to be changed
  91713. dataOffset += 5 * 4; // 5 uints
  91714. var supported = false;
  91715. switch (info.dxgiFormat) {
  91716. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  91717. computeFormats = true;
  91718. supported = true;
  91719. break;
  91720. case DXGI_FORMAT_B8G8R8X8_UNORM:
  91721. info.isRGB = true;
  91722. info.isFourCC = false;
  91723. bpp = 32;
  91724. supported = true;
  91725. break;
  91726. }
  91727. if (supported) {
  91728. break;
  91729. }
  91730. default:
  91731. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  91732. return;
  91733. }
  91734. }
  91735. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  91736. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  91737. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  91738. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  91739. if (computeFormats) {
  91740. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  91741. }
  91742. mipmapCount = 1;
  91743. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  91744. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91745. }
  91746. for (var face = 0; face < faces; face++) {
  91747. width = header[off_width];
  91748. height = header[off_height];
  91749. for (mip = 0; mip < mipmapCount; ++mip) {
  91750. if (lodIndex === -1 || lodIndex === mip) {
  91751. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  91752. var i = (lodIndex === -1) ? mip : 0;
  91753. if (!info.isCompressed && info.isFourCC) {
  91754. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91755. dataLength = width * height * 4;
  91756. var floatArray = null;
  91757. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  91758. if (bpp === 128) {
  91759. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91760. if (sphericalPolynomialFaces && i == 0) {
  91761. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91762. }
  91763. }
  91764. else if (bpp === 64) {
  91765. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91766. if (sphericalPolynomialFaces && i == 0) {
  91767. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91768. }
  91769. }
  91770. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91771. }
  91772. else {
  91773. if (bpp === 128) {
  91774. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91775. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91776. if (sphericalPolynomialFaces && i == 0) {
  91777. sphericalPolynomialFaces.push(floatArray);
  91778. }
  91779. }
  91780. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  91781. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91782. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91783. if (sphericalPolynomialFaces && i == 0) {
  91784. sphericalPolynomialFaces.push(floatArray);
  91785. }
  91786. }
  91787. else { // 64
  91788. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91789. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91790. if (sphericalPolynomialFaces && i == 0) {
  91791. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91792. }
  91793. }
  91794. }
  91795. if (floatArray) {
  91796. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91797. }
  91798. }
  91799. else if (info.isRGB) {
  91800. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91801. if (bpp === 24) {
  91802. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91803. dataLength = width * height * 3;
  91804. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91805. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91806. }
  91807. else { // 32
  91808. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91809. dataLength = width * height * 4;
  91810. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91811. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91812. }
  91813. }
  91814. else if (info.isLuminance) {
  91815. var unpackAlignment = engine._getUnpackAlignement();
  91816. var unpaddedRowSize = width;
  91817. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91818. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91819. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91820. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91821. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91822. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91823. }
  91824. else {
  91825. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91826. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91827. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91828. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91829. }
  91830. }
  91831. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91832. width *= 0.5;
  91833. height *= 0.5;
  91834. width = Math.max(1.0, width);
  91835. height = Math.max(1.0, height);
  91836. }
  91837. if (currentFace !== undefined) {
  91838. // Loading a single face
  91839. break;
  91840. }
  91841. }
  91842. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91843. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91844. size: header[off_width],
  91845. right: sphericalPolynomialFaces[0],
  91846. left: sphericalPolynomialFaces[1],
  91847. up: sphericalPolynomialFaces[2],
  91848. down: sphericalPolynomialFaces[3],
  91849. front: sphericalPolynomialFaces[4],
  91850. back: sphericalPolynomialFaces[5],
  91851. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91852. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91853. gammaSpace: false,
  91854. });
  91855. }
  91856. else {
  91857. info.sphericalPolynomial = undefined;
  91858. }
  91859. };
  91860. DDSTools.StoreLODInAlphaChannel = false;
  91861. return DDSTools;
  91862. }());
  91863. BABYLON.DDSTools = DDSTools;
  91864. })(BABYLON || (BABYLON = {}));
  91865. //# sourceMappingURL=babylon.dds.js.map
  91866. var BABYLON;
  91867. (function (BABYLON) {
  91868. /**
  91869. * Implementation of the DDS Texture Loader.
  91870. */
  91871. var DDSTextureLoader = /** @class */ (function () {
  91872. function DDSTextureLoader() {
  91873. /**
  91874. * Defines wether the loader supports cascade loading the different faces.
  91875. */
  91876. this.supportCascades = true;
  91877. }
  91878. /**
  91879. * This returns if the loader support the current file information.
  91880. * @param extension defines the file extension of the file being loaded
  91881. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91882. * @param fallback defines the fallback internal texture if any
  91883. * @param isBase64 defines whether the texture is encoded as a base64
  91884. * @param isBuffer defines whether the texture data are stored as a buffer
  91885. * @returns true if the loader can load the specified file
  91886. */
  91887. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91888. return extension.indexOf(".dds") === 0;
  91889. };
  91890. /**
  91891. * Transform the url before loading if required.
  91892. * @param rootUrl the url of the texture
  91893. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91894. * @returns the transformed texture
  91895. */
  91896. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91897. return rootUrl;
  91898. };
  91899. /**
  91900. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91901. * @param rootUrl the url of the texture
  91902. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91903. * @returns the fallback texture
  91904. */
  91905. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91906. return null;
  91907. };
  91908. /**
  91909. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91910. * @param data contains the texture data
  91911. * @param texture defines the BabylonJS internal texture
  91912. * @param createPolynomials will be true if polynomials have been requested
  91913. * @param onLoad defines the callback to trigger once the texture is ready
  91914. * @param onError defines the callback to trigger in case of error
  91915. */
  91916. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91917. var engine = texture.getEngine();
  91918. var info;
  91919. var loadMipmap = false;
  91920. if (Array.isArray(imgs)) {
  91921. for (var index = 0; index < imgs.length; index++) {
  91922. var data_1 = imgs[index];
  91923. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91924. texture.width = info.width;
  91925. texture.height = info.height;
  91926. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91927. engine._unpackFlipY(info.isCompressed);
  91928. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91929. if (!info.isFourCC && info.mipmapCount === 1) {
  91930. engine.generateMipMapsForCubemap(texture);
  91931. }
  91932. }
  91933. }
  91934. else {
  91935. var data = imgs;
  91936. info = BABYLON.DDSTools.GetDDSInfo(data);
  91937. texture.width = info.width;
  91938. texture.height = info.height;
  91939. if (createPolynomials) {
  91940. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91941. }
  91942. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91943. engine._unpackFlipY(info.isCompressed);
  91944. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91945. if (!info.isFourCC && info.mipmapCount === 1) {
  91946. engine.generateMipMapsForCubemap(texture);
  91947. }
  91948. }
  91949. engine._setCubeMapTextureParams(loadMipmap);
  91950. texture.isReady = true;
  91951. if (onLoad) {
  91952. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91953. }
  91954. };
  91955. /**
  91956. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91957. * @param data contains the texture data
  91958. * @param texture defines the BabylonJS internal texture
  91959. * @param callback defines the method to call once ready to upload
  91960. */
  91961. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91962. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91963. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91964. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91965. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91966. });
  91967. };
  91968. return DDSTextureLoader;
  91969. }());
  91970. // Register the loader.
  91971. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91972. })(BABYLON || (BABYLON = {}));
  91973. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91974. var BABYLON;
  91975. (function (BABYLON) {
  91976. /*
  91977. * Based on jsTGALoader - Javascript loader for TGA file
  91978. * By Vincent Thibault
  91979. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91980. */
  91981. var TGATools = /** @class */ (function () {
  91982. function TGATools() {
  91983. }
  91984. TGATools.GetTGAHeader = function (data) {
  91985. var offset = 0;
  91986. var header = {
  91987. id_length: data[offset++],
  91988. colormap_type: data[offset++],
  91989. image_type: data[offset++],
  91990. colormap_index: data[offset++] | data[offset++] << 8,
  91991. colormap_length: data[offset++] | data[offset++] << 8,
  91992. colormap_size: data[offset++],
  91993. origin: [
  91994. data[offset++] | data[offset++] << 8,
  91995. data[offset++] | data[offset++] << 8
  91996. ],
  91997. width: data[offset++] | data[offset++] << 8,
  91998. height: data[offset++] | data[offset++] << 8,
  91999. pixel_size: data[offset++],
  92000. flags: data[offset++]
  92001. };
  92002. return header;
  92003. };
  92004. /**
  92005. * Uploads TGA content to a Babylon Texture
  92006. * @hidden
  92007. */
  92008. TGATools.UploadContent = function (texture, data) {
  92009. // Not enough data to contain header ?
  92010. if (data.length < 19) {
  92011. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  92012. return;
  92013. }
  92014. // Read Header
  92015. var offset = 18;
  92016. var header = TGATools.GetTGAHeader(data);
  92017. // Assume it's a valid Targa file.
  92018. if (header.id_length + offset > data.length) {
  92019. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  92020. return;
  92021. }
  92022. // Skip not needed data
  92023. offset += header.id_length;
  92024. var use_rle = false;
  92025. var use_pal = false;
  92026. var use_grey = false;
  92027. // Get some informations.
  92028. switch (header.image_type) {
  92029. case TGATools._TYPE_RLE_INDEXED:
  92030. use_rle = true;
  92031. case TGATools._TYPE_INDEXED:
  92032. use_pal = true;
  92033. break;
  92034. case TGATools._TYPE_RLE_RGB:
  92035. use_rle = true;
  92036. case TGATools._TYPE_RGB:
  92037. // use_rgb = true;
  92038. break;
  92039. case TGATools._TYPE_RLE_GREY:
  92040. use_rle = true;
  92041. case TGATools._TYPE_GREY:
  92042. use_grey = true;
  92043. break;
  92044. }
  92045. var pixel_data;
  92046. // var numAlphaBits = header.flags & 0xf;
  92047. var pixel_size = header.pixel_size >> 3;
  92048. var pixel_total = header.width * header.height * pixel_size;
  92049. // Read palettes
  92050. var palettes;
  92051. if (use_pal) {
  92052. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  92053. }
  92054. // Read LRE
  92055. if (use_rle) {
  92056. pixel_data = new Uint8Array(pixel_total);
  92057. var c, count, i;
  92058. var localOffset = 0;
  92059. var pixels = new Uint8Array(pixel_size);
  92060. while (offset < pixel_total && localOffset < pixel_total) {
  92061. c = data[offset++];
  92062. count = (c & 0x7f) + 1;
  92063. // RLE pixels
  92064. if (c & 0x80) {
  92065. // Bind pixel tmp array
  92066. for (i = 0; i < pixel_size; ++i) {
  92067. pixels[i] = data[offset++];
  92068. }
  92069. // Copy pixel array
  92070. for (i = 0; i < count; ++i) {
  92071. pixel_data.set(pixels, localOffset + i * pixel_size);
  92072. }
  92073. localOffset += pixel_size * count;
  92074. }
  92075. // Raw pixels
  92076. else {
  92077. count *= pixel_size;
  92078. for (i = 0; i < count; ++i) {
  92079. pixel_data[localOffset + i] = data[offset++];
  92080. }
  92081. localOffset += count;
  92082. }
  92083. }
  92084. }
  92085. // RAW Pixels
  92086. else {
  92087. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  92088. }
  92089. // Load to texture
  92090. var x_start, y_start, x_step, y_step, y_end, x_end;
  92091. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  92092. default:
  92093. case TGATools._ORIGIN_UL:
  92094. x_start = 0;
  92095. x_step = 1;
  92096. x_end = header.width;
  92097. y_start = 0;
  92098. y_step = 1;
  92099. y_end = header.height;
  92100. break;
  92101. case TGATools._ORIGIN_BL:
  92102. x_start = 0;
  92103. x_step = 1;
  92104. x_end = header.width;
  92105. y_start = header.height - 1;
  92106. y_step = -1;
  92107. y_end = -1;
  92108. break;
  92109. case TGATools._ORIGIN_UR:
  92110. x_start = header.width - 1;
  92111. x_step = -1;
  92112. x_end = -1;
  92113. y_start = 0;
  92114. y_step = 1;
  92115. y_end = header.height;
  92116. break;
  92117. case TGATools._ORIGIN_BR:
  92118. x_start = header.width - 1;
  92119. x_step = -1;
  92120. x_end = -1;
  92121. y_start = header.height - 1;
  92122. y_step = -1;
  92123. y_end = -1;
  92124. break;
  92125. }
  92126. // Load the specify method
  92127. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  92128. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  92129. var engine = texture.getEngine();
  92130. engine._uploadDataToTextureDirectly(texture, imageData);
  92131. };
  92132. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92133. var image = pixel_data, colormap = palettes;
  92134. var width = header.width, height = header.height;
  92135. var color, i = 0, x, y;
  92136. var imageData = new Uint8Array(width * height * 4);
  92137. for (y = y_start; y !== y_end; y += y_step) {
  92138. for (x = x_start; x !== x_end; x += x_step, i++) {
  92139. color = image[i];
  92140. imageData[(x + width * y) * 4 + 3] = 255;
  92141. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  92142. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  92143. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  92144. }
  92145. }
  92146. return imageData;
  92147. };
  92148. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92149. var image = pixel_data;
  92150. var width = header.width, height = header.height;
  92151. var color, i = 0, x, y;
  92152. var imageData = new Uint8Array(width * height * 4);
  92153. for (y = y_start; y !== y_end; y += y_step) {
  92154. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  92155. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  92156. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  92157. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  92158. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  92159. imageData[(x + width * y) * 4 + 0] = r;
  92160. imageData[(x + width * y) * 4 + 1] = g;
  92161. imageData[(x + width * y) * 4 + 2] = b;
  92162. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  92163. }
  92164. }
  92165. return imageData;
  92166. };
  92167. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92168. var image = pixel_data;
  92169. var width = header.width, height = header.height;
  92170. var i = 0, x, y;
  92171. var imageData = new Uint8Array(width * height * 4);
  92172. for (y = y_start; y !== y_end; y += y_step) {
  92173. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  92174. imageData[(x + width * y) * 4 + 3] = 255;
  92175. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92176. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  92177. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  92178. }
  92179. }
  92180. return imageData;
  92181. };
  92182. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92183. var image = pixel_data;
  92184. var width = header.width, height = header.height;
  92185. var i = 0, x, y;
  92186. var imageData = new Uint8Array(width * height * 4);
  92187. for (y = y_start; y !== y_end; y += y_step) {
  92188. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  92189. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92190. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  92191. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  92192. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  92193. }
  92194. }
  92195. return imageData;
  92196. };
  92197. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92198. var image = pixel_data;
  92199. var width = header.width, height = header.height;
  92200. var color, i = 0, x, y;
  92201. var imageData = new Uint8Array(width * height * 4);
  92202. for (y = y_start; y !== y_end; y += y_step) {
  92203. for (x = x_start; x !== x_end; x += x_step, i++) {
  92204. color = image[i];
  92205. imageData[(x + width * y) * 4 + 0] = color;
  92206. imageData[(x + width * y) * 4 + 1] = color;
  92207. imageData[(x + width * y) * 4 + 2] = color;
  92208. imageData[(x + width * y) * 4 + 3] = 255;
  92209. }
  92210. }
  92211. return imageData;
  92212. };
  92213. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  92214. var image = pixel_data;
  92215. var width = header.width, height = header.height;
  92216. var i = 0, x, y;
  92217. var imageData = new Uint8Array(width * height * 4);
  92218. for (y = y_start; y !== y_end; y += y_step) {
  92219. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  92220. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  92221. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  92222. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  92223. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  92224. }
  92225. }
  92226. return imageData;
  92227. };
  92228. //private static _TYPE_NO_DATA = 0;
  92229. TGATools._TYPE_INDEXED = 1;
  92230. TGATools._TYPE_RGB = 2;
  92231. TGATools._TYPE_GREY = 3;
  92232. TGATools._TYPE_RLE_INDEXED = 9;
  92233. TGATools._TYPE_RLE_RGB = 10;
  92234. TGATools._TYPE_RLE_GREY = 11;
  92235. TGATools._ORIGIN_MASK = 0x30;
  92236. TGATools._ORIGIN_SHIFT = 0x04;
  92237. TGATools._ORIGIN_BL = 0x00;
  92238. TGATools._ORIGIN_BR = 0x01;
  92239. TGATools._ORIGIN_UL = 0x02;
  92240. TGATools._ORIGIN_UR = 0x03;
  92241. return TGATools;
  92242. }());
  92243. BABYLON.TGATools = TGATools;
  92244. })(BABYLON || (BABYLON = {}));
  92245. //# sourceMappingURL=babylon.tga.js.map
  92246. var BABYLON;
  92247. (function (BABYLON) {
  92248. /**
  92249. * Implementation of the TGA Texture Loader.
  92250. */
  92251. var TGATextureLoader = /** @class */ (function () {
  92252. function TGATextureLoader() {
  92253. /**
  92254. * Defines wether the loader supports cascade loading the different faces.
  92255. */
  92256. this.supportCascades = false;
  92257. }
  92258. /**
  92259. * This returns if the loader support the current file information.
  92260. * @param extension defines the file extension of the file being loaded
  92261. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92262. * @param fallback defines the fallback internal texture if any
  92263. * @param isBase64 defines whether the texture is encoded as a base64
  92264. * @param isBuffer defines whether the texture data are stored as a buffer
  92265. * @returns true if the loader can load the specified file
  92266. */
  92267. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92268. return extension.indexOf(".tga") === 0;
  92269. };
  92270. /**
  92271. * Transform the url before loading if required.
  92272. * @param rootUrl the url of the texture
  92273. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92274. * @returns the transformed texture
  92275. */
  92276. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92277. return rootUrl;
  92278. };
  92279. /**
  92280. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92281. * @param rootUrl the url of the texture
  92282. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92283. * @returns the fallback texture
  92284. */
  92285. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92286. return null;
  92287. };
  92288. /**
  92289. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92290. * @param data contains the texture data
  92291. * @param texture defines the BabylonJS internal texture
  92292. * @param createPolynomials will be true if polynomials have been requested
  92293. * @param onLoad defines the callback to trigger once the texture is ready
  92294. * @param onError defines the callback to trigger in case of error
  92295. */
  92296. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92297. throw ".env not supported in Cube.";
  92298. };
  92299. /**
  92300. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92301. * @param data contains the texture data
  92302. * @param texture defines the BabylonJS internal texture
  92303. * @param callback defines the method to call once ready to upload
  92304. */
  92305. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  92306. var uintData = new Uint8Array(data);
  92307. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  92308. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  92309. BABYLON.TGATools.UploadContent(texture, uintData);
  92310. });
  92311. };
  92312. return TGATextureLoader;
  92313. }());
  92314. // Register the loader.
  92315. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  92316. })(BABYLON || (BABYLON = {}));
  92317. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  92318. var BABYLON;
  92319. (function (BABYLON) {
  92320. /**
  92321. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  92322. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  92323. */
  92324. var KhronosTextureContainer = /** @class */ (function () {
  92325. /**
  92326. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  92327. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  92328. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  92329. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  92330. */
  92331. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  92332. this.arrayBuffer = arrayBuffer;
  92333. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  92334. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  92335. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  92336. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  92337. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  92338. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  92339. BABYLON.Tools.Error("texture missing KTX identifier");
  92340. return;
  92341. }
  92342. // load the reset of the header in native 32 bit int
  92343. var header = new Int32Array(this.arrayBuffer, 12, 13);
  92344. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  92345. var oppositeEndianess = header[0] === 0x01020304;
  92346. // read all the header elements in order they exist in the file, without modification (sans endainness)
  92347. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  92348. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  92349. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  92350. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  92351. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  92352. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  92353. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  92354. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  92355. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  92356. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  92357. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  92358. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  92359. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  92360. if (this.glType !== 0) {
  92361. BABYLON.Tools.Error("only compressed formats currently supported");
  92362. return;
  92363. }
  92364. else {
  92365. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  92366. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  92367. }
  92368. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  92369. BABYLON.Tools.Error("only 2D textures currently supported");
  92370. return;
  92371. }
  92372. if (this.numberOfArrayElements !== 0) {
  92373. BABYLON.Tools.Error("texture arrays not currently supported");
  92374. return;
  92375. }
  92376. if (this.numberOfFaces !== facesExpected) {
  92377. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  92378. return;
  92379. }
  92380. // we now have a completely validated file, so could use existence of loadType as success
  92381. // would need to make this more elaborate & adjust checks above to support more than one load type
  92382. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  92383. }
  92384. // not as fast hardware based, but will probably never need to use
  92385. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  92386. return ((val & 0xFF) << 24)
  92387. | ((val & 0xFF00) << 8)
  92388. | ((val >> 8) & 0xFF00)
  92389. | ((val >> 24) & 0xFF);
  92390. };
  92391. /**
  92392. * Uploads KTX content to a Babylon Texture.
  92393. * It is assumed that the texture has already been created & is currently bound
  92394. * @hidden
  92395. */
  92396. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  92397. switch (this.loadType) {
  92398. case KhronosTextureContainer.COMPRESSED_2D:
  92399. this._upload2DCompressedLevels(texture, loadMipmaps);
  92400. break;
  92401. case KhronosTextureContainer.TEX_2D:
  92402. case KhronosTextureContainer.COMPRESSED_3D:
  92403. case KhronosTextureContainer.TEX_3D:
  92404. }
  92405. };
  92406. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  92407. // initialize width & height for level 1
  92408. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  92409. var width = this.pixelWidth;
  92410. var height = this.pixelHeight;
  92411. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  92412. for (var level = 0; level < mipmapCount; level++) {
  92413. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  92414. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  92415. for (var face = 0; face < this.numberOfFaces; face++) {
  92416. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  92417. var engine = texture.getEngine();
  92418. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  92419. dataOffset += imageSize; // add size of the image for the next face/mipmap
  92420. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  92421. }
  92422. width = Math.max(1.0, width * 0.5);
  92423. height = Math.max(1.0, height * 0.5);
  92424. }
  92425. };
  92426. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  92427. // load types
  92428. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  92429. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  92430. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  92431. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  92432. return KhronosTextureContainer;
  92433. }());
  92434. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  92435. })(BABYLON || (BABYLON = {}));
  92436. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  92437. var BABYLON;
  92438. (function (BABYLON) {
  92439. /**
  92440. * Implementation of the KTX Texture Loader.
  92441. */
  92442. var KTXTextureLoader = /** @class */ (function () {
  92443. function KTXTextureLoader() {
  92444. /**
  92445. * Defines wether the loader supports cascade loading the different faces.
  92446. */
  92447. this.supportCascades = false;
  92448. }
  92449. /**
  92450. * This returns if the loader support the current file information.
  92451. * @param extension defines the file extension of the file being loaded
  92452. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92453. * @param fallback defines the fallback internal texture if any
  92454. * @param isBase64 defines whether the texture is encoded as a base64
  92455. * @param isBuffer defines whether the texture data are stored as a buffer
  92456. * @returns true if the loader can load the specified file
  92457. */
  92458. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92459. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  92460. return true;
  92461. }
  92462. return false;
  92463. };
  92464. /**
  92465. * Transform the url before loading if required.
  92466. * @param rootUrl the url of the texture
  92467. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92468. * @returns the transformed texture
  92469. */
  92470. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92471. var lastDot = rootUrl.lastIndexOf('.');
  92472. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  92473. };
  92474. /**
  92475. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92476. * @param rootUrl the url of the texture
  92477. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92478. * @returns the fallback texture
  92479. */
  92480. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92481. // remove the format appended to the rootUrl in the original createCubeTexture call.
  92482. var exp = new RegExp("" + textureFormatInUse + "$");
  92483. return rootUrl.replace(exp, "");
  92484. };
  92485. /**
  92486. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92487. * @param data contains the texture data
  92488. * @param texture defines the BabylonJS internal texture
  92489. * @param createPolynomials will be true if polynomials have been requested
  92490. * @param onLoad defines the callback to trigger once the texture is ready
  92491. * @param onError defines the callback to trigger in case of error
  92492. */
  92493. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92494. if (Array.isArray(data)) {
  92495. return;
  92496. }
  92497. var engine = texture.getEngine();
  92498. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  92499. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  92500. engine._unpackFlipY(true);
  92501. ktx.uploadLevels(texture, texture.generateMipMaps);
  92502. texture.width = ktx.pixelWidth;
  92503. texture.height = ktx.pixelHeight;
  92504. engine._setCubeMapTextureParams(loadMipmap);
  92505. texture.isReady = true;
  92506. };
  92507. /**
  92508. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92509. * @param data contains the texture data
  92510. * @param texture defines the BabylonJS internal texture
  92511. * @param callback defines the method to call once ready to upload
  92512. */
  92513. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  92514. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  92515. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  92516. ktx.uploadLevels(texture, texture.generateMipMaps);
  92517. });
  92518. };
  92519. return KTXTextureLoader;
  92520. }());
  92521. // Register the loader.
  92522. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  92523. })(BABYLON || (BABYLON = {}));
  92524. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  92525. var BABYLON;
  92526. (function (BABYLON) {
  92527. /**
  92528. * Sets of helpers addressing the serialization and deserialization of environment texture
  92529. * stored in a BabylonJS env file.
  92530. * Those files are usually stored as .env files.
  92531. */
  92532. var EnvironmentTextureTools = /** @class */ (function () {
  92533. function EnvironmentTextureTools() {
  92534. }
  92535. /**
  92536. * Gets the environment info from an env file.
  92537. * @param data The array buffer containing the .env bytes.
  92538. * @returns the environment file info (the json header) if successfully parsed.
  92539. */
  92540. EnvironmentTextureTools.GetEnvInfo = function (data) {
  92541. var dataView = new DataView(data);
  92542. var pos = 0;
  92543. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92544. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  92545. BABYLON.Tools.Error('Not a babylon environment map');
  92546. return null;
  92547. }
  92548. }
  92549. // Read json manifest - collect characters up to null terminator
  92550. var manifestString = '';
  92551. var charCode = 0x00;
  92552. while ((charCode = dataView.getUint8(pos++))) {
  92553. manifestString += String.fromCharCode(charCode);
  92554. }
  92555. var manifest = JSON.parse(manifestString);
  92556. if (manifest.specular) {
  92557. // Extend the header with the position of the payload.
  92558. manifest.specular.specularDataPosition = pos;
  92559. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  92560. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  92561. }
  92562. return manifest;
  92563. };
  92564. /**
  92565. * Creates an environment texture from a loaded cube texture.
  92566. * @param texture defines the cube texture to convert in env file
  92567. * @return a promise containing the environment data if succesfull.
  92568. */
  92569. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  92570. var _this = this;
  92571. var internalTexture = texture.getInternalTexture();
  92572. if (!internalTexture) {
  92573. return Promise.reject("The cube texture is invalid.");
  92574. }
  92575. if (!texture._prefiltered) {
  92576. return Promise.reject("The cube texture is invalid (not prefiltered).");
  92577. }
  92578. var engine = internalTexture.getEngine();
  92579. if (engine && engine.premultipliedAlpha) {
  92580. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  92581. }
  92582. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  92583. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  92584. }
  92585. var canvas = engine.getRenderingCanvas();
  92586. if (!canvas) {
  92587. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  92588. }
  92589. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92590. if (!engine.getCaps().textureFloatRender) {
  92591. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92592. if (!engine.getCaps().textureHalfFloatRender) {
  92593. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  92594. }
  92595. }
  92596. var cubeWidth = internalTexture.width;
  92597. var hostingScene = new BABYLON.Scene(engine);
  92598. var specularTextures = {};
  92599. var promises = [];
  92600. // Read and collect all mipmaps data from the cube.
  92601. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  92602. mipmapsCount = Math.round(mipmapsCount);
  92603. var _loop_1 = function (i) {
  92604. var faceWidth = Math.pow(2, mipmapsCount - i);
  92605. var _loop_2 = function (face) {
  92606. var data = texture.readPixels(face, i);
  92607. // Creates a temp texture with the face data.
  92608. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  92609. // And rgbdEncode them.
  92610. var promise = new Promise(function (resolve, reject) {
  92611. 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);
  92612. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92613. rgbdPostProcess.onApply = function (effect) {
  92614. effect._bindTexture("textureSampler", tempTexture);
  92615. };
  92616. // As the process needs to happen on the main canvas, keep track of the current size
  92617. var currentW = engine.getRenderWidth();
  92618. var currentH = engine.getRenderHeight();
  92619. // Set the desired size for the texture
  92620. engine.setSize(faceWidth, faceWidth);
  92621. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  92622. // Reading datas from WebGL
  92623. BABYLON.Tools.ToBlob(canvas, function (blob) {
  92624. var fileReader = new FileReader();
  92625. fileReader.onload = function (event) {
  92626. var arrayBuffer = event.target.result;
  92627. specularTextures[i * 6 + face] = arrayBuffer;
  92628. resolve();
  92629. };
  92630. fileReader.readAsArrayBuffer(blob);
  92631. });
  92632. // Reapply the previous canvas size
  92633. engine.setSize(currentW, currentH);
  92634. });
  92635. });
  92636. promises.push(promise);
  92637. };
  92638. // All faces of the cube.
  92639. for (var face = 0; face < 6; face++) {
  92640. _loop_2(face);
  92641. }
  92642. };
  92643. for (var i = 0; i <= mipmapsCount; i++) {
  92644. _loop_1(i);
  92645. }
  92646. // Once all the textures haves been collected as RGBD stored in PNGs
  92647. return Promise.all(promises).then(function () {
  92648. // We can delete the hosting scene keeping track of all the creation objects
  92649. hostingScene.dispose();
  92650. // Creates the json header for the env texture
  92651. var info = {
  92652. version: 1,
  92653. width: cubeWidth,
  92654. irradiance: _this._CreateEnvTextureIrradiance(texture),
  92655. specular: {
  92656. mipmaps: [],
  92657. lodGenerationScale: texture.lodGenerationScale
  92658. }
  92659. };
  92660. // Sets the specular image data information
  92661. var position = 0;
  92662. for (var i = 0; i <= mipmapsCount; i++) {
  92663. for (var face = 0; face < 6; face++) {
  92664. var byteLength = specularTextures[i * 6 + face].byteLength;
  92665. info.specular.mipmaps.push({
  92666. length: byteLength,
  92667. position: position
  92668. });
  92669. position += byteLength;
  92670. }
  92671. }
  92672. // Encode the JSON as an array buffer
  92673. var infoString = JSON.stringify(info);
  92674. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  92675. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  92676. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  92677. infoView[i] = infoString.charCodeAt(i);
  92678. }
  92679. // Ends up with a null terminator for easier parsing
  92680. infoView[infoString.length] = 0x00;
  92681. // Computes the final required size and creates the storage
  92682. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  92683. var finalBuffer = new ArrayBuffer(totalSize);
  92684. var finalBufferView = new Uint8Array(finalBuffer);
  92685. var dataView = new DataView(finalBuffer);
  92686. // Copy the magic bytes identifying the file in
  92687. var pos = 0;
  92688. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92689. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  92690. }
  92691. // Add the json info
  92692. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  92693. pos += infoBuffer.byteLength;
  92694. // Finally inserts the texture data
  92695. for (var i = 0; i <= mipmapsCount; i++) {
  92696. for (var face = 0; face < 6; face++) {
  92697. var dataBuffer = specularTextures[i * 6 + face];
  92698. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  92699. pos += dataBuffer.byteLength;
  92700. }
  92701. }
  92702. // Voila
  92703. return finalBuffer;
  92704. });
  92705. };
  92706. /**
  92707. * Creates a JSON representation of the spherical data.
  92708. * @param texture defines the texture containing the polynomials
  92709. * @return the JSON representation of the spherical info
  92710. */
  92711. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  92712. var polynmials = texture.sphericalPolynomial;
  92713. if (polynmials == null) {
  92714. return null;
  92715. }
  92716. return {
  92717. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  92718. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  92719. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  92720. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  92721. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  92722. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  92723. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  92724. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  92725. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  92726. };
  92727. };
  92728. /**
  92729. * Uploads the texture info contained in the env file to the GPU.
  92730. * @param texture defines the internal texture to upload to
  92731. * @param arrayBuffer defines the buffer cotaining the data to load
  92732. * @param info defines the texture info retrieved through the GetEnvInfo method
  92733. * @returns a promise
  92734. */
  92735. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  92736. if (info.version !== 1) {
  92737. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  92738. }
  92739. var specularInfo = info.specular;
  92740. if (!specularInfo) {
  92741. // Nothing else parsed so far
  92742. return Promise.resolve();
  92743. }
  92744. // Double checks the enclosed info
  92745. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  92746. mipmapsCount = Math.round(mipmapsCount) + 1;
  92747. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  92748. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  92749. }
  92750. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  92751. var imageData = new Array(mipmapsCount);
  92752. for (var i = 0; i < mipmapsCount; i++) {
  92753. imageData[i] = new Array(6);
  92754. for (var face = 0; face < 6; face++) {
  92755. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  92756. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  92757. }
  92758. }
  92759. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  92760. };
  92761. /**
  92762. * Uploads the levels of image data to the GPU.
  92763. * @param texture defines the internal texture to upload to
  92764. * @param imageData defines the array buffer views of image data [mipmap][face]
  92765. * @returns a promise
  92766. */
  92767. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  92768. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  92769. throw new Error("Texture size must be a power of two");
  92770. }
  92771. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  92772. // Gets everything ready.
  92773. var engine = texture.getEngine();
  92774. var expandTexture = false;
  92775. var generateNonLODTextures = false;
  92776. var rgbdPostProcess = null;
  92777. var cubeRtt = null;
  92778. var lodTextures = null;
  92779. var caps = engine.getCaps();
  92780. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  92781. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92782. texture.generateMipMaps = true;
  92783. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  92784. // Add extra process if texture lod is not supported
  92785. if (!caps.textureLOD) {
  92786. expandTexture = false;
  92787. generateNonLODTextures = true;
  92788. lodTextures = {};
  92789. }
  92790. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92791. else if (engine.webGLVersion < 2) {
  92792. expandTexture = false;
  92793. }
  92794. // If half float available we can uncompress the texture
  92795. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92796. expandTexture = true;
  92797. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92798. }
  92799. // If full float available we can uncompress the texture
  92800. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92801. expandTexture = true;
  92802. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92803. }
  92804. // Expand the texture if possible
  92805. if (expandTexture) {
  92806. // Simply run through the decode PP
  92807. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92808. texture._isRGBD = false;
  92809. texture.invertY = false;
  92810. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92811. generateDepthBuffer: false,
  92812. generateMipMaps: true,
  92813. generateStencilBuffer: false,
  92814. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92815. type: texture.type,
  92816. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92817. });
  92818. }
  92819. else {
  92820. texture._isRGBD = true;
  92821. texture.invertY = true;
  92822. // In case of missing support, applies the same patch than DDS files.
  92823. if (generateNonLODTextures) {
  92824. var mipSlices = 3;
  92825. var scale = texture._lodGenerationScale;
  92826. var offset = texture._lodGenerationOffset;
  92827. for (var i = 0; i < mipSlices; i++) {
  92828. //compute LOD from even spacing in smoothness (matching shader calculation)
  92829. var smoothness = i / (mipSlices - 1);
  92830. var roughness = 1 - smoothness;
  92831. var minLODIndex = offset; // roughness = 0
  92832. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92833. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92834. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92835. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92836. glTextureFromLod.isCube = true;
  92837. glTextureFromLod.invertY = true;
  92838. glTextureFromLod.generateMipMaps = false;
  92839. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92840. // Wrap in a base texture for easy binding.
  92841. var lodTexture = new BABYLON.BaseTexture(null);
  92842. lodTexture.isCube = true;
  92843. lodTexture._texture = glTextureFromLod;
  92844. lodTextures[mipmapIndex] = lodTexture;
  92845. switch (i) {
  92846. case 0:
  92847. texture._lodTextureLow = lodTexture;
  92848. break;
  92849. case 1:
  92850. texture._lodTextureMid = lodTexture;
  92851. break;
  92852. case 2:
  92853. texture._lodTextureHigh = lodTexture;
  92854. break;
  92855. }
  92856. }
  92857. }
  92858. }
  92859. var promises = [];
  92860. var _loop_3 = function (i) {
  92861. var _loop_4 = function (face) {
  92862. // Constructs an image element from image data
  92863. var bytes = imageData[i][face];
  92864. var blob = new Blob([bytes], { type: 'image/png' });
  92865. var url = URL.createObjectURL(blob);
  92866. var image = new Image();
  92867. image.src = url;
  92868. // Enqueue promise to upload to the texture.
  92869. var promise = new Promise(function (resolve, reject) {
  92870. image.onload = function () {
  92871. if (expandTexture) {
  92872. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92873. reject(message);
  92874. }, image);
  92875. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92876. // Uncompress the data to a RTT
  92877. rgbdPostProcess.onApply = function (effect) {
  92878. effect._bindTexture("textureSampler", tempTexture_1);
  92879. effect.setFloat2("scale", 1, 1);
  92880. };
  92881. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92882. // Cleanup
  92883. engine.restoreDefaultFramebuffer();
  92884. tempTexture_1.dispose();
  92885. window.URL.revokeObjectURL(url);
  92886. resolve();
  92887. });
  92888. }
  92889. else {
  92890. engine._uploadImageToTexture(texture, image, face, i);
  92891. // Upload the face to the non lod texture support
  92892. if (generateNonLODTextures) {
  92893. var lodTexture = lodTextures[i];
  92894. if (lodTexture) {
  92895. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92896. }
  92897. }
  92898. resolve();
  92899. }
  92900. };
  92901. image.onerror = function (error) {
  92902. reject(error);
  92903. };
  92904. });
  92905. promises.push(promise);
  92906. };
  92907. // All faces
  92908. for (var face = 0; face < 6; face++) {
  92909. _loop_4(face);
  92910. }
  92911. };
  92912. // All mipmaps up to provided number of images
  92913. for (var i = 0; i < imageData.length; i++) {
  92914. _loop_3(i);
  92915. }
  92916. // Fill remaining mipmaps with black textures.
  92917. if (imageData.length < mipmapsCount) {
  92918. var data = void 0;
  92919. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92920. var dataLength = size * size * 4;
  92921. switch (texture.type) {
  92922. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92923. data = new Uint8Array(dataLength);
  92924. break;
  92925. }
  92926. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92927. data = new Uint16Array(dataLength);
  92928. break;
  92929. }
  92930. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92931. data = new Float32Array(dataLength);
  92932. break;
  92933. }
  92934. }
  92935. for (var i = imageData.length; i < mipmapsCount; i++) {
  92936. for (var face = 0; face < 6; face++) {
  92937. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92938. }
  92939. }
  92940. }
  92941. // Once all done, finishes the cleanup and return
  92942. return Promise.all(promises).then(function () {
  92943. // Release temp RTT.
  92944. if (cubeRtt) {
  92945. engine._releaseFramebufferObjects(cubeRtt);
  92946. cubeRtt._swapAndDie(texture);
  92947. }
  92948. // Release temp Post Process.
  92949. if (rgbdPostProcess) {
  92950. rgbdPostProcess.dispose();
  92951. }
  92952. // Flag internal texture as ready in case they are in use.
  92953. if (generateNonLODTextures) {
  92954. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92955. texture._lodTextureHigh._texture.isReady = true;
  92956. }
  92957. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92958. texture._lodTextureMid._texture.isReady = true;
  92959. }
  92960. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92961. texture._lodTextureLow._texture.isReady = true;
  92962. }
  92963. }
  92964. });
  92965. };
  92966. /**
  92967. * Uploads spherical polynomials information to the texture.
  92968. * @param texture defines the texture we are trying to upload the information to
  92969. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92970. */
  92971. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92972. if (info.version !== 1) {
  92973. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92974. }
  92975. var irradianceInfo = info.irradiance;
  92976. if (!irradianceInfo) {
  92977. return;
  92978. }
  92979. var sp = new BABYLON.SphericalPolynomial();
  92980. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92981. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92982. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92983. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92984. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92985. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92986. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92987. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92988. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92989. texture._sphericalPolynomial = sp;
  92990. };
  92991. /**
  92992. * Magic number identifying the env file.
  92993. */
  92994. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92995. return EnvironmentTextureTools;
  92996. }());
  92997. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92998. })(BABYLON || (BABYLON = {}));
  92999. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  93000. var BABYLON;
  93001. (function (BABYLON) {
  93002. /**
  93003. * Implementation of the ENV Texture Loader.
  93004. */
  93005. var ENVTextureLoader = /** @class */ (function () {
  93006. function ENVTextureLoader() {
  93007. /**
  93008. * Defines wether the loader supports cascade loading the different faces.
  93009. */
  93010. this.supportCascades = false;
  93011. }
  93012. /**
  93013. * This returns if the loader support the current file information.
  93014. * @param extension defines the file extension of the file being loaded
  93015. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93016. * @param fallback defines the fallback internal texture if any
  93017. * @param isBase64 defines whether the texture is encoded as a base64
  93018. * @param isBuffer defines whether the texture data are stored as a buffer
  93019. * @returns true if the loader can load the specified file
  93020. */
  93021. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93022. return extension.indexOf(".env") === 0;
  93023. };
  93024. /**
  93025. * Transform the url before loading if required.
  93026. * @param rootUrl the url of the texture
  93027. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93028. * @returns the transformed texture
  93029. */
  93030. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93031. return rootUrl;
  93032. };
  93033. /**
  93034. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93035. * @param rootUrl the url of the texture
  93036. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93037. * @returns the fallback texture
  93038. */
  93039. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93040. return null;
  93041. };
  93042. /**
  93043. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93044. * @param data contains the texture data
  93045. * @param texture defines the BabylonJS internal texture
  93046. * @param createPolynomials will be true if polynomials have been requested
  93047. * @param onLoad defines the callback to trigger once the texture is ready
  93048. * @param onError defines the callback to trigger in case of error
  93049. */
  93050. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93051. if (Array.isArray(data)) {
  93052. return;
  93053. }
  93054. data = data;
  93055. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  93056. if (info) {
  93057. texture.width = info.width;
  93058. texture.height = info.width;
  93059. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  93060. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  93061. texture.isReady = true;
  93062. if (onLoad) {
  93063. onLoad();
  93064. }
  93065. });
  93066. }
  93067. else if (onError) {
  93068. onError("Can not parse the environment file", null);
  93069. }
  93070. };
  93071. /**
  93072. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93073. * @param data contains the texture data
  93074. * @param texture defines the BabylonJS internal texture
  93075. * @param callback defines the method to call once ready to upload
  93076. */
  93077. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  93078. throw ".env not supported in 2d.";
  93079. };
  93080. return ENVTextureLoader;
  93081. }());
  93082. // Register the loader.
  93083. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  93084. })(BABYLON || (BABYLON = {}));
  93085. //# sourceMappingURL=babylon.envTextureLoader.js.map
  93086. var BABYLON;
  93087. (function (BABYLON) {
  93088. /**
  93089. * Renders a layer on top of an existing scene
  93090. */
  93091. var UtilityLayerRenderer = /** @class */ (function () {
  93092. /**
  93093. * Instantiates a UtilityLayerRenderer
  93094. * @param originalScene the original scene that will be rendered on top of
  93095. */
  93096. function UtilityLayerRenderer(
  93097. /** the original scene that will be rendered on top of */
  93098. originalScene) {
  93099. var _this = this;
  93100. this.originalScene = originalScene;
  93101. this._pointerCaptures = {};
  93102. this._lastPointerEvents = {};
  93103. /**
  93104. * If the utility layer should automatically be rendered on top of existing scene
  93105. */
  93106. this.shouldRender = true;
  93107. /**
  93108. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  93109. */
  93110. this.onlyCheckPointerDownEvents = true;
  93111. /**
  93112. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  93113. */
  93114. this.processAllEvents = false;
  93115. /**
  93116. * Observable raised when the pointer move from the utility layer scene to the main scene
  93117. */
  93118. this.onPointerOutObservable = new BABYLON.Observable();
  93119. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  93120. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  93121. this.utilityLayerScene._allowPostProcessClearColor = false;
  93122. originalScene.getEngine().scenes.pop();
  93123. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  93124. this.utilityLayerScene.detachControl();
  93125. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  93126. if (!_this.processAllEvents) {
  93127. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  93128. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  93129. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  93130. return;
  93131. }
  93132. }
  93133. var pointerEvent = (prePointerInfo.event);
  93134. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  93135. _this._pointerCaptures[pointerEvent.pointerId] = false;
  93136. return;
  93137. }
  93138. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  93139. if (!prePointerInfo.ray && utilityScenePick) {
  93140. prePointerInfo.ray = utilityScenePick.ray;
  93141. }
  93142. // always fire the prepointer oversvable
  93143. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  93144. // allow every non pointer down event to flow to the utility layer
  93145. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  93146. if (!prePointerInfo.skipOnPointerObservable) {
  93147. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  93148. }
  93149. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  93150. _this._pointerCaptures[pointerEvent.pointerId] = false;
  93151. }
  93152. return;
  93153. }
  93154. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  93155. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  93156. if (utilityScenePick && utilityScenePick.hit) {
  93157. if (!prePointerInfo.skipOnPointerObservable) {
  93158. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  93159. }
  93160. prePointerInfo.skipOnPointerObservable = true;
  93161. }
  93162. }
  93163. else {
  93164. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  93165. var pointerEvent_1 = (prePointerInfo.event);
  93166. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  93167. if (originalScenePick && utilityScenePick) {
  93168. // No pick in utility scene
  93169. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  93170. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  93171. // We touched an utility mesh present in the main scene
  93172. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  93173. prePointerInfo.skipOnPointerObservable = true;
  93174. }
  93175. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93176. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  93177. }
  93178. }
  93179. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  93180. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  93181. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  93182. // If a previous utility layer set this, do not unset this
  93183. if (!prePointerInfo.skipOnPointerObservable) {
  93184. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  93185. }
  93186. }
  93187. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  93188. // We have a pick in both scenes but main is closer than utility
  93189. // We touched an utility mesh present in the main scene
  93190. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  93191. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  93192. prePointerInfo.skipOnPointerObservable = true;
  93193. }
  93194. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  93195. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  93196. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  93197. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  93198. }
  93199. }
  93200. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  93201. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  93202. }
  93203. }
  93204. }
  93205. });
  93206. // Render directly on top of existing scene without clearing
  93207. this.utilityLayerScene.autoClear = false;
  93208. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  93209. if (_this.shouldRender) {
  93210. _this.render();
  93211. }
  93212. });
  93213. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  93214. _this.dispose();
  93215. });
  93216. this._updateCamera();
  93217. }
  93218. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  93219. /**
  93220. * 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)
  93221. */
  93222. get: function () {
  93223. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  93224. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  93225. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  93226. UtilityLayerRenderer._DefaultUtilityLayer = null;
  93227. });
  93228. }
  93229. return UtilityLayerRenderer._DefaultUtilityLayer;
  93230. },
  93231. enumerable: true,
  93232. configurable: true
  93233. });
  93234. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  93235. /**
  93236. * 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)
  93237. */
  93238. get: function () {
  93239. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  93240. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  93241. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  93242. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  93243. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  93244. });
  93245. }
  93246. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  93247. },
  93248. enumerable: true,
  93249. configurable: true
  93250. });
  93251. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  93252. if (!prePointerInfo.skipOnPointerObservable) {
  93253. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  93254. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  93255. }
  93256. };
  93257. /**
  93258. * Renders the utility layers scene on top of the original scene
  93259. */
  93260. UtilityLayerRenderer.prototype.render = function () {
  93261. this._updateCamera();
  93262. if (this.utilityLayerScene.activeCamera) {
  93263. // Set the camera's scene to utility layers scene
  93264. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  93265. var camera = this.utilityLayerScene.activeCamera;
  93266. camera._scene = this.utilityLayerScene;
  93267. if (camera.leftCamera) {
  93268. camera.leftCamera._scene = this.utilityLayerScene;
  93269. }
  93270. if (camera.rightCamera) {
  93271. camera.rightCamera._scene = this.utilityLayerScene;
  93272. }
  93273. this.utilityLayerScene.render(false);
  93274. // Reset camera's scene back to original
  93275. camera._scene = oldScene;
  93276. if (camera.leftCamera) {
  93277. camera.leftCamera._scene = oldScene;
  93278. }
  93279. if (camera.rightCamera) {
  93280. camera.rightCamera._scene = oldScene;
  93281. }
  93282. }
  93283. };
  93284. /**
  93285. * Disposes of the renderer
  93286. */
  93287. UtilityLayerRenderer.prototype.dispose = function () {
  93288. this.onPointerOutObservable.clear();
  93289. if (this._afterRenderObserver) {
  93290. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  93291. }
  93292. if (this._sceneDisposeObserver) {
  93293. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93294. }
  93295. if (this._originalPointerObserver) {
  93296. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  93297. }
  93298. this.utilityLayerScene.dispose();
  93299. };
  93300. UtilityLayerRenderer.prototype._updateCamera = function () {
  93301. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  93302. };
  93303. UtilityLayerRenderer._DefaultUtilityLayer = null;
  93304. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  93305. return UtilityLayerRenderer;
  93306. }());
  93307. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  93308. })(BABYLON || (BABYLON = {}));
  93309. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  93310. //# sourceMappingURL=babylon.behavior.js.map
  93311. var BABYLON;
  93312. (function (BABYLON) {
  93313. /**
  93314. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  93315. */
  93316. var PointerDragBehavior = /** @class */ (function () {
  93317. /**
  93318. * Creates a pointer drag behavior that can be attached to a mesh
  93319. * @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)
  93320. */
  93321. function PointerDragBehavior(options) {
  93322. /**
  93323. * 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)
  93324. */
  93325. this.maxDragAngle = 0;
  93326. /**
  93327. * @hidden
  93328. */
  93329. this._useAlternatePickedPointAboveMaxDragAngle = false;
  93330. /**
  93331. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93332. */
  93333. this.currentDraggingPointerID = -1;
  93334. /**
  93335. * If the behavior is currently in a dragging state
  93336. */
  93337. this.dragging = false;
  93338. /**
  93339. * 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)
  93340. */
  93341. this.dragDeltaRatio = 0.2;
  93342. /**
  93343. * If the drag plane orientation should be updated during the dragging (Default: true)
  93344. */
  93345. this.updateDragPlane = true;
  93346. // Debug mode will display drag planes to help visualize behavior
  93347. this._debugMode = false;
  93348. this._moving = false;
  93349. /**
  93350. * Fires each time the attached mesh is dragged with the pointer
  93351. * * delta between last drag position and current drag position in world space
  93352. * * dragDistance along the drag axis
  93353. * * dragPlaneNormal normal of the current drag plane used during the drag
  93354. * * dragPlanePoint in world space where the drag intersects the drag plane
  93355. */
  93356. this.onDragObservable = new BABYLON.Observable();
  93357. /**
  93358. * Fires each time a drag begins (eg. mouse down on mesh)
  93359. */
  93360. this.onDragStartObservable = new BABYLON.Observable();
  93361. /**
  93362. * Fires each time a drag ends (eg. mouse release after drag)
  93363. */
  93364. this.onDragEndObservable = new BABYLON.Observable();
  93365. /**
  93366. * If the attached mesh should be moved when dragged
  93367. */
  93368. this.moveAttached = true;
  93369. /**
  93370. * If the drag behavior will react to drag events (Default: true)
  93371. */
  93372. this.enabled = true;
  93373. /**
  93374. * If camera controls should be detached during the drag
  93375. */
  93376. this.detachCameraControls = true;
  93377. /**
  93378. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  93379. */
  93380. this.useObjectOrienationForDragging = true;
  93381. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93382. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  93383. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  93384. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93385. this._attachedElement = null;
  93386. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93387. this._lastPointerRay = {};
  93388. this._dragDelta = new BABYLON.Vector3();
  93389. // Variables to avoid instantiation in the below method
  93390. this._pointA = new BABYLON.Vector3(0, 0, 0);
  93391. this._pointB = new BABYLON.Vector3(0, 0, 0);
  93392. this._pointC = new BABYLON.Vector3(0, 0, 0);
  93393. this._lineA = new BABYLON.Vector3(0, 0, 0);
  93394. this._lineB = new BABYLON.Vector3(0, 0, 0);
  93395. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  93396. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  93397. this._options = options ? options : {};
  93398. var optionCount = 0;
  93399. if (this._options.dragAxis) {
  93400. optionCount++;
  93401. }
  93402. if (this._options.dragPlaneNormal) {
  93403. optionCount++;
  93404. }
  93405. if (optionCount > 1) {
  93406. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  93407. }
  93408. }
  93409. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  93410. /**
  93411. * The name of the behavior
  93412. */
  93413. get: function () {
  93414. return "PointerDrag";
  93415. },
  93416. enumerable: true,
  93417. configurable: true
  93418. });
  93419. /**
  93420. * Initializes the behavior
  93421. */
  93422. PointerDragBehavior.prototype.init = function () { };
  93423. /**
  93424. * Attaches the drag behavior the passed in mesh
  93425. * @param ownerNode The mesh that will be dragged around once attached
  93426. */
  93427. PointerDragBehavior.prototype.attach = function (ownerNode) {
  93428. var _this = this;
  93429. this._scene = ownerNode.getScene();
  93430. this._attachedNode = ownerNode;
  93431. // Initialize drag plane to not interfere with existing scene
  93432. if (!PointerDragBehavior._planeScene) {
  93433. if (this._debugMode) {
  93434. PointerDragBehavior._planeScene = this._scene;
  93435. }
  93436. else {
  93437. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  93438. PointerDragBehavior._planeScene.detachControl();
  93439. this._scene.getEngine().scenes.pop();
  93440. this._scene.onDisposeObservable.addOnce(function () {
  93441. PointerDragBehavior._planeScene.dispose();
  93442. PointerDragBehavior._planeScene = null;
  93443. });
  93444. }
  93445. }
  93446. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  93447. // State of the drag
  93448. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  93449. var pickPredicate = function (m) {
  93450. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  93451. };
  93452. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93453. if (!_this.enabled) {
  93454. return;
  93455. }
  93456. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93457. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93458. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  93459. }
  93460. }
  93461. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93462. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93463. _this.releaseDrag();
  93464. }
  93465. }
  93466. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93467. var pointerId = pointerInfo.event.pointerId;
  93468. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  93469. if (!_this._lastPointerRay[pointerId]) {
  93470. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93471. }
  93472. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  93473. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  93474. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  93475. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  93476. _this._moveDrag(pointerInfo.pickInfo.ray);
  93477. }
  93478. }
  93479. }
  93480. });
  93481. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93482. if (_this._moving && _this.moveAttached) {
  93483. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  93484. // Slowly move mesh to avoid jitter
  93485. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  93486. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  93487. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  93488. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  93489. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  93490. }
  93491. });
  93492. };
  93493. PointerDragBehavior.prototype.releaseDrag = function () {
  93494. this.dragging = false;
  93495. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  93496. this.currentDraggingPointerID = -1;
  93497. this._moving = false;
  93498. // Reattach camera controls
  93499. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93500. this._scene.activeCamera.attachControl(this._attachedElement, true);
  93501. }
  93502. };
  93503. /**
  93504. * Simulates the start of a pointer drag event on the behavior
  93505. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  93506. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  93507. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  93508. */
  93509. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  93510. if (pointerId === void 0) { pointerId = 1; }
  93511. this._startDrag(pointerId, fromRay, startPickedPoint);
  93512. if (this._lastPointerRay[pointerId]) {
  93513. // if there was a last pointer ray drag the object there
  93514. this._moveDrag(this._lastPointerRay[pointerId]);
  93515. }
  93516. };
  93517. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  93518. if (pointerId === void 0) { pointerId = 1; }
  93519. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  93520. return;
  93521. }
  93522. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  93523. // Create start ray from the camera to the object
  93524. if (fromRay) {
  93525. this._startDragRay.direction.copyFrom(fromRay.direction);
  93526. this._startDragRay.origin.copyFrom(fromRay.origin);
  93527. }
  93528. else {
  93529. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  93530. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  93531. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  93532. }
  93533. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  93534. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  93535. if (pickedPoint) {
  93536. this.dragging = true;
  93537. this.currentDraggingPointerID = pointerId;
  93538. this.lastDragPosition.copyFrom(pickedPoint);
  93539. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  93540. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  93541. // Detatch camera controls
  93542. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93543. if (this._scene.activeCamera.inputs.attachedElement) {
  93544. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  93545. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  93546. }
  93547. else {
  93548. this._attachedElement = null;
  93549. }
  93550. }
  93551. }
  93552. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  93553. };
  93554. PointerDragBehavior.prototype._moveDrag = function (ray) {
  93555. this._moving = true;
  93556. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  93557. if (pickedPoint) {
  93558. if (this.updateDragPlane) {
  93559. this._updateDragPlanePosition(ray, pickedPoint);
  93560. }
  93561. var dragLength = 0;
  93562. // depending on the drag mode option drag accordingly
  93563. if (this._options.dragAxis) {
  93564. // Convert local drag axis to world
  93565. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  93566. // Project delta drag from the drag plane onto the drag axis
  93567. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  93568. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  93569. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  93570. }
  93571. else {
  93572. dragLength = this._dragDelta.length();
  93573. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  93574. }
  93575. this._targetPosition.addInPlace(this._dragDelta);
  93576. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  93577. this.lastDragPosition.copyFrom(pickedPoint);
  93578. }
  93579. };
  93580. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  93581. var _this = this;
  93582. if (!ray) {
  93583. return null;
  93584. }
  93585. // Calculate angle between plane normal and ray
  93586. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  93587. // Correct if ray is casted from oposite side
  93588. if (angle > Math.PI / 2) {
  93589. angle = Math.PI - angle;
  93590. }
  93591. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  93592. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  93593. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  93594. // Invert ray direction along the towards object axis
  93595. this._tmpVector.copyFrom(ray.direction);
  93596. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  93597. this._alternatePickedPoint.normalize();
  93598. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  93599. this._tmpVector.addInPlace(this._alternatePickedPoint);
  93600. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  93601. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  93602. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  93603. this._alternatePickedPoint.addInPlace(this._tmpVector);
  93604. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  93605. return this._alternatePickedPoint;
  93606. }
  93607. else {
  93608. return null;
  93609. }
  93610. }
  93611. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  93612. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  93613. return pickResult.pickedPoint;
  93614. }
  93615. else {
  93616. return null;
  93617. }
  93618. };
  93619. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  93620. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  93621. this._pointA.copyFrom(dragPlanePosition);
  93622. if (this._options.dragAxis) {
  93623. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  93624. // Calculate plane normal in direction of camera but perpendicular to drag axis
  93625. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  93626. ray.origin.subtractToRef(this._pointA, this._pointC);
  93627. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  93628. // Get perpendicular line from direction to camera and drag axis
  93629. this._pointB.subtractToRef(this._pointA, this._lineA);
  93630. this._pointC.subtractToRef(this._pointA, this._lineB);
  93631. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  93632. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  93633. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  93634. this._lookAt.normalize();
  93635. this._dragPlane.position.copyFrom(this._pointA);
  93636. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  93637. this._dragPlane.lookAt(this._lookAt);
  93638. }
  93639. else if (this._options.dragPlaneNormal) {
  93640. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  93641. this._dragPlane.position.copyFrom(this._pointA);
  93642. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  93643. this._dragPlane.lookAt(this._lookAt);
  93644. }
  93645. else {
  93646. this._dragPlane.position.copyFrom(this._pointA);
  93647. this._dragPlane.lookAt(ray.origin);
  93648. }
  93649. this._dragPlane.computeWorldMatrix(true);
  93650. };
  93651. /**
  93652. * Detaches the behavior from the mesh
  93653. */
  93654. PointerDragBehavior.prototype.detach = function () {
  93655. if (this._pointerObserver) {
  93656. this._scene.onPointerObservable.remove(this._pointerObserver);
  93657. }
  93658. if (this._beforeRenderObserver) {
  93659. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93660. }
  93661. };
  93662. return PointerDragBehavior;
  93663. }());
  93664. BABYLON.PointerDragBehavior = PointerDragBehavior;
  93665. })(BABYLON || (BABYLON = {}));
  93666. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  93667. var BABYLON;
  93668. (function (BABYLON) {
  93669. /**
  93670. * A behavior that when attached to a mesh will allow the mesh to be scaled
  93671. */
  93672. var MultiPointerScaleBehavior = /** @class */ (function () {
  93673. function MultiPointerScaleBehavior() {
  93674. this._startDistance = 0;
  93675. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  93676. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  93677. this._sceneRenderObserver = null;
  93678. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  93679. this._dragBehaviorA.moveAttached = false;
  93680. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  93681. this._dragBehaviorB.moveAttached = false;
  93682. }
  93683. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  93684. /**
  93685. * The name of the behavior
  93686. */
  93687. get: function () {
  93688. return "MultiPointerScale";
  93689. },
  93690. enumerable: true,
  93691. configurable: true
  93692. });
  93693. /**
  93694. * Initializes the behavior
  93695. */
  93696. MultiPointerScaleBehavior.prototype.init = function () { };
  93697. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  93698. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  93699. };
  93700. /**
  93701. * Attaches the scale behavior the passed in mesh
  93702. * @param ownerNode The mesh that will be scaled around once attached
  93703. */
  93704. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  93705. var _this = this;
  93706. this._ownerNode = ownerNode;
  93707. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  93708. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  93709. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93710. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93711. _this._dragBehaviorA.releaseDrag();
  93712. }
  93713. else {
  93714. _this._initialScale.copyFrom(ownerNode.scaling);
  93715. _this._startDistance = _this._getCurrentDistance();
  93716. }
  93717. }
  93718. });
  93719. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  93720. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93721. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93722. _this._dragBehaviorB.releaseDrag();
  93723. }
  93724. else {
  93725. _this._initialScale.copyFrom(ownerNode.scaling);
  93726. _this._startDistance = _this._getCurrentDistance();
  93727. }
  93728. }
  93729. });
  93730. // Once both drag behaviors are active scale based on the distance between the two pointers
  93731. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93732. behavior.onDragObservable.add(function () {
  93733. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93734. var ratio = _this._getCurrentDistance() / _this._startDistance;
  93735. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  93736. }
  93737. });
  93738. });
  93739. ownerNode.addBehavior(this._dragBehaviorA);
  93740. ownerNode.addBehavior(this._dragBehaviorB);
  93741. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93742. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93743. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93744. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  93745. if (change.length() > 0.01) {
  93746. ownerNode.scaling.addInPlace(change);
  93747. }
  93748. }
  93749. });
  93750. };
  93751. /**
  93752. * Detaches the behavior from the mesh
  93753. */
  93754. MultiPointerScaleBehavior.prototype.detach = function () {
  93755. var _this = this;
  93756. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93757. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93758. behavior.onDragStartObservable.clear();
  93759. behavior.onDragObservable.clear();
  93760. _this._ownerNode.removeBehavior(behavior);
  93761. });
  93762. };
  93763. return MultiPointerScaleBehavior;
  93764. }());
  93765. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  93766. })(BABYLON || (BABYLON = {}));
  93767. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  93768. var BABYLON;
  93769. (function (BABYLON) {
  93770. /**
  93771. * 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
  93772. */
  93773. var SixDofDragBehavior = /** @class */ (function () {
  93774. function SixDofDragBehavior() {
  93775. this._sceneRenderObserver = null;
  93776. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93777. this._moving = false;
  93778. this._startingOrientation = new BABYLON.Quaternion();
  93779. /**
  93780. * 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)
  93781. */
  93782. this.zDragFactor = 3;
  93783. /**
  93784. * If the behavior is currently in a dragging state
  93785. */
  93786. this.dragging = false;
  93787. /**
  93788. * 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)
  93789. */
  93790. this.dragDeltaRatio = 0.2;
  93791. /**
  93792. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93793. */
  93794. this.currentDraggingPointerID = -1;
  93795. /**
  93796. * If camera controls should be detached during the drag
  93797. */
  93798. this.detachCameraControls = true;
  93799. }
  93800. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93801. /**
  93802. * The name of the behavior
  93803. */
  93804. get: function () {
  93805. return "SixDofDrag";
  93806. },
  93807. enumerable: true,
  93808. configurable: true
  93809. });
  93810. /**
  93811. * Initializes the behavior
  93812. */
  93813. SixDofDragBehavior.prototype.init = function () { };
  93814. /**
  93815. * Attaches the scale behavior the passed in mesh
  93816. * @param ownerNode The mesh that will be scaled around once attached
  93817. */
  93818. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93819. var _this = this;
  93820. this._ownerNode = ownerNode;
  93821. this._scene = this._ownerNode.getScene();
  93822. if (!SixDofDragBehavior._virtualScene) {
  93823. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93824. this._scene.getEngine().scenes.pop();
  93825. }
  93826. var pickedMesh = null;
  93827. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93828. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93829. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93830. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93831. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93832. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93833. var pickPredicate = function (m) {
  93834. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93835. };
  93836. var attachedElement = null;
  93837. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93838. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93839. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93840. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93841. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93842. }
  93843. pickedMesh = _this._ownerNode;
  93844. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93845. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93846. // Set position and orientation of the controller
  93847. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93848. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93849. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93850. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93851. pickedMesh.computeWorldMatrix();
  93852. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93853. if (!pickedMesh.rotationQuaternion) {
  93854. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93855. }
  93856. var oldParent = pickedMesh.parent;
  93857. pickedMesh.setParent(null);
  93858. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93859. pickedMesh.setParent(oldParent);
  93860. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93861. // Update state
  93862. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93863. _this.dragging = true;
  93864. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93865. // Detatch camera controls
  93866. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93867. if (_this._scene.activeCamera.inputs.attachedElement) {
  93868. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93869. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93870. }
  93871. else {
  93872. attachedElement = null;
  93873. }
  93874. }
  93875. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93876. }
  93877. }
  93878. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93879. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93880. _this.dragging = false;
  93881. _this._moving = false;
  93882. _this.currentDraggingPointerID = -1;
  93883. pickedMesh = null;
  93884. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93885. // Reattach camera controls
  93886. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93887. _this._scene.activeCamera.attachControl(attachedElement, true);
  93888. }
  93889. }
  93890. }
  93891. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93892. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93893. var zDragFactor = _this.zDragFactor;
  93894. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93895. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93896. zDragFactor = 0;
  93897. }
  93898. // Calculate controller drag distance in controller space
  93899. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93900. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93901. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93902. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93903. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93904. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93905. if (_this._virtualDragMesh.position.z < 0) {
  93906. _this._virtualDragMesh.position.z = 0;
  93907. }
  93908. // Update the controller position
  93909. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93910. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93911. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93912. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93913. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93914. if (pickedMesh.parent) {
  93915. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93916. }
  93917. if (!_this._moving) {
  93918. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93919. }
  93920. _this._moving = true;
  93921. }
  93922. }
  93923. });
  93924. var tmpQuaternion = new BABYLON.Quaternion();
  93925. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93926. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93927. if (_this.dragging && _this._moving && pickedMesh) {
  93928. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93929. // Slowly move mesh to avoid jitter
  93930. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93931. // Get change in rotation
  93932. tmpQuaternion.copyFrom(_this._startingOrientation);
  93933. tmpQuaternion.x = -tmpQuaternion.x;
  93934. tmpQuaternion.y = -tmpQuaternion.y;
  93935. tmpQuaternion.z = -tmpQuaternion.z;
  93936. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93937. // Convert change in rotation to only y axis rotation
  93938. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93939. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93940. // Slowly move mesh to avoid jitter
  93941. var oldParent = pickedMesh.parent;
  93942. pickedMesh.setParent(null);
  93943. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93944. pickedMesh.setParent(oldParent);
  93945. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93946. }
  93947. });
  93948. };
  93949. /**
  93950. * Detaches the behavior from the mesh
  93951. */
  93952. SixDofDragBehavior.prototype.detach = function () {
  93953. if (this._scene) {
  93954. this._scene.onPointerObservable.remove(this._pointerObserver);
  93955. }
  93956. if (this._ownerNode) {
  93957. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93958. }
  93959. if (this._virtualOriginMesh) {
  93960. this._virtualOriginMesh.dispose();
  93961. }
  93962. if (this._virtualDragMesh) {
  93963. this._virtualDragMesh.dispose();
  93964. }
  93965. };
  93966. return SixDofDragBehavior;
  93967. }());
  93968. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93969. })(BABYLON || (BABYLON = {}));
  93970. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93971. var BABYLON;
  93972. (function (BABYLON) {
  93973. /**
  93974. * @hidden
  93975. */
  93976. var FaceDirectionInfo = /** @class */ (function () {
  93977. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93978. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93979. if (diff === void 0) { diff = 0; }
  93980. if (ignore === void 0) { ignore = false; }
  93981. this.direction = direction;
  93982. this.rotatedDirection = rotatedDirection;
  93983. this.diff = diff;
  93984. this.ignore = ignore;
  93985. }
  93986. return FaceDirectionInfo;
  93987. }());
  93988. /**
  93989. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93990. */
  93991. var AttachToBoxBehavior = /** @class */ (function () {
  93992. /**
  93993. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93994. * @param ui The transform node that should be attched to the mesh
  93995. */
  93996. function AttachToBoxBehavior(ui) {
  93997. this.ui = ui;
  93998. /**
  93999. * The name of the behavior
  94000. */
  94001. this.name = "AttachToBoxBehavior";
  94002. /**
  94003. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  94004. */
  94005. this.distanceAwayFromFace = 0.15;
  94006. /**
  94007. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  94008. */
  94009. this.distanceAwayFromBottomOfFace = 0.15;
  94010. 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))];
  94011. this._tmpMatrix = new BABYLON.Matrix();
  94012. this._tmpVector = new BABYLON.Vector3();
  94013. this._zeroVector = BABYLON.Vector3.Zero();
  94014. this._lookAtTmpMatrix = new BABYLON.Matrix();
  94015. /* Does nothing */
  94016. }
  94017. /**
  94018. * Initializes the behavior
  94019. */
  94020. AttachToBoxBehavior.prototype.init = function () {
  94021. /* Does nothing */
  94022. };
  94023. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  94024. var _this = this;
  94025. // Go over each face and calculate the angle between the face's normal and targetDirection
  94026. this._faceVectors.forEach(function (v) {
  94027. if (!_this._target.rotationQuaternion) {
  94028. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  94029. }
  94030. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  94031. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  94032. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  94033. });
  94034. // Return the face information of the one with the normal closeset to target direction
  94035. return this._faceVectors.reduce(function (min, p) {
  94036. if (min.ignore) {
  94037. return p;
  94038. }
  94039. else if (p.ignore) {
  94040. return min;
  94041. }
  94042. else {
  94043. return min.diff < p.diff ? min : p;
  94044. }
  94045. }, this._faceVectors[0]);
  94046. };
  94047. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  94048. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  94049. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  94050. this._lookAtTmpMatrix.invert();
  94051. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  94052. };
  94053. /**
  94054. * Attaches the AttachToBoxBehavior to the passed in mesh
  94055. * @param target The mesh that the specified node will be attached to
  94056. */
  94057. AttachToBoxBehavior.prototype.attach = function (target) {
  94058. var _this = this;
  94059. this._target = target;
  94060. this._scene = this._target.getScene();
  94061. // Every frame, update the app bars position
  94062. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  94063. if (!_this._scene.activeCamera) {
  94064. return;
  94065. }
  94066. // Find the face closest to the cameras position
  94067. var cameraPos = _this._scene.activeCamera.position;
  94068. if (_this._scene.activeCamera.devicePosition) {
  94069. cameraPos = _this._scene.activeCamera.devicePosition;
  94070. }
  94071. var facing = _this._closestFace(cameraPos.subtract(target.position));
  94072. if (_this._scene.activeCamera.leftCamera) {
  94073. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  94074. }
  94075. else {
  94076. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  94077. }
  94078. // Get camera up direction
  94079. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  94080. // Ignore faces to not select a parrelel face for the up vector of the UI
  94081. _this._faceVectors.forEach(function (v) {
  94082. if (facing.direction.x && v.direction.x) {
  94083. v.ignore = true;
  94084. }
  94085. if (facing.direction.y && v.direction.y) {
  94086. v.ignore = true;
  94087. }
  94088. if (facing.direction.z && v.direction.z) {
  94089. v.ignore = true;
  94090. }
  94091. });
  94092. var facingUp = _this._closestFace(_this._tmpVector);
  94093. // Unignore faces
  94094. _this._faceVectors.forEach(function (v) {
  94095. v.ignore = false;
  94096. });
  94097. // Position the app bar on that face
  94098. _this.ui.position.copyFrom(target.position);
  94099. if (facing.direction.x) {
  94100. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94101. _this.ui.position.addInPlace(_this._tmpVector);
  94102. }
  94103. if (facing.direction.y) {
  94104. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94105. _this.ui.position.addInPlace(_this._tmpVector);
  94106. }
  94107. if (facing.direction.z) {
  94108. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  94109. _this.ui.position.addInPlace(_this._tmpVector);
  94110. }
  94111. // Rotate to be oriented properly to the camera
  94112. if (!_this.ui.rotationQuaternion) {
  94113. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  94114. }
  94115. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  94116. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  94117. // Place ui the correct distance from the bottom of the mesh
  94118. if (facingUp.direction.x) {
  94119. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  94120. }
  94121. if (facingUp.direction.y) {
  94122. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  94123. }
  94124. if (facingUp.direction.z) {
  94125. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  94126. }
  94127. _this.ui.position.addInPlace(_this._tmpVector);
  94128. });
  94129. };
  94130. /**
  94131. * Detaches the behavior from the mesh
  94132. */
  94133. AttachToBoxBehavior.prototype.detach = function () {
  94134. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  94135. };
  94136. return AttachToBoxBehavior;
  94137. }());
  94138. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  94139. })(BABYLON || (BABYLON = {}));
  94140. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  94141. var BABYLON;
  94142. (function (BABYLON) {
  94143. /**
  94144. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  94145. */
  94146. var FadeInOutBehavior = /** @class */ (function () {
  94147. /**
  94148. * Instatiates the FadeInOutBehavior
  94149. */
  94150. function FadeInOutBehavior() {
  94151. var _this = this;
  94152. /**
  94153. * Time in milliseconds to delay before fading in (Default: 0)
  94154. */
  94155. this.delay = 0;
  94156. /**
  94157. * Time in milliseconds for the mesh to fade in (Default: 300)
  94158. */
  94159. this.fadeInTime = 300;
  94160. this._millisecondsPerFrame = 1000 / 60;
  94161. this._hovered = false;
  94162. this._hoverValue = 0;
  94163. this._ownerNode = null;
  94164. this._update = function () {
  94165. if (_this._ownerNode) {
  94166. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  94167. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  94168. if (_this._ownerNode.visibility > 1) {
  94169. _this._setAllVisibility(_this._ownerNode, 1);
  94170. _this._hoverValue = _this.fadeInTime + _this.delay;
  94171. return;
  94172. }
  94173. else if (_this._ownerNode.visibility < 0) {
  94174. _this._setAllVisibility(_this._ownerNode, 0);
  94175. if (_this._hoverValue < 0) {
  94176. _this._hoverValue = 0;
  94177. return;
  94178. }
  94179. }
  94180. setTimeout(_this._update, _this._millisecondsPerFrame);
  94181. }
  94182. };
  94183. }
  94184. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  94185. /**
  94186. * The name of the behavior
  94187. */
  94188. get: function () {
  94189. return "FadeInOut";
  94190. },
  94191. enumerable: true,
  94192. configurable: true
  94193. });
  94194. /**
  94195. * Initializes the behavior
  94196. */
  94197. FadeInOutBehavior.prototype.init = function () {
  94198. };
  94199. /**
  94200. * Attaches the fade behavior on the passed in mesh
  94201. * @param ownerNode The mesh that will be faded in/out once attached
  94202. */
  94203. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  94204. this._ownerNode = ownerNode;
  94205. this._setAllVisibility(this._ownerNode, 0);
  94206. };
  94207. /**
  94208. * Detaches the behavior from the mesh
  94209. */
  94210. FadeInOutBehavior.prototype.detach = function () {
  94211. this._ownerNode = null;
  94212. };
  94213. /**
  94214. * Triggers the mesh to begin fading in or out
  94215. * @param value if the object should fade in or out (true to fade in)
  94216. */
  94217. FadeInOutBehavior.prototype.fadeIn = function (value) {
  94218. this._hovered = value;
  94219. this._update();
  94220. };
  94221. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  94222. var _this = this;
  94223. mesh.visibility = value;
  94224. mesh.getChildMeshes().forEach(function (c) {
  94225. _this._setAllVisibility(c, value);
  94226. });
  94227. };
  94228. return FadeInOutBehavior;
  94229. }());
  94230. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  94231. })(BABYLON || (BABYLON = {}));
  94232. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  94233. var BABYLON;
  94234. (function (BABYLON) {
  94235. /**
  94236. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  94237. */
  94238. var Gizmo = /** @class */ (function () {
  94239. /**
  94240. * Creates a gizmo
  94241. * @param gizmoLayer The utility layer the gizmo will be added to
  94242. */
  94243. function Gizmo(
  94244. /** The utility layer the gizmo will be added to */
  94245. gizmoLayer) {
  94246. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94247. var _this = this;
  94248. this.gizmoLayer = gizmoLayer;
  94249. /**
  94250. * Ratio for the scale of the gizmo (Default: 1)
  94251. */
  94252. this.scaleRatio = 1;
  94253. this._tmpMatrix = new BABYLON.Matrix();
  94254. /**
  94255. * If a custom mesh has been set (Default: false)
  94256. */
  94257. this._customMeshSet = false;
  94258. /**
  94259. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  94260. */
  94261. this.updateGizmoRotationToMatchAttachedMesh = true;
  94262. /**
  94263. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  94264. */
  94265. this.updateGizmoPositionToMatchAttachedMesh = true;
  94266. /**
  94267. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  94268. */
  94269. this._updateScale = true;
  94270. this._interactionsEnabled = true;
  94271. this._tempVector = new BABYLON.Vector3();
  94272. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  94273. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  94274. _this._update();
  94275. });
  94276. this.attachedMesh = null;
  94277. }
  94278. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  94279. /**
  94280. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  94281. * * When set, interactions will be enabled
  94282. */
  94283. get: function () {
  94284. return this._attachedMesh;
  94285. },
  94286. set: function (value) {
  94287. this._attachedMesh = value;
  94288. this._rootMesh.setEnabled(value ? true : false);
  94289. this._attachedMeshChanged(value);
  94290. },
  94291. enumerable: true,
  94292. configurable: true
  94293. });
  94294. /**
  94295. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94296. * @param mesh The mesh to replace the default mesh of the gizmo
  94297. */
  94298. Gizmo.prototype.setCustomMesh = function (mesh) {
  94299. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  94300. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  94301. }
  94302. this._rootMesh.getChildMeshes().forEach(function (c) {
  94303. c.dispose();
  94304. });
  94305. mesh.parent = this._rootMesh;
  94306. this._customMeshSet = true;
  94307. };
  94308. Gizmo.prototype._attachedMeshChanged = function (value) {
  94309. };
  94310. /**
  94311. * @hidden
  94312. * Updates the gizmo to match the attached mesh's position/rotation
  94313. */
  94314. Gizmo.prototype._update = function () {
  94315. if (this.attachedMesh) {
  94316. if (this.updateGizmoRotationToMatchAttachedMesh) {
  94317. if (!this._rootMesh.rotationQuaternion) {
  94318. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  94319. }
  94320. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  94321. this._tempVector.copyFrom(this.attachedMesh.scaling);
  94322. if (this.attachedMesh.scaling.x < 0) {
  94323. this.attachedMesh.scaling.x *= -1;
  94324. }
  94325. if (this.attachedMesh.scaling.y < 0) {
  94326. this.attachedMesh.scaling.y *= -1;
  94327. }
  94328. if (this.attachedMesh.scaling.z < 0) {
  94329. this.attachedMesh.scaling.z *= -1;
  94330. }
  94331. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  94332. this.attachedMesh.scaling.copyFrom(this._tempVector);
  94333. this.attachedMesh.computeWorldMatrix();
  94334. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  94335. }
  94336. else if (this._rootMesh.rotationQuaternion) {
  94337. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  94338. }
  94339. if (this.updateGizmoPositionToMatchAttachedMesh) {
  94340. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  94341. }
  94342. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  94343. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  94344. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  94345. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  94346. }
  94347. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  94348. var dist = this._tempVector.length() * this.scaleRatio;
  94349. this._rootMesh.scaling.set(dist, dist, dist);
  94350. }
  94351. }
  94352. };
  94353. /**
  94354. * Disposes of the gizmo
  94355. */
  94356. Gizmo.prototype.dispose = function () {
  94357. this._rootMesh.dispose();
  94358. if (this._beforeRenderObserver) {
  94359. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94360. }
  94361. };
  94362. return Gizmo;
  94363. }());
  94364. BABYLON.Gizmo = Gizmo;
  94365. })(BABYLON || (BABYLON = {}));
  94366. //# sourceMappingURL=babylon.gizmo.js.map
  94367. var BABYLON;
  94368. (function (BABYLON) {
  94369. /**
  94370. * Single axis drag gizmo
  94371. */
  94372. var AxisDragGizmo = /** @class */ (function (_super) {
  94373. __extends(AxisDragGizmo, _super);
  94374. /**
  94375. * Creates an AxisDragGizmo
  94376. * @param gizmoLayer The utility layer the gizmo will be added to
  94377. * @param dragAxis The axis which the gizmo will be able to drag on
  94378. * @param color The color of the gizmo
  94379. */
  94380. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  94381. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94382. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94383. var _this = _super.call(this, gizmoLayer) || this;
  94384. _this._pointerObserver = null;
  94385. /**
  94386. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94387. */
  94388. _this.snapDistance = 0;
  94389. /**
  94390. * Event that fires each time the gizmo snaps to a new location.
  94391. * * snapDistance is the the change in distance
  94392. */
  94393. _this.onSnapObservable = new BABYLON.Observable();
  94394. // Create Material
  94395. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94396. coloredMaterial.disableLighting = true;
  94397. coloredMaterial.emissiveColor = color;
  94398. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94399. hoverMaterial.disableLighting = true;
  94400. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94401. // Build mesh on root node
  94402. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94403. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  94404. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94405. arrowTail.color = coloredMaterial.emissiveColor;
  94406. arrow.addChild(arrowMesh);
  94407. arrow.addChild(arrowTail);
  94408. // Position arrow pointing in its drag axis
  94409. arrowMesh.scaling.scaleInPlace(0.05);
  94410. arrowMesh.material = coloredMaterial;
  94411. arrowMesh.rotation.x = Math.PI / 2;
  94412. arrowMesh.position.z += 0.3;
  94413. arrowTail.scaling.scaleInPlace(0.26);
  94414. arrowTail.rotation.x = Math.PI / 2;
  94415. arrowTail.material = coloredMaterial;
  94416. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94417. arrow.scaling.scaleInPlace(1 / 3);
  94418. _this._rootMesh.addChild(arrow);
  94419. var currentSnapDragDistance = 0;
  94420. var tmpVector = new BABYLON.Vector3();
  94421. var tmpSnapEvent = { snapDistance: 0 };
  94422. // Add drag behavior to handle events when the gizmo is dragged
  94423. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94424. _this.dragBehavior.moveAttached = false;
  94425. _this._rootMesh.addBehavior(_this.dragBehavior);
  94426. var localDelta = new BABYLON.Vector3();
  94427. var tmpMatrix = new BABYLON.Matrix();
  94428. _this.dragBehavior.onDragObservable.add(function (event) {
  94429. if (_this.attachedMesh) {
  94430. // Convert delta to local translation if it has a parent
  94431. if (_this.attachedMesh.parent) {
  94432. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94433. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  94434. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  94435. }
  94436. else {
  94437. localDelta.copyFrom(event.delta);
  94438. }
  94439. // Snapping logic
  94440. if (_this.snapDistance == 0) {
  94441. _this.attachedMesh.position.addInPlace(localDelta);
  94442. }
  94443. else {
  94444. currentSnapDragDistance += event.dragDistance;
  94445. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94446. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  94447. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94448. localDelta.normalizeToRef(tmpVector);
  94449. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  94450. _this.attachedMesh.position.addInPlace(tmpVector);
  94451. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94452. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94453. }
  94454. }
  94455. }
  94456. });
  94457. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94458. if (_this._customMeshSet) {
  94459. return;
  94460. }
  94461. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94462. var material = isHovered ? hoverMaterial : coloredMaterial;
  94463. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94464. m.material = material;
  94465. if (m.color) {
  94466. m.color = material.emissiveColor;
  94467. }
  94468. });
  94469. });
  94470. return _this;
  94471. }
  94472. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  94473. if (this.dragBehavior) {
  94474. this.dragBehavior.enabled = value ? true : false;
  94475. }
  94476. };
  94477. /**
  94478. * Disposes of the gizmo
  94479. */
  94480. AxisDragGizmo.prototype.dispose = function () {
  94481. this.onSnapObservable.clear();
  94482. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94483. this.dragBehavior.detach();
  94484. _super.prototype.dispose.call(this);
  94485. };
  94486. return AxisDragGizmo;
  94487. }(BABYLON.Gizmo));
  94488. BABYLON.AxisDragGizmo = AxisDragGizmo;
  94489. })(BABYLON || (BABYLON = {}));
  94490. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  94491. var BABYLON;
  94492. (function (BABYLON) {
  94493. /**
  94494. * Single axis scale gizmo
  94495. */
  94496. var AxisScaleGizmo = /** @class */ (function (_super) {
  94497. __extends(AxisScaleGizmo, _super);
  94498. /**
  94499. * Creates an AxisScaleGizmo
  94500. * @param gizmoLayer The utility layer the gizmo will be added to
  94501. * @param dragAxis The axis which the gizmo will be able to scale on
  94502. * @param color The color of the gizmo
  94503. */
  94504. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  94505. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94506. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94507. var _this = _super.call(this, gizmoLayer) || this;
  94508. _this._pointerObserver = null;
  94509. /**
  94510. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94511. */
  94512. _this.snapDistance = 0;
  94513. /**
  94514. * Event that fires each time the gizmo snaps to a new location.
  94515. * * snapDistance is the the change in distance
  94516. */
  94517. _this.onSnapObservable = new BABYLON.Observable();
  94518. /**
  94519. * If the scaling operation should be done on all axis (default: false)
  94520. */
  94521. _this.uniformScaling = false;
  94522. // Create Material
  94523. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94524. _this._coloredMaterial.disableLighting = true;
  94525. _this._coloredMaterial.emissiveColor = color;
  94526. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94527. hoverMaterial.disableLighting = true;
  94528. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94529. // Build mesh on root node
  94530. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94531. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  94532. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94533. arrowTail.color = _this._coloredMaterial.emissiveColor;
  94534. arrow.addChild(arrowMesh);
  94535. arrow.addChild(arrowTail);
  94536. // Position arrow pointing in its drag axis
  94537. arrowMesh.scaling.scaleInPlace(0.1);
  94538. arrowMesh.material = _this._coloredMaterial;
  94539. arrowMesh.rotation.x = Math.PI / 2;
  94540. arrowMesh.position.z += 0.3;
  94541. arrowTail.scaling.scaleInPlace(0.26);
  94542. arrowTail.rotation.x = Math.PI / 2;
  94543. arrowTail.material = _this._coloredMaterial;
  94544. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94545. _this._rootMesh.addChild(arrow);
  94546. arrow.scaling.scaleInPlace(1 / 3);
  94547. // Add drag behavior to handle events when the gizmo is dragged
  94548. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94549. _this.dragBehavior.moveAttached = false;
  94550. _this._rootMesh.addBehavior(_this.dragBehavior);
  94551. var currentSnapDragDistance = 0;
  94552. var tmpVector = new BABYLON.Vector3();
  94553. var tmpSnapEvent = { snapDistance: 0 };
  94554. _this.dragBehavior.onDragObservable.add(function (event) {
  94555. if (_this.attachedMesh) {
  94556. // Snapping logic
  94557. var snapped = false;
  94558. var dragSteps = 0;
  94559. if (_this.uniformScaling) {
  94560. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  94561. if (tmpVector.y < 0) {
  94562. tmpVector.scaleInPlace(-1);
  94563. }
  94564. }
  94565. else {
  94566. tmpVector.copyFrom(dragAxis);
  94567. }
  94568. if (_this.snapDistance == 0) {
  94569. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  94570. }
  94571. else {
  94572. currentSnapDragDistance += event.dragDistance;
  94573. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94574. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94575. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94576. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  94577. snapped = true;
  94578. }
  94579. else {
  94580. tmpVector.scaleInPlace(0);
  94581. }
  94582. }
  94583. _this.attachedMesh.scaling.addInPlace(tmpVector);
  94584. if (snapped) {
  94585. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94586. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94587. }
  94588. }
  94589. });
  94590. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94591. if (_this._customMeshSet) {
  94592. return;
  94593. }
  94594. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94595. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  94596. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94597. m.material = material;
  94598. if (m.color) {
  94599. m.color = material.emissiveColor;
  94600. }
  94601. });
  94602. });
  94603. return _this;
  94604. }
  94605. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  94606. if (this.dragBehavior) {
  94607. this.dragBehavior.enabled = value ? true : false;
  94608. }
  94609. };
  94610. /**
  94611. * Disposes of the gizmo
  94612. */
  94613. AxisScaleGizmo.prototype.dispose = function () {
  94614. this.onSnapObservable.clear();
  94615. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94616. this.dragBehavior.detach();
  94617. _super.prototype.dispose.call(this);
  94618. };
  94619. /**
  94620. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94621. * @param mesh The mesh to replace the default mesh of the gizmo
  94622. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  94623. */
  94624. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  94625. var _this = this;
  94626. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  94627. _super.prototype.setCustomMesh.call(this, mesh);
  94628. if (useGizmoMaterial) {
  94629. this._rootMesh.getChildMeshes().forEach(function (m) {
  94630. m.material = _this._coloredMaterial;
  94631. if (m.color) {
  94632. m.color = _this._coloredMaterial.emissiveColor;
  94633. }
  94634. });
  94635. this._customMeshSet = false;
  94636. }
  94637. };
  94638. return AxisScaleGizmo;
  94639. }(BABYLON.Gizmo));
  94640. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  94641. })(BABYLON || (BABYLON = {}));
  94642. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  94643. var BABYLON;
  94644. (function (BABYLON) {
  94645. /**
  94646. * Single plane rotation gizmo
  94647. */
  94648. var PlaneRotationGizmo = /** @class */ (function (_super) {
  94649. __extends(PlaneRotationGizmo, _super);
  94650. /**
  94651. * Creates a PlaneRotationGizmo
  94652. * @param gizmoLayer The utility layer the gizmo will be added to
  94653. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  94654. * @param color The color of the gizmo
  94655. */
  94656. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  94657. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94658. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94659. var _this = _super.call(this, gizmoLayer) || this;
  94660. _this._pointerObserver = null;
  94661. /**
  94662. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  94663. */
  94664. _this.snapDistance = 0;
  94665. /**
  94666. * Event that fires each time the gizmo snaps to a new location.
  94667. * * snapDistance is the the change in distance
  94668. */
  94669. _this.onSnapObservable = new BABYLON.Observable();
  94670. // Create Material
  94671. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94672. coloredMaterial.disableLighting = true;
  94673. coloredMaterial.emissiveColor = color;
  94674. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94675. hoverMaterial.disableLighting = true;
  94676. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94677. // Build mesh on root node
  94678. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94679. // Create circle out of lines
  94680. var tessellation = 20;
  94681. var radius = 0.8;
  94682. var points = new Array();
  94683. for (var i = 0; i < tessellation; i++) {
  94684. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  94685. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  94686. }
  94687. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  94688. rotationMesh.color = coloredMaterial.emissiveColor;
  94689. // Position arrow pointing in its drag axis
  94690. rotationMesh.scaling.scaleInPlace(0.26);
  94691. rotationMesh.material = coloredMaterial;
  94692. rotationMesh.rotation.x = Math.PI / 2;
  94693. parentMesh.addChild(rotationMesh);
  94694. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  94695. _this._rootMesh.addChild(parentMesh);
  94696. parentMesh.scaling.scaleInPlace(1 / 3);
  94697. // Add drag behavior to handle events when the gizmo is dragged
  94698. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  94699. _this.dragBehavior.moveAttached = false;
  94700. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  94701. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  94702. _this._rootMesh.addBehavior(_this.dragBehavior);
  94703. var lastDragPosition = new BABYLON.Vector3();
  94704. _this.dragBehavior.onDragStartObservable.add(function (e) {
  94705. if (_this.attachedMesh) {
  94706. lastDragPosition.copyFrom(e.dragPlanePoint);
  94707. }
  94708. });
  94709. var rotationMatrix = new BABYLON.Matrix();
  94710. var planeNormalTowardsCamera = new BABYLON.Vector3();
  94711. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  94712. var tmpSnapEvent = { snapDistance: 0 };
  94713. var currentSnapDragDistance = 0;
  94714. var tmpMatrix = new BABYLON.Matrix();
  94715. var tmpVector = new BABYLON.Vector3();
  94716. var amountToRotate = new BABYLON.Quaternion();
  94717. _this.dragBehavior.onDragObservable.add(function (event) {
  94718. if (_this.attachedMesh) {
  94719. if (!_this.attachedMesh.rotationQuaternion) {
  94720. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94721. }
  94722. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  94723. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  94724. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  94725. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  94726. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  94727. var angle = Math.atan2(cross.length(), dot);
  94728. planeNormalTowardsCamera.copyFrom(planeNormal);
  94729. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  94730. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94731. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  94732. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  94733. }
  94734. // Flip up vector depending on which side the camera is on
  94735. if (gizmoLayer.utilityLayerScene.activeCamera) {
  94736. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  94737. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  94738. planeNormalTowardsCamera.scaleInPlace(-1);
  94739. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  94740. }
  94741. }
  94742. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  94743. if (halfCircleSide)
  94744. angle = -angle;
  94745. // Snapping logic
  94746. var snapped = false;
  94747. if (_this.snapDistance != 0) {
  94748. currentSnapDragDistance += angle;
  94749. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94750. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94751. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94752. angle = _this.snapDistance * dragSteps;
  94753. snapped = true;
  94754. }
  94755. else {
  94756. angle = 0;
  94757. }
  94758. }
  94759. // If the mesh has a parent, convert needed world rotation to local rotation
  94760. tmpMatrix.reset();
  94761. if (_this.attachedMesh.parent) {
  94762. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94763. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  94764. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  94765. }
  94766. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  94767. var quaternionCoefficient = Math.sin(angle / 2);
  94768. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  94769. // 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
  94770. if (tmpMatrix.determinant() > 0) {
  94771. amountToRotate.toEulerAnglesToRef(tmpVector);
  94772. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  94773. }
  94774. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94775. // Rotate selected mesh quaternion over fixed axis
  94776. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  94777. }
  94778. else {
  94779. // Rotate selected mesh quaternion over rotated axis
  94780. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  94781. }
  94782. lastDragPosition.copyFrom(event.dragPlanePoint);
  94783. if (snapped) {
  94784. tmpSnapEvent.snapDistance = angle;
  94785. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94786. }
  94787. }
  94788. });
  94789. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94790. if (_this._customMeshSet) {
  94791. return;
  94792. }
  94793. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94794. var material = isHovered ? hoverMaterial : coloredMaterial;
  94795. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94796. m.material = material;
  94797. if (m.color) {
  94798. m.color = material.emissiveColor;
  94799. }
  94800. });
  94801. });
  94802. return _this;
  94803. }
  94804. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94805. if (this.dragBehavior) {
  94806. this.dragBehavior.enabled = value ? true : false;
  94807. }
  94808. };
  94809. /**
  94810. * Disposes of the gizmo
  94811. */
  94812. PlaneRotationGizmo.prototype.dispose = function () {
  94813. this.onSnapObservable.clear();
  94814. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94815. this.dragBehavior.detach();
  94816. _super.prototype.dispose.call(this);
  94817. };
  94818. return PlaneRotationGizmo;
  94819. }(BABYLON.Gizmo));
  94820. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94821. })(BABYLON || (BABYLON = {}));
  94822. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94823. var BABYLON;
  94824. (function (BABYLON) {
  94825. /**
  94826. * Gizmo that enables dragging a mesh along 3 axis
  94827. */
  94828. var PositionGizmo = /** @class */ (function (_super) {
  94829. __extends(PositionGizmo, _super);
  94830. /**
  94831. * Creates a PositionGizmo
  94832. * @param gizmoLayer The utility layer the gizmo will be added to
  94833. */
  94834. function PositionGizmo(gizmoLayer) {
  94835. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94836. var _this = _super.call(this, gizmoLayer) || this;
  94837. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94838. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94839. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94840. _this.attachedMesh = null;
  94841. return _this;
  94842. }
  94843. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94844. set: function (mesh) {
  94845. if (this.xGizmo) {
  94846. this.xGizmo.attachedMesh = mesh;
  94847. this.yGizmo.attachedMesh = mesh;
  94848. this.zGizmo.attachedMesh = mesh;
  94849. }
  94850. },
  94851. enumerable: true,
  94852. configurable: true
  94853. });
  94854. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94855. get: function () {
  94856. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94857. },
  94858. set: function (value) {
  94859. if (this.xGizmo) {
  94860. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94861. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94862. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94863. }
  94864. },
  94865. enumerable: true,
  94866. configurable: true
  94867. });
  94868. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94869. get: function () {
  94870. return this.xGizmo.snapDistance;
  94871. },
  94872. /**
  94873. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94874. */
  94875. set: function (value) {
  94876. if (this.xGizmo) {
  94877. this.xGizmo.snapDistance = value;
  94878. this.yGizmo.snapDistance = value;
  94879. this.zGizmo.snapDistance = value;
  94880. }
  94881. },
  94882. enumerable: true,
  94883. configurable: true
  94884. });
  94885. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94886. get: function () {
  94887. return this.xGizmo.scaleRatio;
  94888. },
  94889. /**
  94890. * Ratio for the scale of the gizmo (Default: 1)
  94891. */
  94892. set: function (value) {
  94893. if (this.xGizmo) {
  94894. this.xGizmo.scaleRatio = value;
  94895. this.yGizmo.scaleRatio = value;
  94896. this.zGizmo.scaleRatio = value;
  94897. }
  94898. },
  94899. enumerable: true,
  94900. configurable: true
  94901. });
  94902. /**
  94903. * Disposes of the gizmo
  94904. */
  94905. PositionGizmo.prototype.dispose = function () {
  94906. this.xGizmo.dispose();
  94907. this.yGizmo.dispose();
  94908. this.zGizmo.dispose();
  94909. };
  94910. /**
  94911. * CustomMeshes are not supported by this gizmo
  94912. * @param mesh The mesh to replace the default mesh of the gizmo
  94913. */
  94914. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94915. 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)");
  94916. };
  94917. return PositionGizmo;
  94918. }(BABYLON.Gizmo));
  94919. BABYLON.PositionGizmo = PositionGizmo;
  94920. })(BABYLON || (BABYLON = {}));
  94921. //# sourceMappingURL=babylon.positionGizmo.js.map
  94922. var BABYLON;
  94923. (function (BABYLON) {
  94924. /**
  94925. * Gizmo that enables rotating a mesh along 3 axis
  94926. */
  94927. var RotationGizmo = /** @class */ (function (_super) {
  94928. __extends(RotationGizmo, _super);
  94929. /**
  94930. * Creates a RotationGizmo
  94931. * @param gizmoLayer The utility layer the gizmo will be added to
  94932. */
  94933. function RotationGizmo(gizmoLayer) {
  94934. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94935. var _this = _super.call(this, gizmoLayer) || this;
  94936. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94937. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94938. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94939. _this.attachedMesh = null;
  94940. return _this;
  94941. }
  94942. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94943. set: function (mesh) {
  94944. if (this.xGizmo) {
  94945. this.xGizmo.attachedMesh = mesh;
  94946. this.yGizmo.attachedMesh = mesh;
  94947. this.zGizmo.attachedMesh = mesh;
  94948. }
  94949. },
  94950. enumerable: true,
  94951. configurable: true
  94952. });
  94953. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94954. get: function () {
  94955. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94956. },
  94957. set: function (value) {
  94958. if (this.xGizmo) {
  94959. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94960. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94961. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94962. }
  94963. },
  94964. enumerable: true,
  94965. configurable: true
  94966. });
  94967. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94968. get: function () {
  94969. return this.xGizmo.snapDistance;
  94970. },
  94971. /**
  94972. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94973. */
  94974. set: function (value) {
  94975. if (this.xGizmo) {
  94976. this.xGizmo.snapDistance = value;
  94977. this.yGizmo.snapDistance = value;
  94978. this.zGizmo.snapDistance = value;
  94979. }
  94980. },
  94981. enumerable: true,
  94982. configurable: true
  94983. });
  94984. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94985. get: function () {
  94986. return this.xGizmo.scaleRatio;
  94987. },
  94988. /**
  94989. * Ratio for the scale of the gizmo (Default: 1)
  94990. */
  94991. set: function (value) {
  94992. if (this.xGizmo) {
  94993. this.xGizmo.scaleRatio = value;
  94994. this.yGizmo.scaleRatio = value;
  94995. this.zGizmo.scaleRatio = value;
  94996. }
  94997. },
  94998. enumerable: true,
  94999. configurable: true
  95000. });
  95001. /**
  95002. * Disposes of the gizmo
  95003. */
  95004. RotationGizmo.prototype.dispose = function () {
  95005. this.xGizmo.dispose();
  95006. this.yGizmo.dispose();
  95007. this.zGizmo.dispose();
  95008. };
  95009. /**
  95010. * CustomMeshes are not supported by this gizmo
  95011. * @param mesh The mesh to replace the default mesh of the gizmo
  95012. */
  95013. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  95014. 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)");
  95015. };
  95016. return RotationGizmo;
  95017. }(BABYLON.Gizmo));
  95018. BABYLON.RotationGizmo = RotationGizmo;
  95019. })(BABYLON || (BABYLON = {}));
  95020. //# sourceMappingURL=babylon.rotationGizmo.js.map
  95021. var BABYLON;
  95022. (function (BABYLON) {
  95023. /**
  95024. * Gizmo that enables scaling a mesh along 3 axis
  95025. */
  95026. var ScaleGizmo = /** @class */ (function (_super) {
  95027. __extends(ScaleGizmo, _super);
  95028. /**
  95029. * Creates a ScaleGizmo
  95030. * @param gizmoLayer The utility layer the gizmo will be added to
  95031. */
  95032. function ScaleGizmo(gizmoLayer) {
  95033. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95034. var _this = _super.call(this, gizmoLayer) || this;
  95035. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  95036. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  95037. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  95038. // Create uniform scale gizmo
  95039. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  95040. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95041. _this._uniformGizmo.uniformScaling = true;
  95042. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  95043. octahedron.scaling.scaleInPlace(0.007);
  95044. _this._uniformGizmo.setCustomMesh(octahedron, true);
  95045. _this.attachedMesh = null;
  95046. return _this;
  95047. }
  95048. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  95049. set: function (mesh) {
  95050. if (this.xGizmo) {
  95051. this.xGizmo.attachedMesh = mesh;
  95052. this.yGizmo.attachedMesh = mesh;
  95053. this.zGizmo.attachedMesh = mesh;
  95054. this._uniformGizmo.attachedMesh = mesh;
  95055. }
  95056. },
  95057. enumerable: true,
  95058. configurable: true
  95059. });
  95060. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  95061. get: function () {
  95062. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  95063. },
  95064. set: function (value) {
  95065. if (this.xGizmo) {
  95066. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95067. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95068. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  95069. }
  95070. },
  95071. enumerable: true,
  95072. configurable: true
  95073. });
  95074. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  95075. get: function () {
  95076. return this.xGizmo.snapDistance;
  95077. },
  95078. /**
  95079. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95080. */
  95081. set: function (value) {
  95082. if (this.xGizmo) {
  95083. this.xGizmo.snapDistance = value;
  95084. this.yGizmo.snapDistance = value;
  95085. this.zGizmo.snapDistance = value;
  95086. this._uniformGizmo.snapDistance = value;
  95087. }
  95088. },
  95089. enumerable: true,
  95090. configurable: true
  95091. });
  95092. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  95093. get: function () {
  95094. return this.xGizmo.scaleRatio;
  95095. },
  95096. /**
  95097. * Ratio for the scale of the gizmo (Default: 1)
  95098. */
  95099. set: function (value) {
  95100. if (this.xGizmo) {
  95101. this.xGizmo.scaleRatio = value;
  95102. this.yGizmo.scaleRatio = value;
  95103. this.zGizmo.scaleRatio = value;
  95104. this._uniformGizmo.scaleRatio = value;
  95105. }
  95106. },
  95107. enumerable: true,
  95108. configurable: true
  95109. });
  95110. /**
  95111. * Disposes of the gizmo
  95112. */
  95113. ScaleGizmo.prototype.dispose = function () {
  95114. this.xGizmo.dispose();
  95115. this.yGizmo.dispose();
  95116. this.zGizmo.dispose();
  95117. this._uniformGizmo.dispose();
  95118. };
  95119. return ScaleGizmo;
  95120. }(BABYLON.Gizmo));
  95121. BABYLON.ScaleGizmo = ScaleGizmo;
  95122. })(BABYLON || (BABYLON = {}));
  95123. //# sourceMappingURL=babylon.scaleGizmo.js.map
  95124. var BABYLON;
  95125. (function (BABYLON) {
  95126. /**
  95127. * Bounding box gizmo
  95128. */
  95129. var BoundingBoxGizmo = /** @class */ (function (_super) {
  95130. __extends(BoundingBoxGizmo, _super);
  95131. /**
  95132. * Creates an BoundingBoxGizmo
  95133. * @param gizmoLayer The utility layer the gizmo will be added to
  95134. * @param color The color of the gizmo
  95135. */
  95136. function BoundingBoxGizmo(color, gizmoLayer) {
  95137. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95138. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  95139. var _this = _super.call(this, gizmoLayer) || this;
  95140. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  95141. _this._renderObserver = null;
  95142. _this._pointerObserver = null;
  95143. _this._scaleDragSpeed = 0.2;
  95144. _this._tmpQuaternion = new BABYLON.Quaternion();
  95145. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95146. _this._tmpRotationMatrix = new BABYLON.Matrix();
  95147. /**
  95148. * 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)
  95149. */
  95150. _this.ignoreChildren = false;
  95151. /**
  95152. * 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)
  95153. */
  95154. _this.includeChildPredicate = null;
  95155. /**
  95156. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  95157. */
  95158. _this.rotationSphereSize = 0.1;
  95159. /**
  95160. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  95161. */
  95162. _this.scaleBoxSize = 0.1;
  95163. /**
  95164. * 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)
  95165. */
  95166. _this.fixedDragMeshScreenSize = false;
  95167. /**
  95168. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  95169. */
  95170. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  95171. /**
  95172. * Fired when a rotation sphere or scale box is dragged
  95173. */
  95174. _this.onDragStartObservable = new BABYLON.Observable();
  95175. /**
  95176. * Fired when a scale box is dragged
  95177. */
  95178. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  95179. /**
  95180. * Fired when a scale box drag is ended
  95181. */
  95182. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  95183. /**
  95184. * Fired when a rotation sphere is dragged
  95185. */
  95186. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  95187. /**
  95188. * Fired when a rotation sphere drag is ended
  95189. */
  95190. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  95191. /**
  95192. * 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)
  95193. */
  95194. _this.scalePivot = null;
  95195. _this._existingMeshScale = new BABYLON.Vector3();
  95196. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  95197. _this._updateScale = false;
  95198. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  95199. // Create Materials
  95200. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95201. coloredMaterial.disableLighting = true;
  95202. coloredMaterial.emissiveColor = color;
  95203. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95204. hoverColoredMaterial.disableLighting = true;
  95205. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95206. // Build bounding box out of lines
  95207. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95208. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  95209. var lines = [];
  95210. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  95211. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  95212. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  95213. 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));
  95214. 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));
  95215. 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));
  95216. 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));
  95217. 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));
  95218. 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));
  95219. 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));
  95220. 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));
  95221. 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));
  95222. lines.forEach(function (l) {
  95223. l.color = color;
  95224. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  95225. l.isPickable = false;
  95226. _this._lineBoundingBox.addChild(l);
  95227. });
  95228. _this._rootMesh.addChild(_this._lineBoundingBox);
  95229. // Create rotation spheres
  95230. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95231. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  95232. var _loop_1 = function (i_1) {
  95233. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  95234. sphere.rotationQuaternion = new BABYLON.Quaternion();
  95235. sphere.material = coloredMaterial;
  95236. // Drag behavior
  95237. _dragBehavior = new BABYLON.PointerDragBehavior({});
  95238. _dragBehavior.moveAttached = false;
  95239. _dragBehavior.updateDragPlane = false;
  95240. sphere.addBehavior(_dragBehavior);
  95241. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  95242. var totalTurnAmountOfDrag = 0;
  95243. _dragBehavior.onDragStartObservable.add(function (event) {
  95244. startingTurnDirection.copyFrom(sphere.forward);
  95245. totalTurnAmountOfDrag = 0;
  95246. });
  95247. _dragBehavior.onDragObservable.add(function (event) {
  95248. _this.onRotationSphereDragObservable.notifyObservers({});
  95249. if (_this.attachedMesh) {
  95250. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95251. var worldDragDirection = startingTurnDirection;
  95252. // Project the world right on to the drag plane
  95253. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  95254. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  95255. // project drag delta on to the resulting drag axis and rotate based on that
  95256. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  95257. // Make rotation relative to size of mesh.
  95258. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95259. // Rotate based on axis
  95260. if (!_this.attachedMesh.rotationQuaternion) {
  95261. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  95262. }
  95263. if (!_this._anchorMesh.rotationQuaternion) {
  95264. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  95265. }
  95266. // Do not allow the object to turn more than a full circle
  95267. totalTurnAmountOfDrag += projectDist;
  95268. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  95269. if (i_1 >= 8) {
  95270. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  95271. }
  95272. else if (i_1 >= 4) {
  95273. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  95274. }
  95275. else {
  95276. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  95277. }
  95278. // Rotate around center of bounding box
  95279. _this._anchorMesh.addChild(_this.attachedMesh);
  95280. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  95281. _this._anchorMesh.removeChild(_this.attachedMesh);
  95282. }
  95283. _this.updateBoundingBox();
  95284. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95285. }
  95286. });
  95287. // Selection/deselection
  95288. _dragBehavior.onDragStartObservable.add(function () {
  95289. _this.onDragStartObservable.notifyObservers({});
  95290. _this._selectNode(sphere);
  95291. });
  95292. _dragBehavior.onDragEndObservable.add(function () {
  95293. _this.onRotationSphereDragEndObservable.notifyObservers({});
  95294. _this._selectNode(null);
  95295. });
  95296. this_1._rotateSpheresParent.addChild(sphere);
  95297. };
  95298. var this_1 = this, _dragBehavior;
  95299. for (var i_1 = 0; i_1 < 12; i_1++) {
  95300. _loop_1(i_1);
  95301. }
  95302. _this._rootMesh.addChild(_this._rotateSpheresParent);
  95303. // Create scale cubes
  95304. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95305. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  95306. for (var i = 0; i < 2; i++) {
  95307. for (var j = 0; j < 2; j++) {
  95308. var _loop_2 = function () {
  95309. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  95310. box.material = coloredMaterial;
  95311. // Dragging logic
  95312. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  95313. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95314. _dragBehavior.moveAttached = false;
  95315. box.addBehavior(_dragBehavior);
  95316. _dragBehavior.onDragObservable.add(function (event) {
  95317. _this.onScaleBoxDragObservable.notifyObservers({});
  95318. if (_this.attachedMesh) {
  95319. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95320. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95321. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  95322. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  95323. _this.updateBoundingBox();
  95324. if (_this.scalePivot) {
  95325. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  95326. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  95327. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  95328. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95329. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95330. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  95331. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95332. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  95333. }
  95334. else {
  95335. // Scale from the position of the opposite corner
  95336. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  95337. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95338. }
  95339. _this._anchorMesh.addChild(_this.attachedMesh);
  95340. _this._anchorMesh.scaling.addInPlace(deltaScale);
  95341. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  95342. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  95343. }
  95344. _this._anchorMesh.removeChild(_this.attachedMesh);
  95345. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95346. }
  95347. });
  95348. // Selection/deselection
  95349. _dragBehavior.onDragStartObservable.add(function () {
  95350. _this.onDragStartObservable.notifyObservers({});
  95351. _this._selectNode(box);
  95352. });
  95353. _dragBehavior.onDragEndObservable.add(function () {
  95354. _this.onScaleBoxDragEndObservable.notifyObservers({});
  95355. _this._selectNode(null);
  95356. });
  95357. this_2._scaleBoxesParent.addChild(box);
  95358. };
  95359. var this_2 = this, _dragBehavior;
  95360. for (var k = 0; k < 2; k++) {
  95361. _loop_2();
  95362. }
  95363. }
  95364. }
  95365. _this._rootMesh.addChild(_this._scaleBoxesParent);
  95366. // Hover color change
  95367. var pointerIds = new Array();
  95368. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95369. if (!pointerIds[pointerInfo.event.pointerId]) {
  95370. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  95371. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  95372. pointerIds[pointerInfo.event.pointerId] = mesh;
  95373. mesh.material = hoverColoredMaterial;
  95374. }
  95375. });
  95376. }
  95377. else {
  95378. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  95379. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  95380. delete pointerIds[pointerInfo.event.pointerId];
  95381. }
  95382. }
  95383. });
  95384. // Update bounding box positions
  95385. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  95386. // Only update the bouding box if scaling has changed
  95387. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  95388. _this.updateBoundingBox();
  95389. }
  95390. });
  95391. _this.updateBoundingBox();
  95392. return _this;
  95393. }
  95394. /** @hidden */
  95395. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  95396. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  95397. // Save old pivot and set pivot to 0,0,0
  95398. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  95399. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  95400. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  95401. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  95402. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95403. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95404. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95405. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  95406. }
  95407. }
  95408. BoundingBoxGizmo._PivotCached++;
  95409. };
  95410. /** @hidden */
  95411. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  95412. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  95413. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  95414. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95415. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95416. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95417. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  95418. }
  95419. this._PivotCached--;
  95420. };
  95421. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  95422. if (value) {
  95423. // Reset anchor mesh to match attached mesh's scale
  95424. // This is needed to avoid invalid box/sphere position on first drag
  95425. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  95426. this._anchorMesh.addChild(value);
  95427. this._anchorMesh.removeChild(value);
  95428. BoundingBoxGizmo._RestorePivotPoint(value);
  95429. this.updateBoundingBox();
  95430. }
  95431. };
  95432. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  95433. this._rotateSpheresParent.getChildMeshes()
  95434. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  95435. m.isVisible = (!selectedMesh || m == selectedMesh);
  95436. });
  95437. };
  95438. /**
  95439. * Updates the bounding box information for the Gizmo
  95440. */
  95441. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  95442. if (this.attachedMesh) {
  95443. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  95444. this._update();
  95445. // Rotate based on axis
  95446. if (!this.attachedMesh.rotationQuaternion) {
  95447. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  95448. }
  95449. if (!this._anchorMesh.rotationQuaternion) {
  95450. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  95451. }
  95452. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95453. // Store original position and reset mesh to origin before computing the bounding box
  95454. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95455. this._tmpVector.copyFrom(this.attachedMesh.position);
  95456. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  95457. this.attachedMesh.position.set(0, 0, 0);
  95458. // Update bounding dimensions/positions
  95459. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  95460. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  95461. // Update gizmo to match bounding box scaling and rotation
  95462. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  95463. 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);
  95464. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  95465. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  95466. this._lineBoundingBox.computeWorldMatrix();
  95467. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  95468. // restore position/rotation values
  95469. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  95470. this.attachedMesh.position.copyFrom(this._tmpVector);
  95471. }
  95472. // Update rotation sphere locations
  95473. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  95474. for (var i = 0; i < 3; i++) {
  95475. for (var j = 0; j < 2; j++) {
  95476. for (var k = 0; k < 2; k++) {
  95477. var index = ((i * 4) + (j * 2)) + k;
  95478. if (i == 0) {
  95479. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95480. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95481. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95482. }
  95483. if (i == 1) {
  95484. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  95485. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95486. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95487. }
  95488. if (i == 2) {
  95489. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  95490. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95491. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95492. }
  95493. if (this.fixedDragMeshScreenSize) {
  95494. this._rootMesh.computeWorldMatrix();
  95495. this._rotateSpheresParent.computeWorldMatrix();
  95496. rotateSpheres[index].computeWorldMatrix();
  95497. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95498. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95499. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95500. }
  95501. else {
  95502. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  95503. }
  95504. }
  95505. }
  95506. }
  95507. // Update scale box locations
  95508. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  95509. for (var i = 0; i < 2; i++) {
  95510. for (var j = 0; j < 2; j++) {
  95511. for (var k = 0; k < 2; k++) {
  95512. var index = ((i * 4) + (j * 2)) + k;
  95513. if (scaleBoxes[index]) {
  95514. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95515. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95516. if (this.fixedDragMeshScreenSize) {
  95517. this._rootMesh.computeWorldMatrix();
  95518. this._scaleBoxesParent.computeWorldMatrix();
  95519. scaleBoxes[index].computeWorldMatrix();
  95520. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95521. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95522. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95523. }
  95524. else {
  95525. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  95526. }
  95527. }
  95528. }
  95529. }
  95530. }
  95531. if (this.attachedMesh) {
  95532. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  95533. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  95534. }
  95535. };
  95536. /**
  95537. * Enables rotation on the specified axis and disables rotation on the others
  95538. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  95539. */
  95540. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  95541. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  95542. if (i < 4) {
  95543. m.setEnabled(axis.indexOf("x") != -1);
  95544. }
  95545. else if (i < 8) {
  95546. m.setEnabled(axis.indexOf("y") != -1);
  95547. }
  95548. else {
  95549. m.setEnabled(axis.indexOf("z") != -1);
  95550. }
  95551. });
  95552. };
  95553. /**
  95554. * Disposes of the gizmo
  95555. */
  95556. BoundingBoxGizmo.prototype.dispose = function () {
  95557. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95558. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  95559. this._lineBoundingBox.dispose();
  95560. this._rotateSpheresParent.dispose();
  95561. this._scaleBoxesParent.dispose();
  95562. _super.prototype.dispose.call(this);
  95563. };
  95564. /**
  95565. * 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)
  95566. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  95567. * @returns the bounding box mesh with the passed in mesh as a child
  95568. */
  95569. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  95570. var makeNotPickable = function (root) {
  95571. root.isPickable = false;
  95572. root.getChildMeshes().forEach(function (c) {
  95573. makeNotPickable(c);
  95574. });
  95575. };
  95576. makeNotPickable(mesh);
  95577. // Reset position to get boudning box from origin with no rotation
  95578. if (!mesh.rotationQuaternion) {
  95579. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  95580. }
  95581. var oldPos = mesh.position.clone();
  95582. var oldRot = mesh.rotationQuaternion.clone();
  95583. mesh.rotationQuaternion.set(0, 0, 0, 1);
  95584. mesh.position.set(0, 0, 0);
  95585. // Update bounding dimensions/positions
  95586. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  95587. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  95588. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  95589. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95590. // Restore original positions
  95591. mesh.addChild(box);
  95592. mesh.rotationQuaternion.copyFrom(oldRot);
  95593. mesh.position.copyFrom(oldPos);
  95594. // Reverse parenting
  95595. mesh.removeChild(box);
  95596. box.addChild(mesh);
  95597. box.visibility = 0;
  95598. return box;
  95599. };
  95600. /**
  95601. * CustomMeshes are not supported by this gizmo
  95602. * @param mesh The mesh to replace the default mesh of the gizmo
  95603. */
  95604. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  95605. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  95606. };
  95607. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  95608. // store/remove pivot point should only be applied during their outermost calls
  95609. BoundingBoxGizmo._PivotCached = 0;
  95610. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  95611. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  95612. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  95613. return BoundingBoxGizmo;
  95614. }(BABYLON.Gizmo));
  95615. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  95616. })(BABYLON || (BABYLON = {}));
  95617. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  95618. var BABYLON;
  95619. (function (BABYLON) {
  95620. /**
  95621. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  95622. */
  95623. var GizmoManager = /** @class */ (function () {
  95624. /**
  95625. * Instatiates a gizmo manager
  95626. * @param scene the scene to overlay the gizmos on top of
  95627. */
  95628. function GizmoManager(scene) {
  95629. var _this = this;
  95630. this.scene = scene;
  95631. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  95632. this._pointerObserver = null;
  95633. this._attachedMesh = null;
  95634. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  95635. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  95636. /**
  95637. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  95638. */
  95639. this.attachableMeshes = null;
  95640. /**
  95641. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  95642. */
  95643. this.usePointerToAttachGizmos = true;
  95644. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  95645. // Instatiate/dispose gizmos based on pointer actions
  95646. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  95647. if (!_this.usePointerToAttachGizmos) {
  95648. return;
  95649. }
  95650. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95651. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  95652. var node = pointerInfo.pickInfo.pickedMesh;
  95653. if (_this.attachableMeshes == null) {
  95654. // Attach to the most parent node
  95655. while (node && node.parent != null) {
  95656. node = node.parent;
  95657. }
  95658. }
  95659. else {
  95660. // Attach to the parent node that is an attachableMesh
  95661. var found = false;
  95662. _this.attachableMeshes.forEach(function (mesh) {
  95663. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  95664. node = mesh;
  95665. found = true;
  95666. }
  95667. });
  95668. if (!found) {
  95669. node = null;
  95670. }
  95671. }
  95672. if (node instanceof BABYLON.AbstractMesh) {
  95673. _this.attachToMesh(node);
  95674. }
  95675. else {
  95676. _this.attachToMesh(null);
  95677. }
  95678. }
  95679. else {
  95680. _this.attachToMesh(null);
  95681. }
  95682. }
  95683. });
  95684. }
  95685. /**
  95686. * Attaches a set of gizmos to the specified mesh
  95687. * @param mesh The mesh the gizmo's should be attached to
  95688. */
  95689. GizmoManager.prototype.attachToMesh = function (mesh) {
  95690. if (this._attachedMesh) {
  95691. this._attachedMesh.removeBehavior(this._dragBehavior);
  95692. }
  95693. this._attachedMesh = mesh;
  95694. for (var key in this.gizmos) {
  95695. var gizmo = (this.gizmos[key]);
  95696. if (gizmo && this._gizmosEnabled[key]) {
  95697. gizmo.attachedMesh = mesh;
  95698. }
  95699. }
  95700. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  95701. this._attachedMesh.addBehavior(this._dragBehavior);
  95702. }
  95703. };
  95704. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  95705. get: function () {
  95706. return this._gizmosEnabled.positionGizmo;
  95707. },
  95708. /**
  95709. * If the position gizmo is enabled
  95710. */
  95711. set: function (value) {
  95712. if (value) {
  95713. if (!this.gizmos.positionGizmo) {
  95714. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  95715. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95716. }
  95717. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  95718. }
  95719. else if (this.gizmos.positionGizmo) {
  95720. this.gizmos.positionGizmo.attachedMesh = null;
  95721. }
  95722. this._gizmosEnabled.positionGizmo = value;
  95723. },
  95724. enumerable: true,
  95725. configurable: true
  95726. });
  95727. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  95728. get: function () {
  95729. return this._gizmosEnabled.rotationGizmo;
  95730. },
  95731. /**
  95732. * If the rotation gizmo is enabled
  95733. */
  95734. set: function (value) {
  95735. if (value) {
  95736. if (!this.gizmos.rotationGizmo) {
  95737. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  95738. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95739. }
  95740. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  95741. }
  95742. else if (this.gizmos.rotationGizmo) {
  95743. this.gizmos.rotationGizmo.attachedMesh = null;
  95744. }
  95745. this._gizmosEnabled.rotationGizmo = value;
  95746. },
  95747. enumerable: true,
  95748. configurable: true
  95749. });
  95750. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  95751. get: function () {
  95752. return this._gizmosEnabled.scaleGizmo;
  95753. },
  95754. /**
  95755. * If the scale gizmo is enabled
  95756. */
  95757. set: function (value) {
  95758. if (value) {
  95759. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  95760. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  95761. }
  95762. else if (this.gizmos.scaleGizmo) {
  95763. this.gizmos.scaleGizmo.attachedMesh = null;
  95764. }
  95765. this._gizmosEnabled.scaleGizmo = value;
  95766. },
  95767. enumerable: true,
  95768. configurable: true
  95769. });
  95770. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  95771. get: function () {
  95772. return this._gizmosEnabled.boundingBoxGizmo;
  95773. },
  95774. /**
  95775. * If the boundingBox gizmo is enabled
  95776. */
  95777. set: function (value) {
  95778. if (value) {
  95779. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  95780. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  95781. if (this._attachedMesh) {
  95782. this._attachedMesh.removeBehavior(this._dragBehavior);
  95783. this._attachedMesh.addBehavior(this._dragBehavior);
  95784. }
  95785. }
  95786. else if (this.gizmos.boundingBoxGizmo) {
  95787. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95788. }
  95789. this._gizmosEnabled.boundingBoxGizmo = value;
  95790. },
  95791. enumerable: true,
  95792. configurable: true
  95793. });
  95794. /**
  95795. * Disposes of the gizmo manager
  95796. */
  95797. GizmoManager.prototype.dispose = function () {
  95798. this.scene.onPointerObservable.remove(this._pointerObserver);
  95799. for (var key in this.gizmos) {
  95800. var gizmo = (this.gizmos[key]);
  95801. if (gizmo) {
  95802. gizmo.dispose();
  95803. }
  95804. }
  95805. this._dragBehavior.detach();
  95806. };
  95807. return GizmoManager;
  95808. }());
  95809. BABYLON.GizmoManager = GizmoManager;
  95810. })(BABYLON || (BABYLON = {}));
  95811. //# sourceMappingURL=babylon.gizmoManager.js.map
  95812. var BABYLON;
  95813. (function (BABYLON) {
  95814. /**
  95815. * Defines a target to use with MorphTargetManager
  95816. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95817. */
  95818. var MorphTarget = /** @class */ (function () {
  95819. /**
  95820. * Creates a new MorphTarget
  95821. * @param name defines the name of the target
  95822. * @param influence defines the influence to use
  95823. */
  95824. function MorphTarget(
  95825. /** defines the name of the target */
  95826. name, influence, scene) {
  95827. if (influence === void 0) { influence = 0; }
  95828. if (scene === void 0) { scene = null; }
  95829. this.name = name;
  95830. /**
  95831. * Gets or sets the list of animations
  95832. */
  95833. this.animations = new Array();
  95834. this._positions = null;
  95835. this._normals = null;
  95836. this._tangents = null;
  95837. /**
  95838. * Observable raised when the influence changes
  95839. */
  95840. this.onInfluenceChanged = new BABYLON.Observable();
  95841. this._animationPropertiesOverride = null;
  95842. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95843. this.influence = influence;
  95844. }
  95845. Object.defineProperty(MorphTarget.prototype, "influence", {
  95846. /**
  95847. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95848. */
  95849. get: function () {
  95850. return this._influence;
  95851. },
  95852. set: function (influence) {
  95853. if (this._influence === influence) {
  95854. return;
  95855. }
  95856. var previous = this._influence;
  95857. this._influence = influence;
  95858. if (this.onInfluenceChanged.hasObservers) {
  95859. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95860. }
  95861. },
  95862. enumerable: true,
  95863. configurable: true
  95864. });
  95865. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95866. /**
  95867. * Gets or sets the animation properties override
  95868. */
  95869. get: function () {
  95870. if (!this._animationPropertiesOverride && this._scene) {
  95871. return this._scene.animationPropertiesOverride;
  95872. }
  95873. return this._animationPropertiesOverride;
  95874. },
  95875. set: function (value) {
  95876. this._animationPropertiesOverride = value;
  95877. },
  95878. enumerable: true,
  95879. configurable: true
  95880. });
  95881. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95882. /**
  95883. * Gets a boolean defining if the target contains position data
  95884. */
  95885. get: function () {
  95886. return !!this._positions;
  95887. },
  95888. enumerable: true,
  95889. configurable: true
  95890. });
  95891. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95892. /**
  95893. * Gets a boolean defining if the target contains normal data
  95894. */
  95895. get: function () {
  95896. return !!this._normals;
  95897. },
  95898. enumerable: true,
  95899. configurable: true
  95900. });
  95901. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95902. /**
  95903. * Gets a boolean defining if the target contains tangent data
  95904. */
  95905. get: function () {
  95906. return !!this._tangents;
  95907. },
  95908. enumerable: true,
  95909. configurable: true
  95910. });
  95911. /**
  95912. * Affects position data to this target
  95913. * @param data defines the position data to use
  95914. */
  95915. MorphTarget.prototype.setPositions = function (data) {
  95916. this._positions = data;
  95917. };
  95918. /**
  95919. * Gets the position data stored in this target
  95920. * @returns a FloatArray containing the position data (or null if not present)
  95921. */
  95922. MorphTarget.prototype.getPositions = function () {
  95923. return this._positions;
  95924. };
  95925. /**
  95926. * Affects normal data to this target
  95927. * @param data defines the normal data to use
  95928. */
  95929. MorphTarget.prototype.setNormals = function (data) {
  95930. this._normals = data;
  95931. };
  95932. /**
  95933. * Gets the normal data stored in this target
  95934. * @returns a FloatArray containing the normal data (or null if not present)
  95935. */
  95936. MorphTarget.prototype.getNormals = function () {
  95937. return this._normals;
  95938. };
  95939. /**
  95940. * Affects tangent data to this target
  95941. * @param data defines the tangent data to use
  95942. */
  95943. MorphTarget.prototype.setTangents = function (data) {
  95944. this._tangents = data;
  95945. };
  95946. /**
  95947. * Gets the tangent data stored in this target
  95948. * @returns a FloatArray containing the tangent data (or null if not present)
  95949. */
  95950. MorphTarget.prototype.getTangents = function () {
  95951. return this._tangents;
  95952. };
  95953. /**
  95954. * Serializes the current target into a Serialization object
  95955. * @returns the serialized object
  95956. */
  95957. MorphTarget.prototype.serialize = function () {
  95958. var serializationObject = {};
  95959. serializationObject.name = this.name;
  95960. serializationObject.influence = this.influence;
  95961. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95962. if (this.hasNormals) {
  95963. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95964. }
  95965. if (this.hasTangents) {
  95966. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95967. }
  95968. // Animations
  95969. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95970. return serializationObject;
  95971. };
  95972. // Statics
  95973. /**
  95974. * Creates a new target from serialized data
  95975. * @param serializationObject defines the serialized data to use
  95976. * @returns a new MorphTarget
  95977. */
  95978. MorphTarget.Parse = function (serializationObject) {
  95979. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95980. result.setPositions(serializationObject.positions);
  95981. if (serializationObject.normals) {
  95982. result.setNormals(serializationObject.normals);
  95983. }
  95984. if (serializationObject.tangents) {
  95985. result.setTangents(serializationObject.tangents);
  95986. }
  95987. // Animations
  95988. if (serializationObject.animations) {
  95989. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95990. var parsedAnimation = serializationObject.animations[animationIndex];
  95991. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95992. }
  95993. }
  95994. return result;
  95995. };
  95996. /**
  95997. * Creates a MorphTarget from mesh data
  95998. * @param mesh defines the source mesh
  95999. * @param name defines the name to use for the new target
  96000. * @param influence defines the influence to attach to the target
  96001. * @returns a new MorphTarget
  96002. */
  96003. MorphTarget.FromMesh = function (mesh, name, influence) {
  96004. if (!name) {
  96005. name = mesh.name;
  96006. }
  96007. var result = new MorphTarget(name, influence, mesh.getScene());
  96008. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96010. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  96011. }
  96012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  96013. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  96014. }
  96015. return result;
  96016. };
  96017. return MorphTarget;
  96018. }());
  96019. BABYLON.MorphTarget = MorphTarget;
  96020. })(BABYLON || (BABYLON = {}));
  96021. //# sourceMappingURL=babylon.morphTarget.js.map
  96022. var BABYLON;
  96023. (function (BABYLON) {
  96024. /**
  96025. * This class is used to deform meshes using morphing between different targets
  96026. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  96027. */
  96028. var MorphTargetManager = /** @class */ (function () {
  96029. /**
  96030. * Creates a new MorphTargetManager
  96031. * @param scene defines the current scene
  96032. */
  96033. function MorphTargetManager(scene) {
  96034. if (scene === void 0) { scene = null; }
  96035. this._targets = new Array();
  96036. this._targetObservable = new Array();
  96037. this._activeTargets = new BABYLON.SmartArray(16);
  96038. this._supportsNormals = false;
  96039. this._supportsTangents = false;
  96040. this._vertexCount = 0;
  96041. this._uniqueId = 0;
  96042. this._tempInfluences = new Array();
  96043. if (!scene) {
  96044. scene = BABYLON.Engine.LastCreatedScene;
  96045. }
  96046. this._scene = scene;
  96047. if (this._scene) {
  96048. this._scene.morphTargetManagers.push(this);
  96049. this._uniqueId = this._scene.getUniqueId();
  96050. }
  96051. }
  96052. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  96053. /**
  96054. * Gets the unique ID of this manager
  96055. */
  96056. get: function () {
  96057. return this._uniqueId;
  96058. },
  96059. enumerable: true,
  96060. configurable: true
  96061. });
  96062. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  96063. /**
  96064. * Gets the number of vertices handled by this manager
  96065. */
  96066. get: function () {
  96067. return this._vertexCount;
  96068. },
  96069. enumerable: true,
  96070. configurable: true
  96071. });
  96072. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  96073. /**
  96074. * Gets a boolean indicating if this manager supports morphing of normals
  96075. */
  96076. get: function () {
  96077. return this._supportsNormals;
  96078. },
  96079. enumerable: true,
  96080. configurable: true
  96081. });
  96082. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  96083. /**
  96084. * Gets a boolean indicating if this manager supports morphing of tangents
  96085. */
  96086. get: function () {
  96087. return this._supportsTangents;
  96088. },
  96089. enumerable: true,
  96090. configurable: true
  96091. });
  96092. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  96093. /**
  96094. * Gets the number of targets stored in this manager
  96095. */
  96096. get: function () {
  96097. return this._targets.length;
  96098. },
  96099. enumerable: true,
  96100. configurable: true
  96101. });
  96102. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  96103. /**
  96104. * Gets the number of influencers (ie. the number of targets with influences > 0)
  96105. */
  96106. get: function () {
  96107. return this._activeTargets.length;
  96108. },
  96109. enumerable: true,
  96110. configurable: true
  96111. });
  96112. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  96113. /**
  96114. * Gets the list of influences (one per target)
  96115. */
  96116. get: function () {
  96117. return this._influences;
  96118. },
  96119. enumerable: true,
  96120. configurable: true
  96121. });
  96122. /**
  96123. * Gets the active target at specified index. An active target is a target with an influence > 0
  96124. * @param index defines the index to check
  96125. * @returns the requested target
  96126. */
  96127. MorphTargetManager.prototype.getActiveTarget = function (index) {
  96128. return this._activeTargets.data[index];
  96129. };
  96130. /**
  96131. * Gets the target at specified index
  96132. * @param index defines the index to check
  96133. * @returns the requested target
  96134. */
  96135. MorphTargetManager.prototype.getTarget = function (index) {
  96136. return this._targets[index];
  96137. };
  96138. /**
  96139. * Add a new target to this manager
  96140. * @param target defines the target to add
  96141. */
  96142. MorphTargetManager.prototype.addTarget = function (target) {
  96143. var _this = this;
  96144. this._targets.push(target);
  96145. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  96146. _this._syncActiveTargets(needUpdate);
  96147. }));
  96148. this._syncActiveTargets(true);
  96149. };
  96150. /**
  96151. * Removes a target from the manager
  96152. * @param target defines the target to remove
  96153. */
  96154. MorphTargetManager.prototype.removeTarget = function (target) {
  96155. var index = this._targets.indexOf(target);
  96156. if (index >= 0) {
  96157. this._targets.splice(index, 1);
  96158. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  96159. this._syncActiveTargets(true);
  96160. }
  96161. };
  96162. /**
  96163. * Serializes the current manager into a Serialization object
  96164. * @returns the serialized object
  96165. */
  96166. MorphTargetManager.prototype.serialize = function () {
  96167. var serializationObject = {};
  96168. serializationObject.id = this.uniqueId;
  96169. serializationObject.targets = [];
  96170. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  96171. var target = _a[_i];
  96172. serializationObject.targets.push(target.serialize());
  96173. }
  96174. return serializationObject;
  96175. };
  96176. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  96177. var influenceCount = 0;
  96178. this._activeTargets.reset();
  96179. this._supportsNormals = true;
  96180. this._supportsTangents = true;
  96181. this._vertexCount = 0;
  96182. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  96183. var target = _a[_i];
  96184. this._activeTargets.push(target);
  96185. this._tempInfluences[influenceCount++] = target.influence;
  96186. var positions = target.getPositions();
  96187. if (positions) {
  96188. this._supportsNormals = this._supportsNormals && target.hasNormals;
  96189. this._supportsTangents = this._supportsTangents && target.hasTangents;
  96190. var vertexCount = positions.length / 3;
  96191. if (this._vertexCount === 0) {
  96192. this._vertexCount = vertexCount;
  96193. }
  96194. else if (this._vertexCount !== vertexCount) {
  96195. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  96196. return;
  96197. }
  96198. }
  96199. }
  96200. if (!this._influences || this._influences.length !== influenceCount) {
  96201. this._influences = new Float32Array(influenceCount);
  96202. }
  96203. for (var index = 0; index < influenceCount; index++) {
  96204. this._influences[index] = this._tempInfluences[index];
  96205. }
  96206. if (needUpdate) {
  96207. this.synchronize();
  96208. }
  96209. };
  96210. /**
  96211. * Syncrhonize the targets with all the meshes using this morph target manager
  96212. */
  96213. MorphTargetManager.prototype.synchronize = function () {
  96214. if (!this._scene) {
  96215. return;
  96216. }
  96217. // Flag meshes as dirty to resync with the active targets
  96218. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  96219. var mesh = _a[_i];
  96220. if (mesh.morphTargetManager === this) {
  96221. mesh._syncGeometryWithMorphTargetManager();
  96222. }
  96223. }
  96224. };
  96225. // Statics
  96226. /**
  96227. * Creates a new MorphTargetManager from serialized data
  96228. * @param serializationObject defines the serialized data
  96229. * @param scene defines the hosting scene
  96230. * @returns the new MorphTargetManager
  96231. */
  96232. MorphTargetManager.Parse = function (serializationObject, scene) {
  96233. var result = new MorphTargetManager(scene);
  96234. result._uniqueId = serializationObject.id;
  96235. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  96236. var targetData = _a[_i];
  96237. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  96238. }
  96239. return result;
  96240. };
  96241. return MorphTargetManager;
  96242. }());
  96243. BABYLON.MorphTargetManager = MorphTargetManager;
  96244. })(BABYLON || (BABYLON = {}));
  96245. //# sourceMappingURL=babylon.morphTargetManager.js.map
  96246. var BABYLON;
  96247. (function (BABYLON) {
  96248. var Octree = /** @class */ (function () {
  96249. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  96250. if (maxDepth === void 0) { maxDepth = 2; }
  96251. this.maxDepth = maxDepth;
  96252. this.dynamicContent = new Array();
  96253. this._maxBlockCapacity = maxBlockCapacity || 64;
  96254. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  96255. this._creationFunc = creationFunc;
  96256. }
  96257. // Methods
  96258. Octree.prototype.update = function (worldMin, worldMax, entries) {
  96259. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  96260. };
  96261. Octree.prototype.addMesh = function (entry) {
  96262. for (var index = 0; index < this.blocks.length; index++) {
  96263. var block = this.blocks[index];
  96264. block.addEntry(entry);
  96265. }
  96266. };
  96267. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  96268. this._selectionContent.reset();
  96269. for (var index = 0; index < this.blocks.length; index++) {
  96270. var block = this.blocks[index];
  96271. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  96272. }
  96273. if (allowDuplicate) {
  96274. this._selectionContent.concat(this.dynamicContent);
  96275. }
  96276. else {
  96277. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96278. }
  96279. return this._selectionContent;
  96280. };
  96281. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  96282. this._selectionContent.reset();
  96283. for (var index = 0; index < this.blocks.length; index++) {
  96284. var block = this.blocks[index];
  96285. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  96286. }
  96287. if (allowDuplicate) {
  96288. this._selectionContent.concat(this.dynamicContent);
  96289. }
  96290. else {
  96291. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96292. }
  96293. return this._selectionContent;
  96294. };
  96295. Octree.prototype.intersectsRay = function (ray) {
  96296. this._selectionContent.reset();
  96297. for (var index = 0; index < this.blocks.length; index++) {
  96298. var block = this.blocks[index];
  96299. block.intersectsRay(ray, this._selectionContent);
  96300. }
  96301. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  96302. return this._selectionContent;
  96303. };
  96304. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  96305. target.blocks = new Array();
  96306. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  96307. // Segmenting space
  96308. for (var x = 0; x < 2; x++) {
  96309. for (var y = 0; y < 2; y++) {
  96310. for (var z = 0; z < 2; z++) {
  96311. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  96312. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  96313. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  96314. block.addEntries(entries);
  96315. target.blocks.push(block);
  96316. }
  96317. }
  96318. }
  96319. };
  96320. Octree.CreationFuncForMeshes = function (entry, block) {
  96321. var boundingInfo = entry.getBoundingInfo();
  96322. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96323. block.entries.push(entry);
  96324. }
  96325. };
  96326. Octree.CreationFuncForSubMeshes = function (entry, block) {
  96327. var boundingInfo = entry.getBoundingInfo();
  96328. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96329. block.entries.push(entry);
  96330. }
  96331. };
  96332. return Octree;
  96333. }());
  96334. BABYLON.Octree = Octree;
  96335. })(BABYLON || (BABYLON = {}));
  96336. //# sourceMappingURL=babylon.octree.js.map
  96337. var BABYLON;
  96338. (function (BABYLON) {
  96339. var OctreeBlock = /** @class */ (function () {
  96340. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  96341. this.entries = new Array();
  96342. this._boundingVectors = new Array();
  96343. this._capacity = capacity;
  96344. this._depth = depth;
  96345. this._maxDepth = maxDepth;
  96346. this._creationFunc = creationFunc;
  96347. this._minPoint = minPoint;
  96348. this._maxPoint = maxPoint;
  96349. this._boundingVectors.push(minPoint.clone());
  96350. this._boundingVectors.push(maxPoint.clone());
  96351. this._boundingVectors.push(minPoint.clone());
  96352. this._boundingVectors[2].x = maxPoint.x;
  96353. this._boundingVectors.push(minPoint.clone());
  96354. this._boundingVectors[3].y = maxPoint.y;
  96355. this._boundingVectors.push(minPoint.clone());
  96356. this._boundingVectors[4].z = maxPoint.z;
  96357. this._boundingVectors.push(maxPoint.clone());
  96358. this._boundingVectors[5].z = minPoint.z;
  96359. this._boundingVectors.push(maxPoint.clone());
  96360. this._boundingVectors[6].x = minPoint.x;
  96361. this._boundingVectors.push(maxPoint.clone());
  96362. this._boundingVectors[7].y = minPoint.y;
  96363. }
  96364. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  96365. // Property
  96366. get: function () {
  96367. return this._capacity;
  96368. },
  96369. enumerable: true,
  96370. configurable: true
  96371. });
  96372. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  96373. get: function () {
  96374. return this._minPoint;
  96375. },
  96376. enumerable: true,
  96377. configurable: true
  96378. });
  96379. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  96380. get: function () {
  96381. return this._maxPoint;
  96382. },
  96383. enumerable: true,
  96384. configurable: true
  96385. });
  96386. // Methods
  96387. OctreeBlock.prototype.addEntry = function (entry) {
  96388. if (this.blocks) {
  96389. for (var index = 0; index < this.blocks.length; index++) {
  96390. var block = this.blocks[index];
  96391. block.addEntry(entry);
  96392. }
  96393. return;
  96394. }
  96395. this._creationFunc(entry, this);
  96396. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  96397. this.createInnerBlocks();
  96398. }
  96399. };
  96400. OctreeBlock.prototype.addEntries = function (entries) {
  96401. for (var index = 0; index < entries.length; index++) {
  96402. var mesh = entries[index];
  96403. this.addEntry(mesh);
  96404. }
  96405. };
  96406. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  96407. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  96408. if (this.blocks) {
  96409. for (var index = 0; index < this.blocks.length; index++) {
  96410. var block = this.blocks[index];
  96411. block.select(frustumPlanes, selection, allowDuplicate);
  96412. }
  96413. return;
  96414. }
  96415. if (allowDuplicate) {
  96416. selection.concat(this.entries);
  96417. }
  96418. else {
  96419. selection.concatWithNoDuplicate(this.entries);
  96420. }
  96421. }
  96422. };
  96423. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  96424. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  96425. if (this.blocks) {
  96426. for (var index = 0; index < this.blocks.length; index++) {
  96427. var block = this.blocks[index];
  96428. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  96429. }
  96430. return;
  96431. }
  96432. if (allowDuplicate) {
  96433. selection.concat(this.entries);
  96434. }
  96435. else {
  96436. selection.concatWithNoDuplicate(this.entries);
  96437. }
  96438. }
  96439. };
  96440. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  96441. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  96442. if (this.blocks) {
  96443. for (var index = 0; index < this.blocks.length; index++) {
  96444. var block = this.blocks[index];
  96445. block.intersectsRay(ray, selection);
  96446. }
  96447. return;
  96448. }
  96449. selection.concatWithNoDuplicate(this.entries);
  96450. }
  96451. };
  96452. OctreeBlock.prototype.createInnerBlocks = function () {
  96453. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  96454. };
  96455. return OctreeBlock;
  96456. }());
  96457. BABYLON.OctreeBlock = OctreeBlock;
  96458. })(BABYLON || (BABYLON = {}));
  96459. //# sourceMappingURL=babylon.octreeBlock.js.map
  96460. var BABYLON;
  96461. (function (BABYLON) {
  96462. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  96463. if (maxCapacity === void 0) { maxCapacity = 64; }
  96464. if (maxDepth === void 0) { maxDepth = 2; }
  96465. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96466. if (!component) {
  96467. component = new OctreeSceneComponent(this);
  96468. this._addComponent(component);
  96469. }
  96470. if (!this._selectionOctree) {
  96471. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  96472. }
  96473. var worldExtends = this.getWorldExtends();
  96474. // Update octree
  96475. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  96476. return this._selectionOctree;
  96477. };
  96478. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  96479. get: function () {
  96480. return this._selectionOctree;
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. /**
  96486. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  96487. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  96488. * @param maxCapacity defines the maximum size of each block (64 by default)
  96489. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  96490. * @returns the new octree
  96491. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  96492. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  96493. */
  96494. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  96495. if (maxCapacity === void 0) { maxCapacity = 64; }
  96496. if (maxDepth === void 0) { maxDepth = 2; }
  96497. var scene = this.getScene();
  96498. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96499. if (!component) {
  96500. component = new OctreeSceneComponent(scene);
  96501. scene._addComponent(component);
  96502. }
  96503. if (!this._submeshesOctree) {
  96504. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  96505. }
  96506. this.computeWorldMatrix(true);
  96507. var boundingInfo = this.getBoundingInfo();
  96508. // Update octree
  96509. var bbox = boundingInfo.boundingBox;
  96510. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  96511. return this._submeshesOctree;
  96512. };
  96513. /**
  96514. * Defines the octree scene component responsible to manage any octrees
  96515. * in a given scene.
  96516. */
  96517. var OctreeSceneComponent = /** @class */ (function () {
  96518. /**
  96519. * Creates a new instance of the component for the given scene
  96520. * @param scene Defines the scene to register the component in
  96521. */
  96522. function OctreeSceneComponent(scene) {
  96523. /**
  96524. * The component name helpfull to identify the component in the list of scene components.
  96525. */
  96526. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  96527. /**
  96528. * Indicates if the meshes have been checked to make sure they are isEnabled()
  96529. */
  96530. this.checksIsEnabled = true;
  96531. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  96532. this.scene = scene;
  96533. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  96534. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  96535. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  96536. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  96537. }
  96538. /**
  96539. * Registers the component in a given scene
  96540. */
  96541. OctreeSceneComponent.prototype.register = function () {
  96542. var _this = this;
  96543. this.scene.onMeshRemovedObservable.add(function (mesh) {
  96544. var sceneOctree = _this.scene.selectionOctree;
  96545. if (sceneOctree !== undefined && sceneOctree !== null) {
  96546. var index = sceneOctree.dynamicContent.indexOf(mesh);
  96547. if (index !== -1) {
  96548. sceneOctree.dynamicContent.splice(index, 1);
  96549. }
  96550. }
  96551. });
  96552. this.scene.onMeshImportedObservable.add(function (mesh) {
  96553. var sceneOctree = _this.scene.selectionOctree;
  96554. if (sceneOctree !== undefined && sceneOctree !== null) {
  96555. sceneOctree.addMesh(mesh);
  96556. }
  96557. });
  96558. };
  96559. /**
  96560. * Return the list of active meshes
  96561. * @returns the list of active meshes
  96562. */
  96563. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  96564. if (this.scene._selectionOctree) {
  96565. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  96566. return selection;
  96567. }
  96568. return this.scene._getDefaultMeshCandidates();
  96569. };
  96570. /**
  96571. * Return the list of active sub meshes
  96572. * @param mesh The mesh to get the candidates sub meshes from
  96573. * @returns the list of active sub meshes
  96574. */
  96575. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  96576. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  96577. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  96578. return intersections;
  96579. }
  96580. return this.scene._getDefaultSubMeshCandidates(mesh);
  96581. };
  96582. /**
  96583. * Return the list of sub meshes intersecting with a given local ray
  96584. * @param mesh defines the mesh to find the submesh for
  96585. * @param localRay defines the ray in local space
  96586. * @returns the list of intersecting sub meshes
  96587. */
  96588. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  96589. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  96590. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  96591. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  96592. return intersections;
  96593. }
  96594. return this.scene._getDefaultSubMeshCandidates(mesh);
  96595. };
  96596. /**
  96597. * Return the list of sub meshes colliding with a collider
  96598. * @param mesh defines the mesh to find the submesh for
  96599. * @param collider defines the collider to evaluate the collision against
  96600. * @returns the list of colliding sub meshes
  96601. */
  96602. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  96603. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  96604. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  96605. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  96606. return intersections;
  96607. }
  96608. return this.scene._getDefaultSubMeshCandidates(mesh);
  96609. };
  96610. /**
  96611. * Rebuilds the elements related to this component in case of
  96612. * context lost for instance.
  96613. */
  96614. OctreeSceneComponent.prototype.rebuild = function () {
  96615. // Nothing to do here.
  96616. };
  96617. /**
  96618. * Disposes the component and the associated ressources.
  96619. */
  96620. OctreeSceneComponent.prototype.dispose = function () {
  96621. // Nothing to do here.
  96622. };
  96623. return OctreeSceneComponent;
  96624. }());
  96625. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  96626. })(BABYLON || (BABYLON = {}));
  96627. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  96628. var BABYLON;
  96629. (function (BABYLON) {
  96630. /**
  96631. * Postprocess used to generate anaglyphic rendering
  96632. */
  96633. var AnaglyphPostProcess = /** @class */ (function (_super) {
  96634. __extends(AnaglyphPostProcess, _super);
  96635. /**
  96636. * Creates a new AnaglyphPostProcess
  96637. * @param name defines postprocess name
  96638. * @param options defines creation options or target ratio scale
  96639. * @param rigCameras defines cameras using this postprocess
  96640. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  96641. * @param engine defines hosting engine
  96642. * @param reusable defines if the postprocess will be reused multiple times per frame
  96643. */
  96644. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  96645. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  96646. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96647. _this.onApplyObservable.add(function (effect) {
  96648. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  96649. });
  96650. return _this;
  96651. }
  96652. return AnaglyphPostProcess;
  96653. }(BABYLON.PostProcess));
  96654. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  96655. })(BABYLON || (BABYLON = {}));
  96656. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  96657. var BABYLON;
  96658. (function (BABYLON) {
  96659. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  96660. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96661. });
  96662. /**
  96663. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  96664. */
  96665. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  96666. __extends(AnaglyphArcRotateCamera, _super);
  96667. /**
  96668. * Creates a new AnaglyphArcRotateCamera
  96669. * @param name defines camera name
  96670. * @param alpha defines alpha angle (in radians)
  96671. * @param beta defines beta angle (in radians)
  96672. * @param radius defines radius
  96673. * @param target defines camera target
  96674. * @param interaxialDistance defines distance between each color axis
  96675. * @param scene defines the hosting scene
  96676. */
  96677. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  96678. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96679. _this.interaxialDistance = interaxialDistance;
  96680. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96681. return _this;
  96682. }
  96683. /**
  96684. * Gets camera class name
  96685. * @returns AnaglyphArcRotateCamera
  96686. */
  96687. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  96688. return "AnaglyphArcRotateCamera";
  96689. };
  96690. return AnaglyphArcRotateCamera;
  96691. }(BABYLON.ArcRotateCamera));
  96692. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  96693. })(BABYLON || (BABYLON = {}));
  96694. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  96695. var BABYLON;
  96696. (function (BABYLON) {
  96697. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  96698. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96699. });
  96700. /**
  96701. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  96702. */
  96703. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  96704. __extends(AnaglyphFreeCamera, _super);
  96705. /**
  96706. * Creates a new AnaglyphFreeCamera
  96707. * @param name defines camera name
  96708. * @param position defines initial position
  96709. * @param interaxialDistance defines distance between each color axis
  96710. * @param scene defines the hosting scene
  96711. */
  96712. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  96713. var _this = _super.call(this, name, position, scene) || this;
  96714. _this.interaxialDistance = interaxialDistance;
  96715. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96716. return _this;
  96717. }
  96718. /**
  96719. * Gets camera class name
  96720. * @returns AnaglyphFreeCamera
  96721. */
  96722. AnaglyphFreeCamera.prototype.getClassName = function () {
  96723. return "AnaglyphFreeCamera";
  96724. };
  96725. return AnaglyphFreeCamera;
  96726. }(BABYLON.FreeCamera));
  96727. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  96728. })(BABYLON || (BABYLON = {}));
  96729. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  96730. var BABYLON;
  96731. (function (BABYLON) {
  96732. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  96733. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96734. });
  96735. /**
  96736. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  96737. */
  96738. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  96739. __extends(AnaglyphGamepadCamera, _super);
  96740. /**
  96741. * Creates a new AnaglyphGamepadCamera
  96742. * @param name defines camera name
  96743. * @param position defines initial position
  96744. * @param interaxialDistance defines distance between each color axis
  96745. * @param scene defines the hosting scene
  96746. */
  96747. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  96748. var _this = _super.call(this, name, position, scene) || this;
  96749. _this.interaxialDistance = interaxialDistance;
  96750. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96751. return _this;
  96752. }
  96753. /**
  96754. * Gets camera class name
  96755. * @returns AnaglyphGamepadCamera
  96756. */
  96757. AnaglyphGamepadCamera.prototype.getClassName = function () {
  96758. return "AnaglyphGamepadCamera";
  96759. };
  96760. return AnaglyphGamepadCamera;
  96761. }(BABYLON.GamepadCamera));
  96762. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  96763. })(BABYLON || (BABYLON = {}));
  96764. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  96765. var BABYLON;
  96766. (function (BABYLON) {
  96767. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  96768. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96769. });
  96770. /**
  96771. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  96772. */
  96773. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  96774. __extends(AnaglyphUniversalCamera, _super);
  96775. /**
  96776. * Creates a new AnaglyphUniversalCamera
  96777. * @param name defines camera name
  96778. * @param position defines initial position
  96779. * @param interaxialDistance defines distance between each color axis
  96780. * @param scene defines the hosting scene
  96781. */
  96782. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  96783. var _this = _super.call(this, name, position, scene) || this;
  96784. _this.interaxialDistance = interaxialDistance;
  96785. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96786. return _this;
  96787. }
  96788. /**
  96789. * Gets camera class name
  96790. * @returns AnaglyphUniversalCamera
  96791. */
  96792. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96793. return "AnaglyphUniversalCamera";
  96794. };
  96795. return AnaglyphUniversalCamera;
  96796. }(BABYLON.UniversalCamera));
  96797. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96798. })(BABYLON || (BABYLON = {}));
  96799. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96800. var BABYLON;
  96801. (function (BABYLON) {
  96802. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96803. __extends(StereoscopicInterlacePostProcess, _super);
  96804. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96805. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96806. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96807. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96808. _this.onSizeChangedObservable.add(function () {
  96809. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96810. });
  96811. _this.onApplyObservable.add(function (effect) {
  96812. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96813. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96814. });
  96815. return _this;
  96816. }
  96817. return StereoscopicInterlacePostProcess;
  96818. }(BABYLON.PostProcess));
  96819. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96820. })(BABYLON || (BABYLON = {}));
  96821. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96822. var BABYLON;
  96823. (function (BABYLON) {
  96824. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96825. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96826. });
  96827. /**
  96828. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96829. */
  96830. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96831. __extends(StereoscopicArcRotateCamera, _super);
  96832. /**
  96833. * Creates a new StereoscopicArcRotateCamera
  96834. * @param name defines camera name
  96835. * @param alpha defines alpha angle (in radians)
  96836. * @param beta defines beta angle (in radians)
  96837. * @param radius defines radius
  96838. * @param target defines camera target
  96839. * @param interaxialDistance defines distance between each color axis
  96840. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96841. * @param scene defines the hosting scene
  96842. */
  96843. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96844. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96845. _this.interaxialDistance = interaxialDistance;
  96846. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96847. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96848. return _this;
  96849. }
  96850. /**
  96851. * Gets camera class name
  96852. * @returns StereoscopicArcRotateCamera
  96853. */
  96854. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96855. return "StereoscopicArcRotateCamera";
  96856. };
  96857. return StereoscopicArcRotateCamera;
  96858. }(BABYLON.ArcRotateCamera));
  96859. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96860. })(BABYLON || (BABYLON = {}));
  96861. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96862. var BABYLON;
  96863. (function (BABYLON) {
  96864. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96865. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96866. });
  96867. /**
  96868. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96869. */
  96870. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96871. __extends(StereoscopicFreeCamera, _super);
  96872. /**
  96873. * Creates a new StereoscopicFreeCamera
  96874. * @param name defines camera name
  96875. * @param position defines initial position
  96876. * @param interaxialDistance defines distance between each color axis
  96877. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96878. * @param scene defines the hosting scene
  96879. */
  96880. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96881. var _this = _super.call(this, name, position, scene) || this;
  96882. _this.interaxialDistance = interaxialDistance;
  96883. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96884. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96885. return _this;
  96886. }
  96887. /**
  96888. * Gets camera class name
  96889. * @returns StereoscopicFreeCamera
  96890. */
  96891. StereoscopicFreeCamera.prototype.getClassName = function () {
  96892. return "StereoscopicFreeCamera";
  96893. };
  96894. return StereoscopicFreeCamera;
  96895. }(BABYLON.FreeCamera));
  96896. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96897. })(BABYLON || (BABYLON = {}));
  96898. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96899. var BABYLON;
  96900. (function (BABYLON) {
  96901. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96902. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96903. });
  96904. /**
  96905. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96906. */
  96907. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96908. __extends(StereoscopicGamepadCamera, _super);
  96909. /**
  96910. * Creates a new StereoscopicGamepadCamera
  96911. * @param name defines camera name
  96912. * @param position defines initial position
  96913. * @param interaxialDistance defines distance between each color axis
  96914. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96915. * @param scene defines the hosting scene
  96916. */
  96917. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96918. var _this = _super.call(this, name, position, scene) || this;
  96919. _this.interaxialDistance = interaxialDistance;
  96920. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96921. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96922. return _this;
  96923. }
  96924. /**
  96925. * Gets camera class name
  96926. * @returns StereoscopicGamepadCamera
  96927. */
  96928. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96929. return "StereoscopicGamepadCamera";
  96930. };
  96931. return StereoscopicGamepadCamera;
  96932. }(BABYLON.GamepadCamera));
  96933. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96934. })(BABYLON || (BABYLON = {}));
  96935. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96936. var BABYLON;
  96937. (function (BABYLON) {
  96938. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96939. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96940. });
  96941. /**
  96942. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96943. */
  96944. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96945. __extends(StereoscopicUniversalCamera, _super);
  96946. /**
  96947. * Creates a new StereoscopicUniversalCamera
  96948. * @param name defines camera name
  96949. * @param position defines initial position
  96950. * @param interaxialDistance defines distance between each color axis
  96951. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96952. * @param scene defines the hosting scene
  96953. */
  96954. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96955. var _this = _super.call(this, name, position, scene) || this;
  96956. _this.interaxialDistance = interaxialDistance;
  96957. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96958. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96959. return _this;
  96960. }
  96961. /**
  96962. * Gets camera class name
  96963. * @returns StereoscopicUniversalCamera
  96964. */
  96965. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96966. return "StereoscopicUniversalCamera";
  96967. };
  96968. return StereoscopicUniversalCamera;
  96969. }(BABYLON.UniversalCamera));
  96970. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96971. })(BABYLON || (BABYLON = {}));
  96972. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96973. var BABYLON;
  96974. (function (BABYLON) {
  96975. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96976. __extends(VRDistortionCorrectionPostProcess, _super);
  96977. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96978. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96979. 'LensCenter',
  96980. 'Scale',
  96981. 'ScaleIn',
  96982. 'HmdWarpParam'
  96983. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96984. _this._isRightEye = isRightEye;
  96985. _this._distortionFactors = vrMetrics.distortionK;
  96986. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96987. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96988. _this.adaptScaleToCurrentViewport = true;
  96989. _this.onSizeChangedObservable.add(function () {
  96990. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96991. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96992. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96993. });
  96994. _this.onApplyObservable.add(function (effect) {
  96995. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96996. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96997. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96998. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96999. });
  97000. return _this;
  97001. }
  97002. return VRDistortionCorrectionPostProcess;
  97003. }(BABYLON.PostProcess));
  97004. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  97005. })(BABYLON || (BABYLON = {}));
  97006. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  97007. var BABYLON;
  97008. (function (BABYLON) {
  97009. /**
  97010. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  97011. * Screen rotation is taken into account.
  97012. */
  97013. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  97014. function FreeCameraDeviceOrientationInput() {
  97015. var _this = this;
  97016. this._screenOrientationAngle = 0;
  97017. this._screenQuaternion = new BABYLON.Quaternion();
  97018. this._alpha = 0;
  97019. this._beta = 0;
  97020. this._gamma = 0;
  97021. this._orientationChanged = function () {
  97022. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  97023. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  97024. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  97025. };
  97026. this._deviceOrientation = function (evt) {
  97027. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  97028. _this._beta = evt.beta !== null ? evt.beta : 0;
  97029. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  97030. };
  97031. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  97032. this._orientationChanged();
  97033. }
  97034. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  97035. get: function () {
  97036. return this._camera;
  97037. },
  97038. set: function (camera) {
  97039. this._camera = camera;
  97040. if (this._camera != null && !this._camera.rotationQuaternion) {
  97041. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  97042. }
  97043. },
  97044. enumerable: true,
  97045. configurable: true
  97046. });
  97047. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  97048. window.addEventListener("orientationchange", this._orientationChanged);
  97049. window.addEventListener("deviceorientation", this._deviceOrientation);
  97050. //In certain cases, the attach control is called AFTER orientation was changed,
  97051. //So this is needed.
  97052. this._orientationChanged();
  97053. };
  97054. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  97055. window.removeEventListener("orientationchange", this._orientationChanged);
  97056. window.removeEventListener("deviceorientation", this._deviceOrientation);
  97057. };
  97058. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  97059. //if no device orientation provided, don't update the rotation.
  97060. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  97061. if (!this._alpha)
  97062. return;
  97063. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  97064. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  97065. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  97066. //Mirror on XY Plane
  97067. this._camera.rotationQuaternion.z *= -1;
  97068. this._camera.rotationQuaternion.w *= -1;
  97069. };
  97070. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  97071. return "FreeCameraDeviceOrientationInput";
  97072. };
  97073. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  97074. return "deviceOrientation";
  97075. };
  97076. return FreeCameraDeviceOrientationInput;
  97077. }());
  97078. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  97079. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  97080. })(BABYLON || (BABYLON = {}));
  97081. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  97082. var BABYLON;
  97083. (function (BABYLON) {
  97084. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  97085. function ArcRotateCameraVRDeviceOrientationInput() {
  97086. this.alphaCorrection = 1;
  97087. this.betaCorrection = 1;
  97088. this.gammaCorrection = 1;
  97089. this._alpha = 0;
  97090. this._gamma = 0;
  97091. this._dirty = false;
  97092. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  97093. }
  97094. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  97095. this.camera.attachControl(element, noPreventDefault);
  97096. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  97097. };
  97098. /** @hidden */
  97099. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  97100. if (evt.alpha !== null) {
  97101. this._alpha = +evt.alpha | 0;
  97102. }
  97103. if (evt.gamma !== null) {
  97104. this._gamma = +evt.gamma | 0;
  97105. }
  97106. this._dirty = true;
  97107. };
  97108. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  97109. if (this._dirty) {
  97110. this._dirty = false;
  97111. if (this._gamma < 0) {
  97112. this._gamma = 180 + this._gamma;
  97113. }
  97114. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  97115. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  97116. }
  97117. };
  97118. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  97119. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  97120. };
  97121. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  97122. return "ArcRotateCameraVRDeviceOrientationInput";
  97123. };
  97124. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  97125. return "VRDeviceOrientation";
  97126. };
  97127. return ArcRotateCameraVRDeviceOrientationInput;
  97128. }());
  97129. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  97130. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  97131. })(BABYLON || (BABYLON = {}));
  97132. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  97133. var BABYLON;
  97134. (function (BABYLON) {
  97135. var VRCameraMetrics = /** @class */ (function () {
  97136. function VRCameraMetrics() {
  97137. this.compensateDistortion = true;
  97138. }
  97139. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  97140. get: function () {
  97141. return this.hResolution / (2 * this.vResolution);
  97142. },
  97143. enumerable: true,
  97144. configurable: true
  97145. });
  97146. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  97147. get: function () {
  97148. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  97149. },
  97150. enumerable: true,
  97151. configurable: true
  97152. });
  97153. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  97154. get: function () {
  97155. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  97156. var h = (4 * meters) / this.hScreenSize;
  97157. return BABYLON.Matrix.Translation(h, 0, 0);
  97158. },
  97159. enumerable: true,
  97160. configurable: true
  97161. });
  97162. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  97163. get: function () {
  97164. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  97165. var h = (4 * meters) / this.hScreenSize;
  97166. return BABYLON.Matrix.Translation(-h, 0, 0);
  97167. },
  97168. enumerable: true,
  97169. configurable: true
  97170. });
  97171. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  97172. get: function () {
  97173. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  97174. },
  97175. enumerable: true,
  97176. configurable: true
  97177. });
  97178. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  97179. get: function () {
  97180. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  97181. },
  97182. enumerable: true,
  97183. configurable: true
  97184. });
  97185. VRCameraMetrics.GetDefault = function () {
  97186. var result = new VRCameraMetrics();
  97187. result.hResolution = 1280;
  97188. result.vResolution = 800;
  97189. result.hScreenSize = 0.149759993;
  97190. result.vScreenSize = 0.0935999975;
  97191. result.vScreenCenter = 0.0467999987;
  97192. result.eyeToScreenDistance = 0.0410000011;
  97193. result.lensSeparationDistance = 0.0635000020;
  97194. result.interpupillaryDistance = 0.0640000030;
  97195. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  97196. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  97197. result.postProcessScaleFactor = 1.714605507808412;
  97198. result.lensCenterOffset = 0.151976421;
  97199. return result;
  97200. };
  97201. return VRCameraMetrics;
  97202. }());
  97203. BABYLON.VRCameraMetrics = VRCameraMetrics;
  97204. })(BABYLON || (BABYLON = {}));
  97205. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  97206. var BABYLON;
  97207. (function (BABYLON) {
  97208. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  97209. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97210. });
  97211. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  97212. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97213. });
  97214. /**
  97215. * This represents a WebVR camera.
  97216. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  97217. * @example http://doc.babylonjs.com/how_to/webvr_camera
  97218. */
  97219. var WebVRFreeCamera = /** @class */ (function (_super) {
  97220. __extends(WebVRFreeCamera, _super);
  97221. /**
  97222. * Instantiates a WebVRFreeCamera.
  97223. * @param name The name of the WebVRFreeCamera
  97224. * @param position The starting anchor position for the camera
  97225. * @param scene The scene the camera belongs to
  97226. * @param webVROptions a set of customizable options for the webVRCamera
  97227. */
  97228. function WebVRFreeCamera(name, position, scene, webVROptions) {
  97229. if (webVROptions === void 0) { webVROptions = {}; }
  97230. var _this = _super.call(this, name, position, scene) || this;
  97231. _this.webVROptions = webVROptions;
  97232. /**
  97233. * @hidden
  97234. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  97235. */
  97236. _this._vrDevice = null;
  97237. /**
  97238. * The rawPose of the vrDevice.
  97239. */
  97240. _this.rawPose = null;
  97241. _this._specsVersion = "1.1";
  97242. _this._attached = false;
  97243. _this._descendants = [];
  97244. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  97245. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  97246. /** @hidden */
  97247. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  97248. _this._standingMatrix = null;
  97249. /**
  97250. * Represents device position in babylon space.
  97251. */
  97252. _this.devicePosition = BABYLON.Vector3.Zero();
  97253. /**
  97254. * Represents device rotation in babylon space.
  97255. */
  97256. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  97257. /**
  97258. * The scale of the device to be used when translating from device space to babylon space.
  97259. */
  97260. _this.deviceScaleFactor = 1;
  97261. _this._deviceToWorld = BABYLON.Matrix.Identity();
  97262. _this._worldToDevice = BABYLON.Matrix.Identity();
  97263. /**
  97264. * References to the webVR controllers for the vrDevice.
  97265. */
  97266. _this.controllers = [];
  97267. /**
  97268. * Emits an event when a controller is attached.
  97269. */
  97270. _this.onControllersAttachedObservable = new BABYLON.Observable();
  97271. /**
  97272. * Emits an event when a controller's mesh has been loaded;
  97273. */
  97274. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97275. /**
  97276. * Emits an event when the HMD's pose has been updated.
  97277. */
  97278. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  97279. _this._poseSet = false;
  97280. /**
  97281. * If the rig cameras be used as parent instead of this camera.
  97282. */
  97283. _this.rigParenting = true;
  97284. _this._defaultHeight = undefined;
  97285. _this._htmlElementAttached = null;
  97286. _this._detachIfAttached = function () {
  97287. var vrDisplay = _this.getEngine().getVRDevice();
  97288. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  97289. _this.detachControl(_this._htmlElementAttached);
  97290. }
  97291. };
  97292. _this._workingVector = BABYLON.Vector3.Zero();
  97293. _this._oneVector = BABYLON.Vector3.One();
  97294. _this._workingMatrix = BABYLON.Matrix.Identity();
  97295. _this._tmpMatrix = new BABYLON.Matrix();
  97296. _this._cache.position = BABYLON.Vector3.Zero();
  97297. if (webVROptions.defaultHeight) {
  97298. _this._defaultHeight = webVROptions.defaultHeight;
  97299. _this.position.y = _this._defaultHeight;
  97300. }
  97301. _this.minZ = 0.1;
  97302. //legacy support - the compensation boolean was removed.
  97303. if (arguments.length === 5) {
  97304. _this.webVROptions = arguments[4];
  97305. }
  97306. // default webVR options
  97307. if (_this.webVROptions.trackPosition == undefined) {
  97308. _this.webVROptions.trackPosition = true;
  97309. }
  97310. if (_this.webVROptions.controllerMeshes == undefined) {
  97311. _this.webVROptions.controllerMeshes = true;
  97312. }
  97313. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  97314. _this.webVROptions.defaultLightingOnControllers = true;
  97315. }
  97316. _this.rotationQuaternion = new BABYLON.Quaternion();
  97317. if (_this.webVROptions && _this.webVROptions.positionScale) {
  97318. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  97319. }
  97320. //enable VR
  97321. var engine = _this.getEngine();
  97322. _this._onVREnabled = function (success) { if (success) {
  97323. _this.initControllers();
  97324. } };
  97325. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  97326. engine.initWebVR().add(function (event) {
  97327. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  97328. return;
  97329. }
  97330. _this._vrDevice = event.vrDisplay;
  97331. //reset the rig parameters.
  97332. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  97333. if (_this._attached) {
  97334. _this.getEngine().enableVR();
  97335. }
  97336. });
  97337. if (typeof (VRFrameData) !== "undefined")
  97338. _this._frameData = new VRFrameData();
  97339. /**
  97340. * The idea behind the following lines:
  97341. * objects that have the camera as parent should actually have the rig cameras as a parent.
  97342. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  97343. * the second will not show it correctly.
  97344. *
  97345. * To solve this - each object that has the camera as parent will be added to a protected array.
  97346. * When the rig camera renders, it will take this array and set all of those to be its children.
  97347. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  97348. * Amazing!
  97349. */
  97350. scene.onBeforeCameraRenderObservable.add(function (camera) {
  97351. if (camera.parent === _this && _this.rigParenting) {
  97352. _this._descendants = _this.getDescendants(true, function (n) {
  97353. // don't take the cameras or the controllers!
  97354. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  97355. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  97356. return !isController && !isRigCamera;
  97357. });
  97358. _this._descendants.forEach(function (node) {
  97359. node.parent = camera;
  97360. });
  97361. }
  97362. });
  97363. scene.onAfterCameraRenderObservable.add(function (camera) {
  97364. if (camera.parent === _this && _this.rigParenting) {
  97365. _this._descendants.forEach(function (node) {
  97366. node.parent = _this;
  97367. });
  97368. }
  97369. });
  97370. return _this;
  97371. }
  97372. /**
  97373. * Gets the device distance from the ground in meters.
  97374. * @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.
  97375. */
  97376. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  97377. if (this._standingMatrix) {
  97378. // Add standing matrix offset to get real offset from ground in room
  97379. this._standingMatrix.getTranslationToRef(this._workingVector);
  97380. return this._deviceRoomPosition.y + this._workingVector.y;
  97381. }
  97382. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  97383. return this._defaultHeight || 0;
  97384. };
  97385. /**
  97386. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97387. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  97388. */
  97389. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  97390. var _this = this;
  97391. if (callback === void 0) { callback = function (bool) { }; }
  97392. // Use standing matrix if available
  97393. this.getEngine().initWebVRAsync().then(function (result) {
  97394. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  97395. callback(false);
  97396. }
  97397. else {
  97398. _this._standingMatrix = new BABYLON.Matrix();
  97399. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  97400. if (!_this.getScene().useRightHandedSystem) {
  97401. [2, 6, 8, 9, 14].forEach(function (num) {
  97402. if (_this._standingMatrix) {
  97403. _this._standingMatrix.m[num] *= -1;
  97404. }
  97405. });
  97406. }
  97407. callback(true);
  97408. }
  97409. });
  97410. };
  97411. /**
  97412. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97413. * @returns A promise with a boolean set to if the standing matrix is supported.
  97414. */
  97415. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  97416. var _this = this;
  97417. return new Promise(function (res, rej) {
  97418. _this.useStandingMatrix(function (supported) {
  97419. res(supported);
  97420. });
  97421. });
  97422. };
  97423. /**
  97424. * Disposes the camera
  97425. */
  97426. WebVRFreeCamera.prototype.dispose = function () {
  97427. this._detachIfAttached();
  97428. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  97429. _super.prototype.dispose.call(this);
  97430. };
  97431. /**
  97432. * Gets a vrController by name.
  97433. * @param name The name of the controller to retreive
  97434. * @returns the controller matching the name specified or null if not found
  97435. */
  97436. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  97437. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  97438. var gp = _a[_i];
  97439. if (gp.hand === name) {
  97440. return gp;
  97441. }
  97442. }
  97443. return null;
  97444. };
  97445. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  97446. /**
  97447. * The controller corrisponding to the users left hand.
  97448. */
  97449. get: function () {
  97450. if (!this._leftController) {
  97451. this._leftController = this.getControllerByName("left");
  97452. }
  97453. return this._leftController;
  97454. },
  97455. enumerable: true,
  97456. configurable: true
  97457. });
  97458. ;
  97459. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  97460. /**
  97461. * The controller corrisponding to the users right hand.
  97462. */
  97463. get: function () {
  97464. if (!this._rightController) {
  97465. this._rightController = this.getControllerByName("right");
  97466. }
  97467. return this._rightController;
  97468. },
  97469. enumerable: true,
  97470. configurable: true
  97471. });
  97472. ;
  97473. /**
  97474. * Casts a ray forward from the vrCamera's gaze.
  97475. * @param length Length of the ray (default: 100)
  97476. * @returns the ray corrisponding to the gaze
  97477. */
  97478. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  97479. if (length === void 0) { length = 100; }
  97480. if (this.leftCamera) {
  97481. // Use left eye to avoid computation to compute center on every call
  97482. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  97483. }
  97484. else {
  97485. return _super.prototype.getForwardRay.call(this, length);
  97486. }
  97487. };
  97488. /**
  97489. * @hidden
  97490. * Updates the camera based on device's frame data
  97491. */
  97492. WebVRFreeCamera.prototype._checkInputs = function () {
  97493. if (this._vrDevice && this._vrDevice.isPresenting) {
  97494. this._vrDevice.getFrameData(this._frameData);
  97495. this.updateFromDevice(this._frameData.pose);
  97496. }
  97497. _super.prototype._checkInputs.call(this);
  97498. };
  97499. /**
  97500. * Updates the poseControlled values based on the input device pose.
  97501. * @param poseData Pose coming from the device
  97502. */
  97503. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  97504. if (poseData && poseData.orientation) {
  97505. this.rawPose = poseData;
  97506. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  97507. if (this.getScene().useRightHandedSystem) {
  97508. this._deviceRoomRotationQuaternion.z *= -1;
  97509. this._deviceRoomRotationQuaternion.w *= -1;
  97510. }
  97511. if (this.webVROptions.trackPosition && this.rawPose.position) {
  97512. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  97513. if (this.getScene().useRightHandedSystem) {
  97514. this._deviceRoomPosition.z *= -1;
  97515. }
  97516. }
  97517. this._poseSet = true;
  97518. }
  97519. };
  97520. /**
  97521. * WebVR's attach control will start broadcasting frames to the device.
  97522. * Note that in certain browsers (chrome for example) this function must be called
  97523. * within a user-interaction callback. Example:
  97524. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  97525. *
  97526. * @param element html element to attach the vrDevice to
  97527. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  97528. */
  97529. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  97530. _super.prototype.attachControl.call(this, element, noPreventDefault);
  97531. this._attached = true;
  97532. this._htmlElementAttached = element;
  97533. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  97534. if (this._vrDevice) {
  97535. this.getEngine().enableVR();
  97536. }
  97537. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97538. };
  97539. /**
  97540. * Detaches the camera from the html element and disables VR
  97541. *
  97542. * @param element html element to detach from
  97543. */
  97544. WebVRFreeCamera.prototype.detachControl = function (element) {
  97545. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  97546. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  97547. _super.prototype.detachControl.call(this, element);
  97548. this._attached = false;
  97549. this.getEngine().disableVR();
  97550. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97551. };
  97552. /**
  97553. * @returns the name of this class
  97554. */
  97555. WebVRFreeCamera.prototype.getClassName = function () {
  97556. return "WebVRFreeCamera";
  97557. };
  97558. /**
  97559. * Calls resetPose on the vrDisplay
  97560. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  97561. */
  97562. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  97563. //uses the vrDisplay's "resetPose()".
  97564. //pitch and roll won't be affected.
  97565. this._vrDevice.resetPose();
  97566. };
  97567. /**
  97568. * @hidden
  97569. * Updates the rig cameras (left and right eye)
  97570. */
  97571. WebVRFreeCamera.prototype._updateRigCameras = function () {
  97572. var camLeft = this._rigCameras[0];
  97573. var camRight = this._rigCameras[1];
  97574. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97575. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97576. camLeft.position.copyFrom(this._deviceRoomPosition);
  97577. camRight.position.copyFrom(this._deviceRoomPosition);
  97578. };
  97579. // Remove translation from 6dof headset if trackposition is set to false
  97580. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  97581. if (isViewMatrix === void 0) { isViewMatrix = false; }
  97582. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  97583. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  97584. if (!isViewMatrix) {
  97585. this._tmpMatrix.invert();
  97586. }
  97587. this._tmpMatrix.multiplyToRef(matrix, matrix);
  97588. }
  97589. };
  97590. /**
  97591. * @hidden
  97592. * Updates the cached values of the camera
  97593. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  97594. */
  97595. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  97596. var _this = this;
  97597. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  97598. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  97599. if (!this.updateCacheCalled) {
  97600. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  97601. this.updateCacheCalled = true;
  97602. this.update();
  97603. }
  97604. // Set working vector to the device position in room space rotated by the new rotation
  97605. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  97606. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  97607. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  97608. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  97609. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  97610. // Add translation from anchor position
  97611. this._deviceToWorld.getTranslationToRef(this._workingVector);
  97612. this._workingVector.addInPlace(this.position);
  97613. this._workingVector.subtractInPlace(this._cache.position);
  97614. this._deviceToWorld.setTranslation(this._workingVector);
  97615. // Set an inverted matrix to be used when updating the camera
  97616. this._deviceToWorld.invertToRef(this._worldToDevice);
  97617. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  97618. this.controllers.forEach(function (controller) {
  97619. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  97620. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  97621. controller.update();
  97622. });
  97623. }
  97624. if (!ignoreParentClass) {
  97625. _super.prototype._updateCache.call(this);
  97626. }
  97627. this.updateCacheCalled = false;
  97628. };
  97629. /**
  97630. * Updates the current device position and rotation in the babylon world
  97631. */
  97632. WebVRFreeCamera.prototype.update = function () {
  97633. // Get current device position in babylon world
  97634. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  97635. // Get current device rotation in babylon world
  97636. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  97637. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  97638. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  97639. if (this._poseSet) {
  97640. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  97641. }
  97642. _super.prototype.update.call(this);
  97643. };
  97644. /**
  97645. * @hidden
  97646. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  97647. * @returns an identity matrix
  97648. */
  97649. WebVRFreeCamera.prototype._getViewMatrix = function () {
  97650. return BABYLON.Matrix.Identity();
  97651. };
  97652. /**
  97653. * This function is called by the two RIG cameras.
  97654. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  97655. */
  97656. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  97657. var _this = this;
  97658. // Update the parent camera prior to using a child camera to avoid desynchronization
  97659. var parentCamera = this._cameraRigParams["parentCamera"];
  97660. parentCamera._updateCache();
  97661. //WebVR 1.1
  97662. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  97663. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  97664. if (!this.getScene().useRightHandedSystem) {
  97665. [2, 6, 8, 9, 14].forEach(function (num) {
  97666. _this._webvrViewMatrix.m[num] *= -1;
  97667. });
  97668. }
  97669. // update the camera rotation matrix
  97670. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  97671. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  97672. // Computing target and final matrix
  97673. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  97674. // should the view matrix be updated with scale and position offset?
  97675. if (parentCamera.deviceScaleFactor !== 1) {
  97676. this._webvrViewMatrix.invert();
  97677. // scale the position, if set
  97678. if (parentCamera.deviceScaleFactor) {
  97679. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  97680. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  97681. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  97682. }
  97683. this._webvrViewMatrix.invert();
  97684. }
  97685. // Remove translation from 6dof headset if trackposition is set to false
  97686. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  97687. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  97688. // Compute global position
  97689. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  97690. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  97691. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  97692. this._workingMatrix.getTranslationToRef(this._globalPosition);
  97693. this._markSyncedWithParent();
  97694. return this._webvrViewMatrix;
  97695. };
  97696. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  97697. var _this = this;
  97698. var parentCamera = this.parent;
  97699. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  97700. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  97701. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  97702. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  97703. //babylon compatible matrix
  97704. if (!this.getScene().useRightHandedSystem) {
  97705. [8, 9, 10, 11].forEach(function (num) {
  97706. _this._projectionMatrix.m[num] *= -1;
  97707. });
  97708. }
  97709. return this._projectionMatrix;
  97710. };
  97711. /**
  97712. * Initializes the controllers and their meshes
  97713. */
  97714. WebVRFreeCamera.prototype.initControllers = function () {
  97715. var _this = this;
  97716. this.controllers = [];
  97717. var manager = this.getScene().gamepadManager;
  97718. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  97719. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97720. var webVrController = gamepad;
  97721. if (webVrController.defaultModel) {
  97722. webVrController.defaultModel.setEnabled(false);
  97723. }
  97724. if (webVrController.hand === "right") {
  97725. _this._rightController = null;
  97726. }
  97727. if (webVrController.hand === "left") {
  97728. _this._leftController = null;
  97729. }
  97730. var controllerIndex = _this.controllers.indexOf(webVrController);
  97731. if (controllerIndex !== -1) {
  97732. _this.controllers.splice(controllerIndex, 1);
  97733. }
  97734. }
  97735. });
  97736. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  97737. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97738. var webVrController_1 = gamepad;
  97739. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  97740. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  97741. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  97742. if (_this.webVROptions.controllerMeshes) {
  97743. if (webVrController_1.defaultModel) {
  97744. webVrController_1.defaultModel.setEnabled(true);
  97745. }
  97746. else {
  97747. // Load the meshes
  97748. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  97749. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  97750. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  97751. if (_this.webVROptions.defaultLightingOnControllers) {
  97752. if (!_this._lightOnControllers) {
  97753. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  97754. }
  97755. var activateLightOnSubMeshes_1 = function (mesh, light) {
  97756. var children = mesh.getChildren();
  97757. if (children && children.length !== 0) {
  97758. children.forEach(function (mesh) {
  97759. light.includedOnlyMeshes.push(mesh);
  97760. activateLightOnSubMeshes_1(mesh, light);
  97761. });
  97762. }
  97763. };
  97764. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  97765. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  97766. }
  97767. });
  97768. }
  97769. }
  97770. webVrController_1.attachToPoseControlledCamera(_this);
  97771. // since this is async - sanity check. Is the controller already stored?
  97772. if (_this.controllers.indexOf(webVrController_1) === -1) {
  97773. //add to the controllers array
  97774. _this.controllers.push(webVrController_1);
  97775. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  97776. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  97777. // So we're overriding setting left & right manually to be sure
  97778. var firstViveWandDetected = false;
  97779. for (var i = 0; i < _this.controllers.length; i++) {
  97780. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97781. if (!firstViveWandDetected) {
  97782. firstViveWandDetected = true;
  97783. _this.controllers[i].hand = "left";
  97784. }
  97785. else {
  97786. _this.controllers[i].hand = "right";
  97787. }
  97788. }
  97789. }
  97790. //did we find enough controllers? Great! let the developer know.
  97791. if (_this.controllers.length >= 2) {
  97792. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97793. }
  97794. }
  97795. }
  97796. });
  97797. };
  97798. return WebVRFreeCamera;
  97799. }(BABYLON.FreeCamera));
  97800. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97801. })(BABYLON || (BABYLON = {}));
  97802. //# sourceMappingURL=babylon.webVRCamera.js.map
  97803. var BABYLON;
  97804. (function (BABYLON) {
  97805. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97806. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97807. });
  97808. // We're mainly based on the logic defined into the FreeCamera code
  97809. /**
  97810. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97811. * being tilted forward or back and left or right.
  97812. */
  97813. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97814. __extends(DeviceOrientationCamera, _super);
  97815. /**
  97816. * Creates a new device orientation camera
  97817. * @param name The name of the camera
  97818. * @param position The start position camera
  97819. * @param scene The scene the camera belongs to
  97820. */
  97821. function DeviceOrientationCamera(name, position, scene) {
  97822. var _this = _super.call(this, name, position, scene) || this;
  97823. _this._quaternionCache = new BABYLON.Quaternion();
  97824. _this.inputs.addDeviceOrientation();
  97825. return _this;
  97826. }
  97827. /**
  97828. * Gets the current instance class name ("DeviceOrientationCamera").
  97829. * This helps avoiding instanceof at run time.
  97830. * @returns the class name
  97831. */
  97832. DeviceOrientationCamera.prototype.getClassName = function () {
  97833. return "DeviceOrientationCamera";
  97834. };
  97835. /**
  97836. * @hidden
  97837. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97838. */
  97839. DeviceOrientationCamera.prototype._checkInputs = function () {
  97840. _super.prototype._checkInputs.call(this);
  97841. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97842. if (this._initialQuaternion) {
  97843. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97844. }
  97845. };
  97846. /**
  97847. * Reset the camera to its default orientation on the specified axis only.
  97848. * @param axis The axis to reset
  97849. */
  97850. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97851. var _this = this;
  97852. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97853. //can only work if this camera has a rotation quaternion already.
  97854. if (!this.rotationQuaternion)
  97855. return;
  97856. if (!this._initialQuaternion) {
  97857. this._initialQuaternion = new BABYLON.Quaternion();
  97858. }
  97859. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97860. ['x', 'y', 'z'].forEach(function (axisName) {
  97861. if (!axis[axisName]) {
  97862. _this._initialQuaternion[axisName] = 0;
  97863. }
  97864. else {
  97865. _this._initialQuaternion[axisName] *= -1;
  97866. }
  97867. });
  97868. this._initialQuaternion.normalize();
  97869. //force rotation update
  97870. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97871. };
  97872. return DeviceOrientationCamera;
  97873. }(BABYLON.FreeCamera));
  97874. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97875. })(BABYLON || (BABYLON = {}));
  97876. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97877. var BABYLON;
  97878. (function (BABYLON) {
  97879. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97880. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97881. });
  97882. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97883. __extends(VRDeviceOrientationFreeCamera, _super);
  97884. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97885. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97886. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97887. var _this = _super.call(this, name, position, scene) || this;
  97888. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97889. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97890. return _this;
  97891. }
  97892. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97893. return "VRDeviceOrientationFreeCamera";
  97894. };
  97895. return VRDeviceOrientationFreeCamera;
  97896. }(BABYLON.DeviceOrientationCamera));
  97897. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97898. })(BABYLON || (BABYLON = {}));
  97899. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97900. var BABYLON;
  97901. (function (BABYLON) {
  97902. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97903. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97904. });
  97905. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97906. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97907. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97908. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97909. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97910. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97911. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97912. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97913. _this.inputs.addVRDeviceOrientation();
  97914. return _this;
  97915. }
  97916. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97917. return "VRDeviceOrientationArcRotateCamera";
  97918. };
  97919. return VRDeviceOrientationArcRotateCamera;
  97920. }(BABYLON.ArcRotateCamera));
  97921. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97922. })(BABYLON || (BABYLON = {}));
  97923. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97924. var BABYLON;
  97925. (function (BABYLON) {
  97926. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97927. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97928. });
  97929. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97930. __extends(VRDeviceOrientationGamepadCamera, _super);
  97931. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97932. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97933. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97934. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97935. _this.inputs.addGamepad();
  97936. return _this;
  97937. }
  97938. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97939. return "VRDeviceOrientationGamepadCamera";
  97940. };
  97941. return VRDeviceOrientationGamepadCamera;
  97942. }(BABYLON.VRDeviceOrientationFreeCamera));
  97943. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97944. })(BABYLON || (BABYLON = {}));
  97945. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97946. var BABYLON;
  97947. (function (BABYLON) {
  97948. var VRExperienceHelperGazer = /** @class */ (function () {
  97949. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97950. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97951. this.scene = scene;
  97952. /** @hidden */
  97953. this._pointerDownOnMeshAsked = false;
  97954. /** @hidden */
  97955. this._isActionableMesh = false;
  97956. /** @hidden */
  97957. this._teleportationRequestInitiated = false;
  97958. /** @hidden */
  97959. this._teleportationBackRequestInitiated = false;
  97960. /** @hidden */
  97961. this._rotationRightAsked = false;
  97962. /** @hidden */
  97963. this._rotationLeftAsked = false;
  97964. /** @hidden */
  97965. this._dpadPressed = true;
  97966. /** @hidden */
  97967. this._activePointer = false;
  97968. this._id = VRExperienceHelperGazer._idCounter++;
  97969. // Gaze tracker
  97970. if (!gazeTrackerToClone) {
  97971. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97972. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97973. this._gazeTracker.isPickable = false;
  97974. this._gazeTracker.isVisible = false;
  97975. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97976. targetMat.specularColor = BABYLON.Color3.Black();
  97977. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97978. targetMat.backFaceCulling = false;
  97979. this._gazeTracker.material = targetMat;
  97980. }
  97981. else {
  97982. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97983. }
  97984. }
  97985. /** @hidden */
  97986. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97987. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97988. };
  97989. /** @hidden */
  97990. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97991. this._pointerDownOnMeshAsked = true;
  97992. if (this._currentHit) {
  97993. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97994. }
  97995. };
  97996. /** @hidden */
  97997. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97998. if (this._currentHit) {
  97999. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  98000. }
  98001. this._pointerDownOnMeshAsked = false;
  98002. };
  98003. /** @hidden */
  98004. VRExperienceHelperGazer.prototype._activatePointer = function () {
  98005. this._activePointer = true;
  98006. };
  98007. /** @hidden */
  98008. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  98009. this._activePointer = false;
  98010. };
  98011. /** @hidden */
  98012. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  98013. if (distance === void 0) { distance = 100; }
  98014. };
  98015. VRExperienceHelperGazer.prototype.dispose = function () {
  98016. this._interactionsEnabled = false;
  98017. this._teleportationEnabled = false;
  98018. if (this._gazeTracker) {
  98019. this._gazeTracker.dispose();
  98020. }
  98021. };
  98022. VRExperienceHelperGazer._idCounter = 0;
  98023. return VRExperienceHelperGazer;
  98024. }());
  98025. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  98026. __extends(VRExperienceHelperControllerGazer, _super);
  98027. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  98028. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  98029. _this.webVRController = webVRController;
  98030. // Laser pointer
  98031. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  98032. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  98033. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  98034. laserPointerMaterial.alpha = 0.6;
  98035. _this._laserPointer.material = laserPointerMaterial;
  98036. _this._laserPointer.rotation.x = Math.PI / 2;
  98037. _this._laserPointer.position.z = -0.5;
  98038. _this._laserPointer.isVisible = false;
  98039. _this._laserPointer.isPickable = false;
  98040. if (!webVRController.mesh) {
  98041. // Create an empty mesh that is used prior to loading the high quality model
  98042. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  98043. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  98044. preloadPointerPose.rotation.x = -0.7;
  98045. preloadMesh.addChild(preloadPointerPose);
  98046. webVRController.attachToMesh(preloadMesh);
  98047. }
  98048. _this._setLaserPointerParent(webVRController.mesh);
  98049. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  98050. _this._setLaserPointerParent(mesh);
  98051. });
  98052. return _this;
  98053. }
  98054. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  98055. return this.webVRController.getForwardRay(length);
  98056. };
  98057. /** @hidden */
  98058. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  98059. _super.prototype._activatePointer.call(this);
  98060. this._laserPointer.isVisible = true;
  98061. };
  98062. /** @hidden */
  98063. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  98064. _super.prototype._deactivatePointer.call(this);
  98065. this._laserPointer.isVisible = false;
  98066. };
  98067. /** @hidden */
  98068. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  98069. this._laserPointer.material.emissiveColor = color;
  98070. };
  98071. /** @hidden */
  98072. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  98073. var makeNotPick = function (root) {
  98074. root.isPickable = false;
  98075. root.getChildMeshes().forEach(function (c) {
  98076. makeNotPick(c);
  98077. });
  98078. };
  98079. makeNotPick(mesh);
  98080. var childMeshes = mesh.getChildMeshes();
  98081. this.webVRController._pointingPoseNode = null;
  98082. for (var i = 0; i < childMeshes.length; i++) {
  98083. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  98084. mesh = childMeshes[i];
  98085. this.webVRController._pointingPoseNode = mesh;
  98086. break;
  98087. }
  98088. }
  98089. this._laserPointer.parent = mesh;
  98090. };
  98091. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  98092. if (distance === void 0) { distance = 100; }
  98093. this._laserPointer.scaling.y = distance;
  98094. this._laserPointer.position.z = -distance / 2;
  98095. };
  98096. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  98097. _super.prototype.dispose.call(this);
  98098. this._laserPointer.dispose();
  98099. if (this._meshAttachedObserver) {
  98100. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  98101. }
  98102. };
  98103. return VRExperienceHelperControllerGazer;
  98104. }(VRExperienceHelperGazer));
  98105. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  98106. __extends(VRExperienceHelperCameraGazer, _super);
  98107. function VRExperienceHelperCameraGazer(getCamera, scene) {
  98108. var _this = _super.call(this, scene) || this;
  98109. _this.getCamera = getCamera;
  98110. return _this;
  98111. }
  98112. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  98113. var camera = this.getCamera();
  98114. if (camera) {
  98115. return camera.getForwardRay(length);
  98116. }
  98117. else {
  98118. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  98119. }
  98120. };
  98121. return VRExperienceHelperCameraGazer;
  98122. }(VRExperienceHelperGazer));
  98123. /**
  98124. * Helps to quickly add VR support to an existing scene.
  98125. * See http://doc.babylonjs.com/how_to/webvr_helper
  98126. */
  98127. var VRExperienceHelper = /** @class */ (function () {
  98128. /**
  98129. * Instantiates a VRExperienceHelper.
  98130. * Helps to quickly add VR support to an existing scene.
  98131. * @param scene The scene the VRExperienceHelper belongs to.
  98132. * @param webVROptions Options to modify the vr experience helper's behavior.
  98133. */
  98134. function VRExperienceHelper(scene,
  98135. /** Options to modify the vr experience helper's behavior. */
  98136. webVROptions) {
  98137. if (webVROptions === void 0) { webVROptions = {}; }
  98138. var _this = this;
  98139. this.webVROptions = webVROptions;
  98140. // Can the system support WebVR, even if a headset isn't plugged in?
  98141. this._webVRsupported = false;
  98142. // If WebVR is supported, is a headset plugged in and are we ready to present?
  98143. this._webVRready = false;
  98144. // Are we waiting for the requestPresent callback to complete?
  98145. this._webVRrequesting = false;
  98146. // Are we presenting to the headset right now? (this is the vrDevice state)
  98147. this._webVRpresenting = false;
  98148. // Are we presenting in the fullscreen fallback?
  98149. this._fullscreenVRpresenting = false;
  98150. /**
  98151. * Observable raised when entering VR.
  98152. */
  98153. this.onEnteringVRObservable = new BABYLON.Observable();
  98154. /**
  98155. * Observable raised when exiting VR.
  98156. */
  98157. this.onExitingVRObservable = new BABYLON.Observable();
  98158. /**
  98159. * Observable raised when controller mesh is loaded.
  98160. */
  98161. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  98162. this._useCustomVRButton = false;
  98163. this._teleportationRequested = false;
  98164. this._teleportActive = false;
  98165. this._floorMeshesCollection = [];
  98166. this._rotationAllowed = true;
  98167. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  98168. this._isDefaultTeleportationTarget = true;
  98169. this._teleportationFillColor = "#444444";
  98170. this._teleportationBorderColor = "#FFFFFF";
  98171. this._rotationAngle = 0;
  98172. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  98173. this._padSensibilityUp = 0.65;
  98174. this._padSensibilityDown = 0.35;
  98175. this._leftController = null;
  98176. this._rightController = null;
  98177. /**
  98178. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  98179. */
  98180. this.onNewMeshSelected = new BABYLON.Observable();
  98181. /**
  98182. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  98183. */
  98184. this.onNewMeshPicked = new BABYLON.Observable();
  98185. /**
  98186. * Observable raised before camera teleportation
  98187. */
  98188. this.onBeforeCameraTeleport = new BABYLON.Observable();
  98189. /**
  98190. * Observable raised after camera teleportation
  98191. */
  98192. this.onAfterCameraTeleport = new BABYLON.Observable();
  98193. /**
  98194. * Observable raised when current selected mesh gets unselected
  98195. */
  98196. this.onSelectedMeshUnselected = new BABYLON.Observable();
  98197. /**
  98198. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  98199. */
  98200. this.teleportationEnabled = true;
  98201. this._teleportationInitialized = false;
  98202. this._interactionsEnabled = false;
  98203. this._interactionsRequested = false;
  98204. this._displayGaze = true;
  98205. this._displayLaserPointer = true;
  98206. /**
  98207. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  98208. */
  98209. this.updateGazeTrackerScale = true;
  98210. this._onResize = function () {
  98211. _this.moveButtonToBottomRight();
  98212. if (_this._fullscreenVRpresenting && _this._webVRready) {
  98213. _this.exitVR();
  98214. }
  98215. };
  98216. this._onFullscreenChange = function () {
  98217. if (document.fullscreen !== undefined) {
  98218. _this._fullscreenVRpresenting = document.fullscreen;
  98219. }
  98220. else if (document.mozFullScreen !== undefined) {
  98221. _this._fullscreenVRpresenting = document.mozFullScreen;
  98222. }
  98223. else if (document.webkitIsFullScreen !== undefined) {
  98224. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  98225. }
  98226. else if (document.msIsFullScreen !== undefined) {
  98227. _this._fullscreenVRpresenting = document.msIsFullScreen;
  98228. }
  98229. else if (document.msFullscreenElement !== undefined) {
  98230. _this._fullscreenVRpresenting = document.msFullscreenElement;
  98231. }
  98232. if (!_this._fullscreenVRpresenting && _this._canvas) {
  98233. _this.exitVR();
  98234. if (!_this._useCustomVRButton) {
  98235. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  98236. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  98237. }
  98238. }
  98239. };
  98240. this.beforeRender = function () {
  98241. if (_this._leftController && _this._leftController._activePointer) {
  98242. _this._castRayAndSelectObject(_this._leftController);
  98243. }
  98244. if (_this._rightController && _this._rightController._activePointer) {
  98245. _this._castRayAndSelectObject(_this._rightController);
  98246. }
  98247. if (_this._noControllerIsActive) {
  98248. _this._castRayAndSelectObject(_this._cameraGazer);
  98249. }
  98250. else {
  98251. _this._cameraGazer._gazeTracker.isVisible = false;
  98252. }
  98253. };
  98254. this._onNewGamepadConnected = function (gamepad) {
  98255. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  98256. if (gamepad.leftStick) {
  98257. gamepad.onleftstickchanged(function (stickValues) {
  98258. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  98259. // Listening to classic/xbox gamepad only if no VR controller is active
  98260. if ((!_this._leftController && !_this._rightController) ||
  98261. ((_this._leftController && !_this._leftController._activePointer) &&
  98262. (_this._rightController && !_this._rightController._activePointer))) {
  98263. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  98264. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  98265. }
  98266. }
  98267. });
  98268. }
  98269. if (gamepad.rightStick) {
  98270. gamepad.onrightstickchanged(function (stickValues) {
  98271. if (_this._teleportationInitialized) {
  98272. _this._checkRotate(stickValues, _this._cameraGazer);
  98273. }
  98274. });
  98275. }
  98276. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  98277. gamepad.onbuttondown(function (buttonPressed) {
  98278. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  98279. _this._cameraGazer._selectionPointerDown();
  98280. }
  98281. });
  98282. gamepad.onbuttonup(function (buttonPressed) {
  98283. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  98284. _this._cameraGazer._selectionPointerUp();
  98285. }
  98286. });
  98287. }
  98288. }
  98289. else {
  98290. var webVRController = gamepad;
  98291. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  98292. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  98293. _this._rightController = controller;
  98294. }
  98295. else {
  98296. _this._leftController = controller;
  98297. }
  98298. _this._tryEnableInteractionOnController(controller);
  98299. }
  98300. };
  98301. // 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
  98302. this._tryEnableInteractionOnController = function (controller) {
  98303. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  98304. _this._enableInteractionOnController(controller);
  98305. }
  98306. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  98307. _this._enableTeleportationOnController(controller);
  98308. }
  98309. };
  98310. this._onNewGamepadDisconnected = function (gamepad) {
  98311. if (gamepad instanceof BABYLON.WebVRController) {
  98312. if (gamepad.hand === "left" && _this._leftController != null) {
  98313. _this._leftController.dispose();
  98314. _this._leftController = null;
  98315. }
  98316. if (gamepad.hand === "right" && _this._rightController != null) {
  98317. _this._rightController.dispose();
  98318. _this._rightController = null;
  98319. }
  98320. }
  98321. };
  98322. this._workingVector = BABYLON.Vector3.Zero();
  98323. this._workingQuaternion = BABYLON.Quaternion.Identity();
  98324. this._workingMatrix = BABYLON.Matrix.Identity();
  98325. this._scene = scene;
  98326. this._canvas = scene.getEngine().getRenderingCanvas();
  98327. // Parse options
  98328. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  98329. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  98330. }
  98331. if (webVROptions.createDeviceOrientationCamera === undefined) {
  98332. webVROptions.createDeviceOrientationCamera = true;
  98333. }
  98334. if (webVROptions.laserToggle === undefined) {
  98335. webVROptions.laserToggle = true;
  98336. }
  98337. if (webVROptions.defaultHeight === undefined) {
  98338. webVROptions.defaultHeight = 1.7;
  98339. }
  98340. if (webVROptions.useCustomVRButton) {
  98341. this._useCustomVRButton = true;
  98342. if (webVROptions.customVRButton) {
  98343. this._btnVR = webVROptions.customVRButton;
  98344. }
  98345. }
  98346. if (webVROptions.rayLength) {
  98347. this._rayLength = webVROptions.rayLength;
  98348. }
  98349. this._defaultHeight = webVROptions.defaultHeight;
  98350. if (webVROptions.positionScale) {
  98351. this._rayLength *= webVROptions.positionScale;
  98352. this._defaultHeight *= webVROptions.positionScale;
  98353. }
  98354. this._hasEnteredVR = false;
  98355. // Set position
  98356. if (this._scene.activeCamera) {
  98357. this._position = this._scene.activeCamera.position.clone();
  98358. }
  98359. else {
  98360. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  98361. }
  98362. // Set non-vr camera
  98363. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  98364. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  98365. // Copy data from existing camera
  98366. if (this._scene.activeCamera) {
  98367. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98368. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  98369. // Set rotation from previous camera
  98370. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  98371. var targetCamera = this._scene.activeCamera;
  98372. if (targetCamera.rotationQuaternion) {
  98373. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  98374. }
  98375. else {
  98376. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  98377. }
  98378. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  98379. }
  98380. }
  98381. this._scene.activeCamera = this._deviceOrientationCamera;
  98382. if (this._canvas) {
  98383. this._scene.activeCamera.attachControl(this._canvas);
  98384. }
  98385. }
  98386. else {
  98387. this._existingCamera = this._scene.activeCamera;
  98388. }
  98389. // Create VR cameras
  98390. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98391. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  98392. }
  98393. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  98394. this._webVRCamera.useStandingMatrix();
  98395. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  98396. // Create default button
  98397. if (!this._useCustomVRButton) {
  98398. this._btnVR = document.createElement("BUTTON");
  98399. this._btnVR.className = "babylonVRicon";
  98400. this._btnVR.id = "babylonVRiconbtn";
  98401. this._btnVR.title = "Click to switch to VR";
  98402. 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) }";
  98403. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  98404. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  98405. // css += ".babylonVRicon.vrdisplaysupported { }";
  98406. // css += ".babylonVRicon.vrdisplayready { }";
  98407. // css += ".babylonVRicon.vrdisplayrequesting { }";
  98408. var style = document.createElement('style');
  98409. style.appendChild(document.createTextNode(css));
  98410. document.getElementsByTagName('head')[0].appendChild(style);
  98411. this.moveButtonToBottomRight();
  98412. }
  98413. // VR button click event
  98414. if (this._btnVR) {
  98415. this._btnVR.addEventListener("click", function () {
  98416. if (!_this.isInVRMode) {
  98417. _this.enterVR();
  98418. }
  98419. else {
  98420. _this.exitVR();
  98421. }
  98422. });
  98423. }
  98424. // Window events
  98425. window.addEventListener("resize", this._onResize);
  98426. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  98427. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  98428. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  98429. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  98430. document.onmsfullscreenchange = this._onFullscreenChange;
  98431. // Display vr button when headset is connected
  98432. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98433. this.displayVRButton();
  98434. }
  98435. else {
  98436. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  98437. if (e.vrDisplay) {
  98438. _this.displayVRButton();
  98439. }
  98440. });
  98441. }
  98442. // Exiting VR mode using 'ESC' key on desktop
  98443. this._onKeyDown = function (event) {
  98444. if (event.keyCode === 27 && _this.isInVRMode) {
  98445. _this.exitVR();
  98446. }
  98447. };
  98448. document.addEventListener("keydown", this._onKeyDown);
  98449. // Exiting VR mode double tapping the touch screen
  98450. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  98451. if (_this.isInVRMode) {
  98452. _this.exitVR();
  98453. if (_this._fullscreenVRpresenting) {
  98454. _this._scene.getEngine().switchFullscreen(true);
  98455. }
  98456. }
  98457. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  98458. // Listen for WebVR display changes
  98459. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  98460. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  98461. this._onVRRequestPresentStart = function () {
  98462. _this._webVRrequesting = true;
  98463. _this.updateButtonVisibility();
  98464. };
  98465. this._onVRRequestPresentComplete = function (success) {
  98466. _this._webVRrequesting = false;
  98467. _this.updateButtonVisibility();
  98468. };
  98469. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  98470. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  98471. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  98472. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98473. scene.onDisposeObservable.add(function () {
  98474. _this.dispose();
  98475. });
  98476. // Gamepad connection events
  98477. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  98478. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  98479. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  98480. this.updateButtonVisibility();
  98481. //create easing functions
  98482. this._circleEase = new BABYLON.CircleEase();
  98483. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98484. if (this.webVROptions.floorMeshes) {
  98485. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  98486. }
  98487. }
  98488. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  98489. /** Return this.onEnteringVRObservable
  98490. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  98491. */
  98492. get: function () {
  98493. return this.onEnteringVRObservable;
  98494. },
  98495. enumerable: true,
  98496. configurable: true
  98497. });
  98498. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  98499. /** Return this.onExitingVRObservable
  98500. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  98501. */
  98502. get: function () {
  98503. return this.onExitingVRObservable;
  98504. },
  98505. enumerable: true,
  98506. configurable: true
  98507. });
  98508. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  98509. /** Return this.onControllerMeshLoadedObservable
  98510. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  98511. */
  98512. get: function () {
  98513. return this.onControllerMeshLoadedObservable;
  98514. },
  98515. enumerable: true,
  98516. configurable: true
  98517. });
  98518. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  98519. /**
  98520. * The mesh used to display where the user is going to teleport.
  98521. */
  98522. get: function () {
  98523. return this._teleportationTarget;
  98524. },
  98525. /**
  98526. * Sets the mesh to be used to display where the user is going to teleport.
  98527. */
  98528. set: function (value) {
  98529. if (value) {
  98530. value.name = "teleportationTarget";
  98531. this._isDefaultTeleportationTarget = false;
  98532. this._teleportationTarget = value;
  98533. }
  98534. },
  98535. enumerable: true,
  98536. configurable: true
  98537. });
  98538. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  98539. /**
  98540. * 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
  98541. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  98542. * See http://doc.babylonjs.com/resources/baking_transformations
  98543. */
  98544. get: function () {
  98545. return this._cameraGazer._gazeTracker;
  98546. },
  98547. set: function (value) {
  98548. if (value) {
  98549. // Dispose of existing meshes
  98550. if (this._cameraGazer._gazeTracker) {
  98551. this._cameraGazer._gazeTracker.dispose();
  98552. }
  98553. if (this._leftController && this._leftController._gazeTracker) {
  98554. this._leftController._gazeTracker.dispose();
  98555. }
  98556. if (this._rightController && this._rightController._gazeTracker) {
  98557. this._rightController._gazeTracker.dispose();
  98558. }
  98559. // Set and create gaze trackers on head and controllers
  98560. this._cameraGazer._gazeTracker = value;
  98561. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  98562. this._cameraGazer._gazeTracker.isPickable = false;
  98563. this._cameraGazer._gazeTracker.isVisible = false;
  98564. this._cameraGazer._gazeTracker.name = "gazeTracker";
  98565. if (this._leftController) {
  98566. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98567. }
  98568. if (this._rightController) {
  98569. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98570. }
  98571. }
  98572. },
  98573. enumerable: true,
  98574. configurable: true
  98575. });
  98576. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  98577. /**
  98578. * The gaze tracking mesh corresponding to the left controller
  98579. */
  98580. get: function () {
  98581. if (this._leftController) {
  98582. return this._leftController._gazeTracker;
  98583. }
  98584. return null;
  98585. },
  98586. enumerable: true,
  98587. configurable: true
  98588. });
  98589. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  98590. /**
  98591. * The gaze tracking mesh corresponding to the right controller
  98592. */
  98593. get: function () {
  98594. if (this._rightController) {
  98595. return this._rightController._gazeTracker;
  98596. }
  98597. return null;
  98598. },
  98599. enumerable: true,
  98600. configurable: true
  98601. });
  98602. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  98603. /**
  98604. * If the ray of the gaze should be displayed.
  98605. */
  98606. get: function () {
  98607. return this._displayGaze;
  98608. },
  98609. /**
  98610. * Sets if the ray of the gaze should be displayed.
  98611. */
  98612. set: function (value) {
  98613. this._displayGaze = value;
  98614. if (!value) {
  98615. this._cameraGazer._gazeTracker.isVisible = false;
  98616. if (this._leftController) {
  98617. this._leftController._gazeTracker.isVisible = false;
  98618. }
  98619. if (this._rightController) {
  98620. this._rightController._gazeTracker.isVisible = false;
  98621. }
  98622. }
  98623. },
  98624. enumerable: true,
  98625. configurable: true
  98626. });
  98627. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  98628. /**
  98629. * If the ray of the LaserPointer should be displayed.
  98630. */
  98631. get: function () {
  98632. return this._displayLaserPointer;
  98633. },
  98634. /**
  98635. * Sets if the ray of the LaserPointer should be displayed.
  98636. */
  98637. set: function (value) {
  98638. this._displayLaserPointer = value;
  98639. if (!value) {
  98640. if (this._rightController) {
  98641. this._rightController._deactivatePointer();
  98642. this._rightController._gazeTracker.isVisible = false;
  98643. }
  98644. if (this._leftController) {
  98645. this._leftController._deactivatePointer();
  98646. this._leftController._gazeTracker.isVisible = false;
  98647. }
  98648. }
  98649. else {
  98650. if (this._rightController) {
  98651. this._rightController._activatePointer();
  98652. }
  98653. if (this._leftController) {
  98654. this._leftController._activatePointer();
  98655. }
  98656. }
  98657. },
  98658. enumerable: true,
  98659. configurable: true
  98660. });
  98661. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  98662. /**
  98663. * The deviceOrientationCamera used as the camera when not in VR.
  98664. */
  98665. get: function () {
  98666. return this._deviceOrientationCamera;
  98667. },
  98668. enumerable: true,
  98669. configurable: true
  98670. });
  98671. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  98672. /**
  98673. * Based on the current WebVR support, returns the current VR camera used.
  98674. */
  98675. get: function () {
  98676. if (this._webVRready) {
  98677. return this._webVRCamera;
  98678. }
  98679. else {
  98680. return this._scene.activeCamera;
  98681. }
  98682. },
  98683. enumerable: true,
  98684. configurable: true
  98685. });
  98686. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  98687. /**
  98688. * The webVRCamera which is used when in VR.
  98689. */
  98690. get: function () {
  98691. return this._webVRCamera;
  98692. },
  98693. enumerable: true,
  98694. configurable: true
  98695. });
  98696. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  98697. /**
  98698. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  98699. */
  98700. get: function () {
  98701. return this._vrDeviceOrientationCamera;
  98702. },
  98703. enumerable: true,
  98704. configurable: true
  98705. });
  98706. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  98707. get: function () {
  98708. var result = this._cameraGazer._teleportationRequestInitiated
  98709. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  98710. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  98711. return result;
  98712. },
  98713. enumerable: true,
  98714. configurable: true
  98715. });
  98716. // Raised when one of the controller has loaded successfully its associated default mesh
  98717. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  98718. if (this._leftController && this._leftController.webVRController == webVRController) {
  98719. if (webVRController.mesh) {
  98720. this._leftController._setLaserPointerParent(webVRController.mesh);
  98721. }
  98722. }
  98723. if (this._rightController && this._rightController.webVRController == webVRController) {
  98724. if (webVRController.mesh) {
  98725. this._rightController._setLaserPointerParent(webVRController.mesh);
  98726. }
  98727. }
  98728. try {
  98729. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  98730. }
  98731. catch (err) {
  98732. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  98733. }
  98734. };
  98735. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  98736. /**
  98737. * Gets a value indicating if we are currently in VR mode.
  98738. */
  98739. get: function () {
  98740. return this._webVRpresenting || this._fullscreenVRpresenting;
  98741. },
  98742. enumerable: true,
  98743. configurable: true
  98744. });
  98745. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  98746. var vrDisplay = this._scene.getEngine().getVRDevice();
  98747. if (vrDisplay) {
  98748. var wasPresenting = this._webVRpresenting;
  98749. this._webVRpresenting = vrDisplay.isPresenting;
  98750. if (wasPresenting && !this._webVRpresenting)
  98751. this.exitVR();
  98752. }
  98753. else {
  98754. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  98755. }
  98756. this.updateButtonVisibility();
  98757. };
  98758. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  98759. this._webVRsupported = eventArgs.vrSupported;
  98760. this._webVRready = !!eventArgs.vrDisplay;
  98761. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  98762. this.updateButtonVisibility();
  98763. };
  98764. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  98765. if (this._canvas && !this._useCustomVRButton) {
  98766. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  98767. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  98768. }
  98769. };
  98770. VRExperienceHelper.prototype.displayVRButton = function () {
  98771. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  98772. document.body.appendChild(this._btnVR);
  98773. this._btnVRDisplayed = true;
  98774. }
  98775. };
  98776. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  98777. if (!this._btnVR || this._useCustomVRButton) {
  98778. return;
  98779. }
  98780. this._btnVR.className = "babylonVRicon";
  98781. if (this.isInVRMode) {
  98782. this._btnVR.className += " vrdisplaypresenting";
  98783. }
  98784. else {
  98785. if (this._webVRready)
  98786. this._btnVR.className += " vrdisplayready";
  98787. if (this._webVRsupported)
  98788. this._btnVR.className += " vrdisplaysupported";
  98789. if (this._webVRrequesting)
  98790. this._btnVR.className += " vrdisplayrequesting";
  98791. }
  98792. };
  98793. /**
  98794. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98795. * Otherwise, will use the fullscreen API.
  98796. */
  98797. VRExperienceHelper.prototype.enterVR = function () {
  98798. if (this.onEnteringVRObservable) {
  98799. try {
  98800. this.onEnteringVRObservable.notifyObservers(this);
  98801. }
  98802. catch (err) {
  98803. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98804. }
  98805. }
  98806. if (this._scene.activeCamera) {
  98807. this._position = this._scene.activeCamera.position.clone();
  98808. // make sure that we return to the last active camera
  98809. this._existingCamera = this._scene.activeCamera;
  98810. }
  98811. if (this._webVRrequesting)
  98812. return;
  98813. // If WebVR is supported and a headset is connected
  98814. if (this._webVRready) {
  98815. if (!this._webVRpresenting) {
  98816. this._webVRCamera.position = this._position;
  98817. this._scene.activeCamera = this._webVRCamera;
  98818. }
  98819. }
  98820. else if (this._vrDeviceOrientationCamera) {
  98821. this._vrDeviceOrientationCamera.position = this._position;
  98822. if (this._scene.activeCamera) {
  98823. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98824. }
  98825. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98826. this._scene.getEngine().switchFullscreen(true);
  98827. this.updateButtonVisibility();
  98828. }
  98829. if (this._scene.activeCamera && this._canvas) {
  98830. this._scene.activeCamera.attachControl(this._canvas);
  98831. }
  98832. if (this._interactionsEnabled) {
  98833. this._scene.registerBeforeRender(this.beforeRender);
  98834. }
  98835. this._hasEnteredVR = true;
  98836. };
  98837. /**
  98838. * Attempt to exit VR, or fullscreen.
  98839. */
  98840. VRExperienceHelper.prototype.exitVR = function () {
  98841. if (this._hasEnteredVR) {
  98842. if (this.onExitingVRObservable) {
  98843. try {
  98844. this.onExitingVRObservable.notifyObservers(this);
  98845. }
  98846. catch (err) {
  98847. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98848. }
  98849. }
  98850. if (this._webVRpresenting) {
  98851. this._scene.getEngine().disableVR();
  98852. }
  98853. if (this._scene.activeCamera) {
  98854. this._position = this._scene.activeCamera.position.clone();
  98855. }
  98856. if (this._deviceOrientationCamera) {
  98857. this._deviceOrientationCamera.position = this._position;
  98858. this._scene.activeCamera = this._deviceOrientationCamera;
  98859. if (this._canvas) {
  98860. this._scene.activeCamera.attachControl(this._canvas);
  98861. }
  98862. }
  98863. else if (this._existingCamera) {
  98864. this._existingCamera.position = this._position;
  98865. this._scene.activeCamera = this._existingCamera;
  98866. }
  98867. this.updateButtonVisibility();
  98868. if (this._interactionsEnabled) {
  98869. this._scene.unregisterBeforeRender(this.beforeRender);
  98870. this._cameraGazer._gazeTracker.isVisible = false;
  98871. if (this._leftController) {
  98872. this._leftController._gazeTracker.isVisible = false;
  98873. }
  98874. if (this._rightController) {
  98875. this._rightController._gazeTracker.isVisible = false;
  98876. }
  98877. }
  98878. // resize to update width and height when exiting vr exits fullscreen
  98879. this._scene.getEngine().resize();
  98880. this._hasEnteredVR = false;
  98881. }
  98882. };
  98883. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98884. /**
  98885. * The position of the vr experience helper.
  98886. */
  98887. get: function () {
  98888. return this._position;
  98889. },
  98890. /**
  98891. * Sets the position of the vr experience helper.
  98892. */
  98893. set: function (value) {
  98894. this._position = value;
  98895. if (this._scene.activeCamera) {
  98896. this._scene.activeCamera.position = value;
  98897. }
  98898. },
  98899. enumerable: true,
  98900. configurable: true
  98901. });
  98902. /**
  98903. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98904. */
  98905. VRExperienceHelper.prototype.enableInteractions = function () {
  98906. var _this = this;
  98907. if (!this._interactionsEnabled) {
  98908. this._interactionsRequested = true;
  98909. if (this._leftController) {
  98910. this._enableInteractionOnController(this._leftController);
  98911. }
  98912. if (this._rightController) {
  98913. this._enableInteractionOnController(this._rightController);
  98914. }
  98915. this.raySelectionPredicate = function (mesh) {
  98916. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98917. };
  98918. this.meshSelectionPredicate = function (mesh) {
  98919. return true;
  98920. };
  98921. this._raySelectionPredicate = function (mesh) {
  98922. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98923. && mesh.name.indexOf("teleportationTarget") === -1
  98924. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98925. return _this.raySelectionPredicate(mesh);
  98926. }
  98927. return false;
  98928. };
  98929. this._interactionsEnabled = true;
  98930. }
  98931. };
  98932. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98933. get: function () {
  98934. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98935. },
  98936. enumerable: true,
  98937. configurable: true
  98938. });
  98939. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98940. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98941. if (this._floorMeshesCollection[i].id === mesh.id) {
  98942. return true;
  98943. }
  98944. }
  98945. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98946. return true;
  98947. }
  98948. return false;
  98949. };
  98950. /**
  98951. * Adds a floor mesh to be used for teleportation.
  98952. * @param floorMesh the mesh to be used for teleportation.
  98953. */
  98954. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98955. if (!this._floorMeshesCollection) {
  98956. return;
  98957. }
  98958. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98959. return;
  98960. }
  98961. this._floorMeshesCollection.push(floorMesh);
  98962. };
  98963. /**
  98964. * Removes a floor mesh from being used for teleportation.
  98965. * @param floorMesh the mesh to be removed.
  98966. */
  98967. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98968. if (!this._floorMeshesCollection) {
  98969. return;
  98970. }
  98971. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98972. if (meshIndex !== -1) {
  98973. this._floorMeshesCollection.splice(meshIndex, 1);
  98974. }
  98975. };
  98976. /**
  98977. * Enables interactions and teleportation using the VR controllers and gaze.
  98978. * @param vrTeleportationOptions options to modify teleportation behavior.
  98979. */
  98980. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98981. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98982. if (!this._teleportationInitialized) {
  98983. this._teleportationRequested = true;
  98984. this.enableInteractions();
  98985. if (vrTeleportationOptions.floorMeshName) {
  98986. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98987. }
  98988. if (vrTeleportationOptions.floorMeshes) {
  98989. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98990. }
  98991. if (this._leftController != null) {
  98992. this._enableTeleportationOnController(this._leftController);
  98993. }
  98994. if (this._rightController != null) {
  98995. this._enableTeleportationOnController(this._rightController);
  98996. }
  98997. // Creates an image processing post process for the vignette not relying
  98998. // on the main scene configuration for image processing to reduce setup and spaces
  98999. // (gamma/linear) conflicts.
  99000. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  99001. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  99002. imageProcessingConfiguration.vignetteEnabled = true;
  99003. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  99004. this._webVRCamera.detachPostProcess(this._postProcessMove);
  99005. this._teleportationInitialized = true;
  99006. if (this._isDefaultTeleportationTarget) {
  99007. this._createTeleportationCircles();
  99008. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  99009. }
  99010. }
  99011. };
  99012. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  99013. var _this = this;
  99014. var controllerMesh = controller.webVRController.mesh;
  99015. if (controllerMesh) {
  99016. controller._interactionsEnabled = true;
  99017. controller._activatePointer();
  99018. if (this.webVROptions.laserToggle) {
  99019. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  99020. // Enabling / disabling laserPointer
  99021. if (_this._displayLaserPointer && stateObject.value === 1) {
  99022. if (controller._activePointer) {
  99023. controller._deactivatePointer();
  99024. }
  99025. else {
  99026. controller._activatePointer();
  99027. }
  99028. if (_this.displayGaze) {
  99029. controller._gazeTracker.isVisible = controller._activePointer;
  99030. }
  99031. }
  99032. });
  99033. }
  99034. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  99035. var gazer = controller;
  99036. if (_this._noControllerIsActive) {
  99037. gazer = _this._cameraGazer;
  99038. }
  99039. if (!gazer._pointerDownOnMeshAsked) {
  99040. if (stateObject.value > _this._padSensibilityUp) {
  99041. gazer._selectionPointerDown();
  99042. }
  99043. }
  99044. else if (stateObject.value < _this._padSensibilityDown) {
  99045. gazer._selectionPointerUp();
  99046. }
  99047. });
  99048. }
  99049. };
  99050. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  99051. // Dont teleport if another gaze already requested teleportation
  99052. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  99053. return;
  99054. }
  99055. if (!gazer._teleportationRequestInitiated) {
  99056. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  99057. gazer._activatePointer();
  99058. gazer._teleportationRequestInitiated = true;
  99059. }
  99060. }
  99061. else {
  99062. // Listening to the proper controller values changes to confirm teleportation
  99063. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  99064. if (this._teleportActive) {
  99065. this.teleportCamera(this._haloCenter);
  99066. }
  99067. gazer._teleportationRequestInitiated = false;
  99068. }
  99069. }
  99070. };
  99071. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  99072. // Only rotate when user is not currently selecting a teleportation location
  99073. if (gazer._teleportationRequestInitiated) {
  99074. return;
  99075. }
  99076. if (!gazer._rotationLeftAsked) {
  99077. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  99078. gazer._rotationLeftAsked = true;
  99079. if (this._rotationAllowed) {
  99080. this._rotateCamera(false);
  99081. }
  99082. }
  99083. }
  99084. else {
  99085. if (stateObject.x > -this._padSensibilityDown) {
  99086. gazer._rotationLeftAsked = false;
  99087. }
  99088. }
  99089. if (!gazer._rotationRightAsked) {
  99090. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  99091. gazer._rotationRightAsked = true;
  99092. if (this._rotationAllowed) {
  99093. this._rotateCamera(true);
  99094. }
  99095. }
  99096. }
  99097. else {
  99098. if (stateObject.x < this._padSensibilityDown) {
  99099. gazer._rotationRightAsked = false;
  99100. }
  99101. }
  99102. };
  99103. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  99104. // Only teleport backwards when user is not currently selecting a teleportation location
  99105. if (gazer._teleportationRequestInitiated) {
  99106. return;
  99107. }
  99108. // Teleport backwards
  99109. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  99110. if (!gazer._teleportationBackRequestInitiated) {
  99111. if (!this.currentVRCamera) {
  99112. return;
  99113. }
  99114. // Get rotation and position of the current camera
  99115. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  99116. var position = this.currentVRCamera.position;
  99117. // If the camera has device position, use that instead
  99118. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  99119. rotation = this.currentVRCamera.deviceRotationQuaternion;
  99120. position = this.currentVRCamera.devicePosition;
  99121. }
  99122. // Get matrix with only the y rotation of the device rotation
  99123. rotation.toEulerAnglesToRef(this._workingVector);
  99124. this._workingVector.z = 0;
  99125. this._workingVector.x = 0;
  99126. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  99127. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  99128. // Rotate backwards ray by device rotation to cast at the ground behind the user
  99129. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  99130. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  99131. var ray = new BABYLON.Ray(position, this._workingVector);
  99132. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99133. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  99134. this.teleportCamera(hit.pickedPoint);
  99135. }
  99136. gazer._teleportationBackRequestInitiated = true;
  99137. }
  99138. }
  99139. else {
  99140. gazer._teleportationBackRequestInitiated = false;
  99141. }
  99142. };
  99143. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  99144. var _this = this;
  99145. var controllerMesh = controller.webVRController.mesh;
  99146. if (controllerMesh) {
  99147. if (!controller._interactionsEnabled) {
  99148. this._enableInteractionOnController(controller);
  99149. }
  99150. controller._interactionsEnabled = true;
  99151. controller._teleportationEnabled = true;
  99152. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99153. controller._dpadPressed = false;
  99154. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  99155. controller._dpadPressed = stateObject.pressed;
  99156. if (!controller._dpadPressed) {
  99157. controller._rotationLeftAsked = false;
  99158. controller._rotationRightAsked = false;
  99159. controller._teleportationBackRequestInitiated = false;
  99160. }
  99161. });
  99162. }
  99163. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  99164. if (_this.teleportationEnabled) {
  99165. _this._checkTeleportBackwards(stateObject, controller);
  99166. _this._checkTeleportWithRay(stateObject, controller);
  99167. }
  99168. _this._checkRotate(stateObject, controller);
  99169. });
  99170. }
  99171. };
  99172. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  99173. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  99174. this._teleportationTarget.isPickable = false;
  99175. var length = 512;
  99176. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  99177. dynamicTexture.hasAlpha = true;
  99178. var context = dynamicTexture.getContext();
  99179. var centerX = length / 2;
  99180. var centerY = length / 2;
  99181. var radius = 200;
  99182. context.beginPath();
  99183. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  99184. context.fillStyle = this._teleportationFillColor;
  99185. context.fill();
  99186. context.lineWidth = 10;
  99187. context.strokeStyle = this._teleportationBorderColor;
  99188. context.stroke();
  99189. context.closePath();
  99190. dynamicTexture.update();
  99191. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  99192. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  99193. this._teleportationTarget.material = teleportationCircleMaterial;
  99194. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  99195. torus.isPickable = false;
  99196. torus.parent = this._teleportationTarget;
  99197. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  99198. var keys = [];
  99199. keys.push({
  99200. frame: 0,
  99201. value: 0
  99202. });
  99203. keys.push({
  99204. frame: 30,
  99205. value: 0.4
  99206. });
  99207. keys.push({
  99208. frame: 60,
  99209. value: 0
  99210. });
  99211. animationInnerCircle.setKeys(keys);
  99212. var easingFunction = new BABYLON.SineEase();
  99213. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  99214. animationInnerCircle.setEasingFunction(easingFunction);
  99215. torus.animations = [];
  99216. torus.animations.push(animationInnerCircle);
  99217. this._scene.beginAnimation(torus, 0, 60, true);
  99218. this._hideTeleportationTarget();
  99219. };
  99220. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  99221. this._teleportActive = true;
  99222. if (this._teleportationInitialized) {
  99223. this._teleportationTarget.isVisible = true;
  99224. if (this._isDefaultTeleportationTarget) {
  99225. this._teleportationTarget.getChildren()[0].isVisible = true;
  99226. }
  99227. }
  99228. };
  99229. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  99230. this._teleportActive = false;
  99231. if (this._teleportationInitialized) {
  99232. this._teleportationTarget.isVisible = false;
  99233. if (this._isDefaultTeleportationTarget) {
  99234. this._teleportationTarget.getChildren()[0].isVisible = false;
  99235. }
  99236. }
  99237. };
  99238. VRExperienceHelper.prototype._rotateCamera = function (right) {
  99239. var _this = this;
  99240. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99241. return;
  99242. }
  99243. if (right) {
  99244. this._rotationAngle++;
  99245. }
  99246. else {
  99247. this._rotationAngle--;
  99248. }
  99249. this.currentVRCamera.animations = [];
  99250. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  99251. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99252. var animationRotationKeys = [];
  99253. animationRotationKeys.push({
  99254. frame: 0,
  99255. value: this.currentVRCamera.rotationQuaternion
  99256. });
  99257. animationRotationKeys.push({
  99258. frame: 6,
  99259. value: target
  99260. });
  99261. animationRotation.setKeys(animationRotationKeys);
  99262. animationRotation.setEasingFunction(this._circleEase);
  99263. this.currentVRCamera.animations.push(animationRotation);
  99264. this._postProcessMove.animations = [];
  99265. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99266. var vignetteWeightKeys = [];
  99267. vignetteWeightKeys.push({
  99268. frame: 0,
  99269. value: 0
  99270. });
  99271. vignetteWeightKeys.push({
  99272. frame: 3,
  99273. value: 4
  99274. });
  99275. vignetteWeightKeys.push({
  99276. frame: 6,
  99277. value: 0
  99278. });
  99279. animationPP.setKeys(vignetteWeightKeys);
  99280. animationPP.setEasingFunction(this._circleEase);
  99281. this._postProcessMove.animations.push(animationPP);
  99282. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99283. var vignetteStretchKeys = [];
  99284. vignetteStretchKeys.push({
  99285. frame: 0,
  99286. value: 0
  99287. });
  99288. vignetteStretchKeys.push({
  99289. frame: 3,
  99290. value: 10
  99291. });
  99292. vignetteStretchKeys.push({
  99293. frame: 6,
  99294. value: 0
  99295. });
  99296. animationPP2.setKeys(vignetteStretchKeys);
  99297. animationPP2.setEasingFunction(this._circleEase);
  99298. this._postProcessMove.animations.push(animationPP2);
  99299. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99300. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99301. this._postProcessMove.samples = 4;
  99302. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99303. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  99304. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99305. });
  99306. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  99307. };
  99308. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  99309. if (hit.pickedPoint) {
  99310. if (gazer._teleportationRequestInitiated) {
  99311. this._displayTeleportationTarget();
  99312. this._haloCenter.copyFrom(hit.pickedPoint);
  99313. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  99314. }
  99315. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  99316. if (pickNormal) {
  99317. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99318. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99319. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  99320. }
  99321. this._teleportationTarget.position.y += 0.1;
  99322. }
  99323. };
  99324. /**
  99325. * Teleports the users feet to the desired location
  99326. * @param location The location where the user's feet should be placed
  99327. */
  99328. VRExperienceHelper.prototype.teleportCamera = function (location) {
  99329. var _this = this;
  99330. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99331. return;
  99332. }
  99333. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  99334. // offset of the headset from the anchor.
  99335. if (this.webVRCamera.leftCamera) {
  99336. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  99337. this._workingVector.subtractInPlace(this.webVRCamera.position);
  99338. location.subtractToRef(this._workingVector, this._workingVector);
  99339. }
  99340. else {
  99341. this._workingVector.copyFrom(location);
  99342. }
  99343. // Add height to account for user's height offset
  99344. if (this.isInVRMode) {
  99345. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  99346. }
  99347. else {
  99348. this._workingVector.y += this._defaultHeight;
  99349. }
  99350. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  99351. // Create animation from the camera's position to the new location
  99352. this.currentVRCamera.animations = [];
  99353. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99354. var animationCameraTeleportationKeys = [{
  99355. frame: 0,
  99356. value: this.currentVRCamera.position
  99357. },
  99358. {
  99359. frame: 11,
  99360. value: this._workingVector
  99361. }
  99362. ];
  99363. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  99364. animationCameraTeleportation.setEasingFunction(this._circleEase);
  99365. this.currentVRCamera.animations.push(animationCameraTeleportation);
  99366. this._postProcessMove.animations = [];
  99367. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99368. var vignetteWeightKeys = [];
  99369. vignetteWeightKeys.push({
  99370. frame: 0,
  99371. value: 0
  99372. });
  99373. vignetteWeightKeys.push({
  99374. frame: 5,
  99375. value: 8
  99376. });
  99377. vignetteWeightKeys.push({
  99378. frame: 11,
  99379. value: 0
  99380. });
  99381. animationPP.setKeys(vignetteWeightKeys);
  99382. this._postProcessMove.animations.push(animationPP);
  99383. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99384. var vignetteStretchKeys = [];
  99385. vignetteStretchKeys.push({
  99386. frame: 0,
  99387. value: 0
  99388. });
  99389. vignetteStretchKeys.push({
  99390. frame: 5,
  99391. value: 10
  99392. });
  99393. vignetteStretchKeys.push({
  99394. frame: 11,
  99395. value: 0
  99396. });
  99397. animationPP2.setKeys(vignetteStretchKeys);
  99398. this._postProcessMove.animations.push(animationPP2);
  99399. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99400. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99401. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99402. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  99403. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99404. });
  99405. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  99406. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  99407. });
  99408. this._hideTeleportationTarget();
  99409. };
  99410. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  99411. if (normal) {
  99412. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  99413. if (angle < Math.PI / 2) {
  99414. normal.scaleInPlace(-1);
  99415. }
  99416. }
  99417. return normal;
  99418. };
  99419. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  99420. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99421. return;
  99422. }
  99423. var ray = gazer._getForwardRay(this._rayLength);
  99424. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99425. if (hit) {
  99426. // Populate the contrllers mesh that can be used for drag/drop
  99427. if (gazer._laserPointer) {
  99428. hit.originMesh = gazer._laserPointer.parent;
  99429. }
  99430. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  99431. }
  99432. gazer._currentHit = hit;
  99433. // Moving the gazeTracker on the mesh face targetted
  99434. if (hit && hit.pickedPoint) {
  99435. if (this._displayGaze) {
  99436. var multiplier = 1;
  99437. gazer._gazeTracker.isVisible = true;
  99438. if (gazer._isActionableMesh) {
  99439. multiplier = 3;
  99440. }
  99441. if (this.updateGazeTrackerScale) {
  99442. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  99443. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  99444. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  99445. }
  99446. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  99447. // To avoid z-fighting
  99448. var deltaFighting = 0.002;
  99449. if (pickNormal) {
  99450. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99451. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99452. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  99453. }
  99454. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  99455. if (gazer._gazeTracker.position.x < 0) {
  99456. gazer._gazeTracker.position.x += deltaFighting;
  99457. }
  99458. else {
  99459. gazer._gazeTracker.position.x -= deltaFighting;
  99460. }
  99461. if (gazer._gazeTracker.position.y < 0) {
  99462. gazer._gazeTracker.position.y += deltaFighting;
  99463. }
  99464. else {
  99465. gazer._gazeTracker.position.y -= deltaFighting;
  99466. }
  99467. if (gazer._gazeTracker.position.z < 0) {
  99468. gazer._gazeTracker.position.z += deltaFighting;
  99469. }
  99470. else {
  99471. gazer._gazeTracker.position.z -= deltaFighting;
  99472. }
  99473. }
  99474. // Changing the size of the laser pointer based on the distance from the targetted point
  99475. gazer._updatePointerDistance(hit.distance);
  99476. }
  99477. else {
  99478. gazer._updatePointerDistance();
  99479. gazer._gazeTracker.isVisible = false;
  99480. }
  99481. if (hit && hit.pickedMesh) {
  99482. // The object selected is the floor, we're in a teleportation scenario
  99483. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  99484. // Moving the teleportation area to this targetted point
  99485. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  99486. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  99487. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99488. }
  99489. gazer._currentMeshSelected = null;
  99490. if (gazer._teleportationRequestInitiated) {
  99491. this._moveTeleportationSelectorTo(hit, gazer, ray);
  99492. }
  99493. return;
  99494. }
  99495. // If not, we're in a selection scenario
  99496. //this._teleportationAllowed = false;
  99497. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  99498. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  99499. this.onNewMeshPicked.notifyObservers(hit);
  99500. gazer._currentMeshSelected = hit.pickedMesh;
  99501. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  99502. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  99503. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  99504. gazer._isActionableMesh = true;
  99505. }
  99506. else {
  99507. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99508. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99509. gazer._isActionableMesh = false;
  99510. }
  99511. try {
  99512. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  99513. }
  99514. catch (err) {
  99515. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  99516. }
  99517. }
  99518. else {
  99519. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99520. gazer._currentMeshSelected = null;
  99521. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99522. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99523. }
  99524. }
  99525. }
  99526. else {
  99527. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99528. gazer._currentMeshSelected = null;
  99529. //this._teleportationAllowed = false;
  99530. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99531. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99532. }
  99533. };
  99534. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  99535. if (mesh) {
  99536. this.onSelectedMeshUnselected.notifyObservers(mesh);
  99537. }
  99538. };
  99539. /**
  99540. * Sets the color of the laser ray from the vr controllers.
  99541. * @param color new color for the ray.
  99542. */
  99543. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  99544. if (this._leftController) {
  99545. this._leftController._setLaserPointerColor(color);
  99546. }
  99547. if (this._rightController) {
  99548. this._rightController._setLaserPointerColor(color);
  99549. }
  99550. };
  99551. /**
  99552. * Sets the color of the ray from the vr headsets gaze.
  99553. * @param color new color for the ray.
  99554. */
  99555. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  99556. if (!this._cameraGazer._gazeTracker.material) {
  99557. return;
  99558. }
  99559. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  99560. if (this._leftController) {
  99561. this._leftController._gazeTracker.material.emissiveColor = color;
  99562. }
  99563. if (this._rightController) {
  99564. this._rightController._gazeTracker.material.emissiveColor = color;
  99565. }
  99566. };
  99567. /**
  99568. * Exits VR and disposes of the vr experience helper
  99569. */
  99570. VRExperienceHelper.prototype.dispose = function () {
  99571. if (this.isInVRMode) {
  99572. this.exitVR();
  99573. }
  99574. if (this._postProcessMove) {
  99575. this._postProcessMove.dispose();
  99576. }
  99577. if (this._webVRCamera) {
  99578. this._webVRCamera.dispose();
  99579. }
  99580. if (this._vrDeviceOrientationCamera) {
  99581. this._vrDeviceOrientationCamera.dispose();
  99582. }
  99583. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  99584. document.body.removeChild(this._btnVR);
  99585. }
  99586. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  99587. this._deviceOrientationCamera.dispose();
  99588. }
  99589. if (this._cameraGazer) {
  99590. this._cameraGazer.dispose();
  99591. }
  99592. if (this._leftController) {
  99593. this._leftController.dispose();
  99594. }
  99595. if (this._rightController) {
  99596. this._rightController.dispose();
  99597. }
  99598. if (this._teleportationTarget) {
  99599. this._teleportationTarget.dispose();
  99600. }
  99601. this._floorMeshesCollection = [];
  99602. document.removeEventListener("keydown", this._onKeyDown);
  99603. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99604. window.removeEventListener("resize", this._onResize);
  99605. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  99606. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  99607. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  99608. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  99609. document.onmsfullscreenchange = null;
  99610. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  99611. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  99612. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  99613. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99614. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  99615. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  99616. this._scene.unregisterBeforeRender(this.beforeRender);
  99617. };
  99618. /**
  99619. * Gets the name of the VRExperienceHelper class
  99620. * @returns "VRExperienceHelper"
  99621. */
  99622. VRExperienceHelper.prototype.getClassName = function () {
  99623. return "VRExperienceHelper";
  99624. };
  99625. return VRExperienceHelper;
  99626. }());
  99627. BABYLON.VRExperienceHelper = VRExperienceHelper;
  99628. })(BABYLON || (BABYLON = {}));
  99629. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  99630. // Mainly based on these 2 articles :
  99631. // 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
  99632. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  99633. var BABYLON;
  99634. (function (BABYLON) {
  99635. /**
  99636. * Defines the potential axis of a Joystick
  99637. */
  99638. var JoystickAxis;
  99639. (function (JoystickAxis) {
  99640. /** X axis */
  99641. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  99642. /** Y axis */
  99643. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  99644. /** Z axis */
  99645. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  99646. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  99647. /**
  99648. * Class used to define virtual joystick (used in touch mode)
  99649. */
  99650. var VirtualJoystick = /** @class */ (function () {
  99651. /**
  99652. * Creates a new virtual joystick
  99653. * @param leftJoystick defines that the joystick is for left hand (false by default)
  99654. */
  99655. function VirtualJoystick(leftJoystick) {
  99656. var _this = this;
  99657. if (leftJoystick) {
  99658. this._leftJoystick = true;
  99659. }
  99660. else {
  99661. this._leftJoystick = false;
  99662. }
  99663. VirtualJoystick._globalJoystickIndex++;
  99664. // By default left & right arrow keys are moving the X
  99665. // and up & down keys are moving the Y
  99666. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99667. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99668. this.reverseLeftRight = false;
  99669. this.reverseUpDown = false;
  99670. // collections of pointers
  99671. this._touches = new BABYLON.StringDictionary();
  99672. this.deltaPosition = BABYLON.Vector3.Zero();
  99673. this._joystickSensibility = 25;
  99674. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99675. this._onResize = function (evt) {
  99676. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99677. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99678. if (VirtualJoystick.vjCanvas) {
  99679. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  99680. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  99681. }
  99682. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  99683. };
  99684. // injecting a canvas element on top of the canvas 3D game
  99685. if (!VirtualJoystick.vjCanvas) {
  99686. window.addEventListener("resize", this._onResize, false);
  99687. VirtualJoystick.vjCanvas = document.createElement("canvas");
  99688. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99689. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99690. VirtualJoystick.vjCanvas.width = window.innerWidth;
  99691. VirtualJoystick.vjCanvas.height = window.innerHeight;
  99692. VirtualJoystick.vjCanvas.style.width = "100%";
  99693. VirtualJoystick.vjCanvas.style.height = "100%";
  99694. VirtualJoystick.vjCanvas.style.position = "absolute";
  99695. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  99696. VirtualJoystick.vjCanvas.style.top = "0px";
  99697. VirtualJoystick.vjCanvas.style.left = "0px";
  99698. VirtualJoystick.vjCanvas.style.zIndex = "5";
  99699. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  99700. // Support for jQuery PEP polyfill
  99701. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  99702. var context = VirtualJoystick.vjCanvas.getContext('2d');
  99703. if (!context) {
  99704. throw new Error("Unable to create canvas for virtual joystick");
  99705. }
  99706. VirtualJoystick.vjCanvasContext = context;
  99707. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  99708. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99709. document.body.appendChild(VirtualJoystick.vjCanvas);
  99710. }
  99711. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  99712. this.pressed = false;
  99713. // default joystick color
  99714. this._joystickColor = "cyan";
  99715. this._joystickPointerID = -1;
  99716. // current joystick position
  99717. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  99718. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  99719. // origin joystick position
  99720. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  99721. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  99722. this._onPointerDownHandlerRef = function (evt) {
  99723. _this._onPointerDown(evt);
  99724. };
  99725. this._onPointerMoveHandlerRef = function (evt) {
  99726. _this._onPointerMove(evt);
  99727. };
  99728. this._onPointerUpHandlerRef = function (evt) {
  99729. _this._onPointerUp(evt);
  99730. };
  99731. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  99732. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  99733. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  99734. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  99735. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  99736. evt.preventDefault(); // Disables system menu
  99737. }, false);
  99738. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99739. }
  99740. /**
  99741. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  99742. * @param newJoystickSensibility defines the new sensibility
  99743. */
  99744. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  99745. this._joystickSensibility = newJoystickSensibility;
  99746. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99747. };
  99748. VirtualJoystick.prototype._onPointerDown = function (e) {
  99749. var positionOnScreenCondition;
  99750. e.preventDefault();
  99751. if (this._leftJoystick === true) {
  99752. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  99753. }
  99754. else {
  99755. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  99756. }
  99757. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  99758. // First contact will be dedicated to the virtual joystick
  99759. this._joystickPointerID = e.pointerId;
  99760. this._joystickPointerStartPos.x = e.clientX;
  99761. this._joystickPointerStartPos.y = e.clientY;
  99762. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  99763. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  99764. this._deltaJoystickVector.x = 0;
  99765. this._deltaJoystickVector.y = 0;
  99766. this.pressed = true;
  99767. this._touches.add(e.pointerId.toString(), e);
  99768. }
  99769. else {
  99770. // You can only trigger the action buttons with a joystick declared
  99771. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  99772. this._action();
  99773. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  99774. }
  99775. }
  99776. };
  99777. VirtualJoystick.prototype._onPointerMove = function (e) {
  99778. // If the current pointer is the one associated to the joystick (first touch contact)
  99779. if (this._joystickPointerID == e.pointerId) {
  99780. this._joystickPointerPos.x = e.clientX;
  99781. this._joystickPointerPos.y = e.clientY;
  99782. this._deltaJoystickVector = this._joystickPointerPos.clone();
  99783. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  99784. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99785. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99786. switch (this._axisTargetedByLeftAndRight) {
  99787. case JoystickAxis.X:
  99788. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99789. break;
  99790. case JoystickAxis.Y:
  99791. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99792. break;
  99793. case JoystickAxis.Z:
  99794. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99795. break;
  99796. }
  99797. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99798. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99799. switch (this._axisTargetedByUpAndDown) {
  99800. case JoystickAxis.X:
  99801. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99802. break;
  99803. case JoystickAxis.Y:
  99804. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99805. break;
  99806. case JoystickAxis.Z:
  99807. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99808. break;
  99809. }
  99810. }
  99811. else {
  99812. var data = this._touches.get(e.pointerId.toString());
  99813. if (data) {
  99814. data.x = e.clientX;
  99815. data.y = e.clientY;
  99816. }
  99817. }
  99818. };
  99819. VirtualJoystick.prototype._onPointerUp = function (e) {
  99820. if (this._joystickPointerID == e.pointerId) {
  99821. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99822. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99823. this._joystickPointerID = -1;
  99824. this.pressed = false;
  99825. }
  99826. else {
  99827. var touch = this._touches.get(e.pointerId.toString());
  99828. if (touch) {
  99829. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99830. }
  99831. }
  99832. this._deltaJoystickVector.x = 0;
  99833. this._deltaJoystickVector.y = 0;
  99834. this._touches.remove(e.pointerId.toString());
  99835. };
  99836. /**
  99837. * Change the color of the virtual joystick
  99838. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99839. */
  99840. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99841. this._joystickColor = newColor;
  99842. };
  99843. /**
  99844. * Defines a callback to call when the joystick is touched
  99845. * @param action defines the callback
  99846. */
  99847. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99848. this._action = action;
  99849. };
  99850. /**
  99851. * Defines which axis you'd like to control for left & right
  99852. * @param axis defines the axis to use
  99853. */
  99854. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99855. switch (axis) {
  99856. case JoystickAxis.X:
  99857. case JoystickAxis.Y:
  99858. case JoystickAxis.Z:
  99859. this._axisTargetedByLeftAndRight = axis;
  99860. break;
  99861. default:
  99862. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99863. break;
  99864. }
  99865. };
  99866. /**
  99867. * Defines which axis you'd like to control for up & down
  99868. * @param axis defines the axis to use
  99869. */
  99870. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99871. switch (axis) {
  99872. case JoystickAxis.X:
  99873. case JoystickAxis.Y:
  99874. case JoystickAxis.Z:
  99875. this._axisTargetedByUpAndDown = axis;
  99876. break;
  99877. default:
  99878. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99879. break;
  99880. }
  99881. };
  99882. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99883. var _this = this;
  99884. if (this.pressed) {
  99885. this._touches.forEach(function (key, touch) {
  99886. if (touch.pointerId === _this._joystickPointerID) {
  99887. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99888. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99889. VirtualJoystick.vjCanvasContext.beginPath();
  99890. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99891. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99892. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99893. VirtualJoystick.vjCanvasContext.stroke();
  99894. VirtualJoystick.vjCanvasContext.closePath();
  99895. VirtualJoystick.vjCanvasContext.beginPath();
  99896. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99897. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99898. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99899. VirtualJoystick.vjCanvasContext.stroke();
  99900. VirtualJoystick.vjCanvasContext.closePath();
  99901. VirtualJoystick.vjCanvasContext.beginPath();
  99902. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99903. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99904. VirtualJoystick.vjCanvasContext.stroke();
  99905. VirtualJoystick.vjCanvasContext.closePath();
  99906. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99907. }
  99908. else {
  99909. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99910. VirtualJoystick.vjCanvasContext.beginPath();
  99911. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99912. VirtualJoystick.vjCanvasContext.beginPath();
  99913. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99914. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99915. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99916. VirtualJoystick.vjCanvasContext.stroke();
  99917. VirtualJoystick.vjCanvasContext.closePath();
  99918. touch.prevX = touch.x;
  99919. touch.prevY = touch.y;
  99920. }
  99921. ;
  99922. });
  99923. }
  99924. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99925. };
  99926. /**
  99927. * Release internal HTML canvas
  99928. */
  99929. VirtualJoystick.prototype.releaseCanvas = function () {
  99930. if (VirtualJoystick.vjCanvas) {
  99931. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99932. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99933. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99934. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99935. window.removeEventListener("resize", this._onResize);
  99936. document.body.removeChild(VirtualJoystick.vjCanvas);
  99937. VirtualJoystick.vjCanvas = null;
  99938. }
  99939. };
  99940. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99941. VirtualJoystick._globalJoystickIndex = 0;
  99942. return VirtualJoystick;
  99943. }());
  99944. BABYLON.VirtualJoystick = VirtualJoystick;
  99945. })(BABYLON || (BABYLON = {}));
  99946. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99947. var BABYLON;
  99948. (function (BABYLON) {
  99949. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99950. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99951. });
  99952. // We're mainly based on the logic defined into the FreeCamera code
  99953. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99954. __extends(VirtualJoysticksCamera, _super);
  99955. function VirtualJoysticksCamera(name, position, scene) {
  99956. var _this = _super.call(this, name, position, scene) || this;
  99957. _this.inputs.addVirtualJoystick();
  99958. return _this;
  99959. }
  99960. VirtualJoysticksCamera.prototype.getClassName = function () {
  99961. return "VirtualJoysticksCamera";
  99962. };
  99963. return VirtualJoysticksCamera;
  99964. }(BABYLON.FreeCamera));
  99965. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99966. })(BABYLON || (BABYLON = {}));
  99967. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99968. var BABYLON;
  99969. (function (BABYLON) {
  99970. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99971. function FreeCameraVirtualJoystickInput() {
  99972. }
  99973. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99974. return this._leftjoystick;
  99975. };
  99976. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99977. return this._rightjoystick;
  99978. };
  99979. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99980. if (this._leftjoystick) {
  99981. var camera = this.camera;
  99982. var speed = camera._computeLocalCameraSpeed() * 50;
  99983. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99984. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99985. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99986. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99987. if (!this._leftjoystick.pressed) {
  99988. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99989. }
  99990. if (!this._rightjoystick.pressed) {
  99991. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99992. }
  99993. }
  99994. };
  99995. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99996. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99997. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99998. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99999. this._leftjoystick.setJoystickSensibility(0.15);
  100000. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  100001. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  100002. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  100003. this._rightjoystick.reverseUpDown = true;
  100004. this._rightjoystick.setJoystickSensibility(0.05);
  100005. this._rightjoystick.setJoystickColor("yellow");
  100006. };
  100007. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  100008. this._leftjoystick.releaseCanvas();
  100009. this._rightjoystick.releaseCanvas();
  100010. };
  100011. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  100012. return "FreeCameraVirtualJoystickInput";
  100013. };
  100014. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  100015. return "virtualJoystick";
  100016. };
  100017. return FreeCameraVirtualJoystickInput;
  100018. }());
  100019. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  100020. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  100021. })(BABYLON || (BABYLON = {}));
  100022. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  100023. var BABYLON;
  100024. (function (BABYLON) {
  100025. var SimplificationSettings = /** @class */ (function () {
  100026. function SimplificationSettings(quality, distance, optimizeMesh) {
  100027. this.quality = quality;
  100028. this.distance = distance;
  100029. this.optimizeMesh = optimizeMesh;
  100030. }
  100031. return SimplificationSettings;
  100032. }());
  100033. BABYLON.SimplificationSettings = SimplificationSettings;
  100034. var SimplificationQueue = /** @class */ (function () {
  100035. function SimplificationQueue() {
  100036. this.running = false;
  100037. this._simplificationArray = [];
  100038. }
  100039. SimplificationQueue.prototype.addTask = function (task) {
  100040. this._simplificationArray.push(task);
  100041. };
  100042. SimplificationQueue.prototype.executeNext = function () {
  100043. var task = this._simplificationArray.pop();
  100044. if (task) {
  100045. this.running = true;
  100046. this.runSimplification(task);
  100047. }
  100048. else {
  100049. this.running = false;
  100050. }
  100051. };
  100052. SimplificationQueue.prototype.runSimplification = function (task) {
  100053. var _this = this;
  100054. if (task.parallelProcessing) {
  100055. //parallel simplifier
  100056. task.settings.forEach(function (setting) {
  100057. var simplifier = _this.getSimplifier(task);
  100058. simplifier.simplify(setting, function (newMesh) {
  100059. task.mesh.addLODLevel(setting.distance, newMesh);
  100060. newMesh.isVisible = true;
  100061. //check if it is the last
  100062. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  100063. //all done, run the success callback.
  100064. task.successCallback();
  100065. }
  100066. _this.executeNext();
  100067. });
  100068. });
  100069. }
  100070. else {
  100071. //single simplifier.
  100072. var simplifier = this.getSimplifier(task);
  100073. var runDecimation = function (setting, callback) {
  100074. simplifier.simplify(setting, function (newMesh) {
  100075. task.mesh.addLODLevel(setting.distance, newMesh);
  100076. newMesh.isVisible = true;
  100077. //run the next quality level
  100078. callback();
  100079. });
  100080. };
  100081. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  100082. runDecimation(task.settings[loop.index], function () {
  100083. loop.executeNext();
  100084. });
  100085. }, function () {
  100086. //execution ended, run the success callback.
  100087. if (task.successCallback) {
  100088. task.successCallback();
  100089. }
  100090. _this.executeNext();
  100091. });
  100092. }
  100093. };
  100094. SimplificationQueue.prototype.getSimplifier = function (task) {
  100095. switch (task.simplificationType) {
  100096. case SimplificationType.QUADRATIC:
  100097. default:
  100098. return new QuadraticErrorSimplification(task.mesh);
  100099. }
  100100. };
  100101. return SimplificationQueue;
  100102. }());
  100103. BABYLON.SimplificationQueue = SimplificationQueue;
  100104. /**
  100105. * The implemented types of simplification
  100106. * At the moment only Quadratic Error Decimation is implemented
  100107. */
  100108. var SimplificationType;
  100109. (function (SimplificationType) {
  100110. /** Quadratic error decimation */
  100111. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  100112. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  100113. var DecimationTriangle = /** @class */ (function () {
  100114. function DecimationTriangle(vertices) {
  100115. this.vertices = vertices;
  100116. this.error = new Array(4);
  100117. this.deleted = false;
  100118. this.isDirty = false;
  100119. this.deletePending = false;
  100120. this.borderFactor = 0;
  100121. }
  100122. return DecimationTriangle;
  100123. }());
  100124. BABYLON.DecimationTriangle = DecimationTriangle;
  100125. var DecimationVertex = /** @class */ (function () {
  100126. function DecimationVertex(position, id) {
  100127. this.position = position;
  100128. this.id = id;
  100129. this.isBorder = true;
  100130. this.q = new QuadraticMatrix();
  100131. this.triangleCount = 0;
  100132. this.triangleStart = 0;
  100133. this.originalOffsets = [];
  100134. }
  100135. DecimationVertex.prototype.updatePosition = function (newPosition) {
  100136. this.position.copyFrom(newPosition);
  100137. };
  100138. return DecimationVertex;
  100139. }());
  100140. BABYLON.DecimationVertex = DecimationVertex;
  100141. var QuadraticMatrix = /** @class */ (function () {
  100142. function QuadraticMatrix(data) {
  100143. this.data = new Array(10);
  100144. for (var i = 0; i < 10; ++i) {
  100145. if (data && data[i]) {
  100146. this.data[i] = data[i];
  100147. }
  100148. else {
  100149. this.data[i] = 0;
  100150. }
  100151. }
  100152. }
  100153. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  100154. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  100155. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  100156. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  100157. return det;
  100158. };
  100159. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  100160. for (var i = 0; i < 10; ++i) {
  100161. this.data[i] += matrix.data[i];
  100162. }
  100163. };
  100164. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  100165. for (var i = 0; i < 10; ++i) {
  100166. this.data[i] += data[i];
  100167. }
  100168. };
  100169. QuadraticMatrix.prototype.add = function (matrix) {
  100170. var m = new QuadraticMatrix();
  100171. for (var i = 0; i < 10; ++i) {
  100172. m.data[i] = this.data[i] + matrix.data[i];
  100173. }
  100174. return m;
  100175. };
  100176. QuadraticMatrix.FromData = function (a, b, c, d) {
  100177. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  100178. };
  100179. //returning an array to avoid garbage collection
  100180. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  100181. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  100182. };
  100183. return QuadraticMatrix;
  100184. }());
  100185. BABYLON.QuadraticMatrix = QuadraticMatrix;
  100186. var Reference = /** @class */ (function () {
  100187. function Reference(vertexId, triangleId) {
  100188. this.vertexId = vertexId;
  100189. this.triangleId = triangleId;
  100190. }
  100191. return Reference;
  100192. }());
  100193. BABYLON.Reference = Reference;
  100194. /**
  100195. * An implementation of the Quadratic Error simplification algorithm.
  100196. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  100197. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  100198. * @author RaananW
  100199. */
  100200. var QuadraticErrorSimplification = /** @class */ (function () {
  100201. function QuadraticErrorSimplification(_mesh) {
  100202. this._mesh = _mesh;
  100203. this.syncIterations = 5000;
  100204. this.aggressiveness = 7;
  100205. this.decimationIterations = 100;
  100206. this.boundingBoxEpsilon = BABYLON.Epsilon;
  100207. }
  100208. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  100209. var _this = this;
  100210. this.initDecimatedMesh();
  100211. //iterating through the submeshes array, one after the other.
  100212. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  100213. _this.initWithMesh(loop.index, function () {
  100214. _this.runDecimation(settings, loop.index, function () {
  100215. loop.executeNext();
  100216. });
  100217. }, settings.optimizeMesh);
  100218. }, function () {
  100219. setTimeout(function () {
  100220. successCallback(_this._reconstructedMesh);
  100221. }, 0);
  100222. });
  100223. };
  100224. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  100225. var _this = this;
  100226. var targetCount = ~~(this.triangles.length * settings.quality);
  100227. var deletedTriangles = 0;
  100228. var triangleCount = this.triangles.length;
  100229. var iterationFunction = function (iteration, callback) {
  100230. setTimeout(function () {
  100231. if (iteration % 5 === 0) {
  100232. _this.updateMesh(iteration === 0);
  100233. }
  100234. for (var i = 0; i < _this.triangles.length; ++i) {
  100235. _this.triangles[i].isDirty = false;
  100236. }
  100237. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  100238. var trianglesIterator = function (i) {
  100239. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  100240. var t = _this.triangles[tIdx];
  100241. if (!t)
  100242. return;
  100243. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  100244. return;
  100245. }
  100246. for (var j = 0; j < 3; ++j) {
  100247. if (t.error[j] < threshold) {
  100248. var deleted0 = [];
  100249. var deleted1 = [];
  100250. var v0 = t.vertices[j];
  100251. var v1 = t.vertices[(j + 1) % 3];
  100252. if (v0.isBorder || v1.isBorder)
  100253. continue;
  100254. var p = BABYLON.Vector3.Zero();
  100255. var n = BABYLON.Vector3.Zero();
  100256. var uv = BABYLON.Vector2.Zero();
  100257. var color = new BABYLON.Color4(0, 0, 0, 1);
  100258. _this.calculateError(v0, v1, p, n, uv, color);
  100259. var delTr = new Array();
  100260. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  100261. continue;
  100262. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  100263. continue;
  100264. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  100265. continue;
  100266. var uniqueArray = new Array();
  100267. delTr.forEach(function (deletedT) {
  100268. if (uniqueArray.indexOf(deletedT) === -1) {
  100269. deletedT.deletePending = true;
  100270. uniqueArray.push(deletedT);
  100271. }
  100272. });
  100273. if (uniqueArray.length % 2 !== 0) {
  100274. continue;
  100275. }
  100276. v0.q = v1.q.add(v0.q);
  100277. v0.updatePosition(p);
  100278. var tStart = _this.references.length;
  100279. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  100280. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  100281. var tCount = _this.references.length - tStart;
  100282. if (tCount <= v0.triangleCount) {
  100283. if (tCount) {
  100284. for (var c = 0; c < tCount; c++) {
  100285. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  100286. }
  100287. }
  100288. }
  100289. else {
  100290. v0.triangleStart = tStart;
  100291. }
  100292. v0.triangleCount = tCount;
  100293. break;
  100294. }
  100295. }
  100296. };
  100297. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  100298. }, 0);
  100299. };
  100300. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  100301. if (triangleCount - deletedTriangles <= targetCount)
  100302. loop.breakLoop();
  100303. else {
  100304. iterationFunction(loop.index, function () {
  100305. loop.executeNext();
  100306. });
  100307. }
  100308. }, function () {
  100309. setTimeout(function () {
  100310. //reconstruct this part of the mesh
  100311. _this.reconstructMesh(submeshIndex);
  100312. successCallback();
  100313. }, 0);
  100314. });
  100315. };
  100316. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  100317. var _this = this;
  100318. this.vertices = [];
  100319. this.triangles = [];
  100320. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100321. var indices = this._mesh.getIndices();
  100322. var submesh = this._mesh.subMeshes[submeshIndex];
  100323. var findInVertices = function (positionToSearch) {
  100324. if (optimizeMesh) {
  100325. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  100326. if (_this.vertices[ii].position.equals(positionToSearch)) {
  100327. return _this.vertices[ii];
  100328. }
  100329. }
  100330. }
  100331. return null;
  100332. };
  100333. var vertexReferences = [];
  100334. var vertexInit = function (i) {
  100335. if (!positionData) {
  100336. return;
  100337. }
  100338. var offset = i + submesh.verticesStart;
  100339. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  100340. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  100341. vertex.originalOffsets.push(offset);
  100342. if (vertex.id === _this.vertices.length) {
  100343. _this.vertices.push(vertex);
  100344. }
  100345. vertexReferences.push(vertex.id);
  100346. };
  100347. //var totalVertices = mesh.getTotalVertices();
  100348. var totalVertices = submesh.verticesCount;
  100349. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  100350. var indicesInit = function (i) {
  100351. if (!indices) {
  100352. return;
  100353. }
  100354. var offset = (submesh.indexStart / 3) + i;
  100355. var pos = (offset * 3);
  100356. var i0 = indices[pos + 0];
  100357. var i1 = indices[pos + 1];
  100358. var i2 = indices[pos + 2];
  100359. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  100360. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  100361. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  100362. var triangle = new DecimationTriangle([v0, v1, v2]);
  100363. triangle.originalOffset = pos;
  100364. _this.triangles.push(triangle);
  100365. };
  100366. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  100367. _this.init(callback);
  100368. });
  100369. });
  100370. };
  100371. QuadraticErrorSimplification.prototype.init = function (callback) {
  100372. var _this = this;
  100373. var triangleInit1 = function (i) {
  100374. var t = _this.triangles[i];
  100375. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  100376. for (var j = 0; j < 3; j++) {
  100377. 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))));
  100378. }
  100379. };
  100380. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  100381. var triangleInit2 = function (i) {
  100382. var t = _this.triangles[i];
  100383. for (var j = 0; j < 3; ++j) {
  100384. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  100385. }
  100386. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100387. };
  100388. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  100389. callback();
  100390. });
  100391. });
  100392. };
  100393. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  100394. var newTriangles = [];
  100395. var i;
  100396. for (i = 0; i < this.vertices.length; ++i) {
  100397. this.vertices[i].triangleCount = 0;
  100398. }
  100399. var t;
  100400. var j;
  100401. for (i = 0; i < this.triangles.length; ++i) {
  100402. if (!this.triangles[i].deleted) {
  100403. t = this.triangles[i];
  100404. for (j = 0; j < 3; ++j) {
  100405. t.vertices[j].triangleCount = 1;
  100406. }
  100407. newTriangles.push(t);
  100408. }
  100409. }
  100410. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  100411. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  100412. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  100413. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  100414. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  100415. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  100416. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  100417. var vertexCount = 0;
  100418. for (i = 0; i < this.vertices.length; ++i) {
  100419. var vertex = this.vertices[i];
  100420. vertex.id = vertexCount;
  100421. if (vertex.triangleCount) {
  100422. vertex.originalOffsets.forEach(function (originalOffset) {
  100423. if (!normalData) {
  100424. return;
  100425. }
  100426. newPositionData.push(vertex.position.x);
  100427. newPositionData.push(vertex.position.y);
  100428. newPositionData.push(vertex.position.z);
  100429. newNormalData.push(normalData[originalOffset * 3]);
  100430. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  100431. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  100432. if (uvs && uvs.length) {
  100433. newUVsData.push(uvs[(originalOffset * 2)]);
  100434. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  100435. }
  100436. else if (colorsData && colorsData.length) {
  100437. newColorsData.push(colorsData[(originalOffset * 4)]);
  100438. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  100439. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  100440. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  100441. }
  100442. ++vertexCount;
  100443. });
  100444. }
  100445. }
  100446. var startingIndex = this._reconstructedMesh.getTotalIndices();
  100447. var startingVertex = this._reconstructedMesh.getTotalVertices();
  100448. var submeshesArray = this._reconstructedMesh.subMeshes;
  100449. this._reconstructedMesh.subMeshes = [];
  100450. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  100451. var originalIndices = this._mesh.getIndices();
  100452. for (i = 0; i < newTriangles.length; ++i) {
  100453. t = newTriangles[i]; //now get the new referencing point for each vertex
  100454. [0, 1, 2].forEach(function (idx) {
  100455. var id = originalIndices[t.originalOffset + idx];
  100456. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  100457. if (offset < 0)
  100458. offset = 0;
  100459. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  100460. });
  100461. }
  100462. //overwriting the old vertex buffers and indices.
  100463. this._reconstructedMesh.setIndices(newIndicesArray);
  100464. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  100465. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  100466. if (newUVsData.length > 0)
  100467. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  100468. if (newColorsData.length > 0)
  100469. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  100470. //create submesh
  100471. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  100472. if (submeshIndex > 0) {
  100473. this._reconstructedMesh.subMeshes = [];
  100474. submeshesArray.forEach(function (submesh) {
  100475. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  100476. });
  100477. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  100478. }
  100479. };
  100480. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  100481. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  100482. this._reconstructedMesh.material = this._mesh.material;
  100483. this._reconstructedMesh.parent = this._mesh.parent;
  100484. this._reconstructedMesh.isVisible = false;
  100485. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  100486. };
  100487. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  100488. for (var i = 0; i < vertex1.triangleCount; ++i) {
  100489. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  100490. if (t.deleted)
  100491. continue;
  100492. var s = this.references[vertex1.triangleStart + i].vertexId;
  100493. var v1 = t.vertices[(s + 1) % 3];
  100494. var v2 = t.vertices[(s + 2) % 3];
  100495. if ((v1 === vertex2 || v2 === vertex2)) {
  100496. deletedArray[i] = true;
  100497. delTr.push(t);
  100498. continue;
  100499. }
  100500. var d1 = v1.position.subtract(point);
  100501. d1 = d1.normalize();
  100502. var d2 = v2.position.subtract(point);
  100503. d2 = d2.normalize();
  100504. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  100505. return true;
  100506. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  100507. deletedArray[i] = false;
  100508. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  100509. return true;
  100510. }
  100511. return false;
  100512. };
  100513. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  100514. var newDeleted = deletedTriangles;
  100515. for (var i = 0; i < vertex.triangleCount; ++i) {
  100516. var ref = this.references[vertex.triangleStart + i];
  100517. var t = this.triangles[ref.triangleId];
  100518. if (t.deleted)
  100519. continue;
  100520. if (deletedArray[i] && t.deletePending) {
  100521. t.deleted = true;
  100522. newDeleted++;
  100523. continue;
  100524. }
  100525. t.vertices[ref.vertexId] = origVertex;
  100526. t.isDirty = true;
  100527. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  100528. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  100529. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  100530. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100531. this.references.push(ref);
  100532. }
  100533. return newDeleted;
  100534. };
  100535. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  100536. for (var i = 0; i < this.vertices.length; ++i) {
  100537. var vCount = [];
  100538. var vId = [];
  100539. var v = this.vertices[i];
  100540. var j;
  100541. for (j = 0; j < v.triangleCount; ++j) {
  100542. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  100543. for (var ii = 0; ii < 3; ii++) {
  100544. var ofs = 0;
  100545. var vv = triangle.vertices[ii];
  100546. while (ofs < vCount.length) {
  100547. if (vId[ofs] === vv.id)
  100548. break;
  100549. ++ofs;
  100550. }
  100551. if (ofs === vCount.length) {
  100552. vCount.push(1);
  100553. vId.push(vv.id);
  100554. }
  100555. else {
  100556. vCount[ofs]++;
  100557. }
  100558. }
  100559. }
  100560. for (j = 0; j < vCount.length; ++j) {
  100561. if (vCount[j] === 1) {
  100562. this.vertices[vId[j]].isBorder = true;
  100563. }
  100564. else {
  100565. this.vertices[vId[j]].isBorder = false;
  100566. }
  100567. }
  100568. }
  100569. };
  100570. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  100571. if (identifyBorders === void 0) { identifyBorders = false; }
  100572. var i;
  100573. if (!identifyBorders) {
  100574. var newTrianglesVector = [];
  100575. for (i = 0; i < this.triangles.length; ++i) {
  100576. if (!this.triangles[i].deleted) {
  100577. newTrianglesVector.push(this.triangles[i]);
  100578. }
  100579. }
  100580. this.triangles = newTrianglesVector;
  100581. }
  100582. for (i = 0; i < this.vertices.length; ++i) {
  100583. this.vertices[i].triangleCount = 0;
  100584. this.vertices[i].triangleStart = 0;
  100585. }
  100586. var t;
  100587. var j;
  100588. var v;
  100589. for (i = 0; i < this.triangles.length; ++i) {
  100590. t = this.triangles[i];
  100591. for (j = 0; j < 3; ++j) {
  100592. v = t.vertices[j];
  100593. v.triangleCount++;
  100594. }
  100595. }
  100596. var tStart = 0;
  100597. for (i = 0; i < this.vertices.length; ++i) {
  100598. this.vertices[i].triangleStart = tStart;
  100599. tStart += this.vertices[i].triangleCount;
  100600. this.vertices[i].triangleCount = 0;
  100601. }
  100602. var newReferences = new Array(this.triangles.length * 3);
  100603. for (i = 0; i < this.triangles.length; ++i) {
  100604. t = this.triangles[i];
  100605. for (j = 0; j < 3; ++j) {
  100606. v = t.vertices[j];
  100607. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  100608. v.triangleCount++;
  100609. }
  100610. }
  100611. this.references = newReferences;
  100612. if (identifyBorders) {
  100613. this.identifyBorder();
  100614. }
  100615. };
  100616. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  100617. var x = point.x;
  100618. var y = point.y;
  100619. var z = point.z;
  100620. 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
  100621. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  100622. };
  100623. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  100624. var q = vertex1.q.add(vertex2.q);
  100625. var border = vertex1.isBorder && vertex2.isBorder;
  100626. var error = 0;
  100627. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  100628. if (qDet !== 0 && !border) {
  100629. if (!pointResult) {
  100630. pointResult = BABYLON.Vector3.Zero();
  100631. }
  100632. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  100633. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  100634. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  100635. error = this.vertexError(q, pointResult);
  100636. }
  100637. else {
  100638. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  100639. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  100640. var error1 = this.vertexError(q, vertex1.position);
  100641. var error2 = this.vertexError(q, vertex2.position);
  100642. var error3 = this.vertexError(q, p3);
  100643. error = Math.min(error1, error2, error3);
  100644. if (error === error1) {
  100645. if (pointResult) {
  100646. pointResult.copyFrom(vertex1.position);
  100647. }
  100648. }
  100649. else if (error === error2) {
  100650. if (pointResult) {
  100651. pointResult.copyFrom(vertex2.position);
  100652. }
  100653. }
  100654. else {
  100655. if (pointResult) {
  100656. pointResult.copyFrom(p3);
  100657. }
  100658. }
  100659. }
  100660. return error;
  100661. };
  100662. return QuadraticErrorSimplification;
  100663. }());
  100664. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  100665. })(BABYLON || (BABYLON = {}));
  100666. //# sourceMappingURL=babylon.meshSimplification.js.map
  100667. var BABYLON;
  100668. (function (BABYLON) {
  100669. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  100670. get: function () {
  100671. if (!this._simplificationQueue) {
  100672. this._simplificationQueue = new BABYLON.SimplificationQueue();
  100673. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  100674. if (!component) {
  100675. component = new SimplicationQueueSceneComponent(this);
  100676. this._addComponent(component);
  100677. }
  100678. }
  100679. return this._simplificationQueue;
  100680. },
  100681. set: function (value) {
  100682. this._simplificationQueue = value;
  100683. },
  100684. enumerable: true,
  100685. configurable: true
  100686. });
  100687. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  100688. if (parallelProcessing === void 0) { parallelProcessing = true; }
  100689. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  100690. this.getScene().simplificationQueue.addTask({
  100691. settings: settings,
  100692. parallelProcessing: parallelProcessing,
  100693. mesh: this,
  100694. simplificationType: simplificationType,
  100695. successCallback: successCallback
  100696. });
  100697. return this;
  100698. };
  100699. /**
  100700. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  100701. * created in a scene
  100702. */
  100703. var SimplicationQueueSceneComponent = /** @class */ (function () {
  100704. /**
  100705. * Creates a new instance of the component for the given scene
  100706. * @param scene Defines the scene to register the component in
  100707. */
  100708. function SimplicationQueueSceneComponent(scene) {
  100709. /**
  100710. * The component name helpfull to identify the component in the list of scene components.
  100711. */
  100712. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  100713. this.scene = scene;
  100714. }
  100715. /**
  100716. * Registers the component in a given scene
  100717. */
  100718. SimplicationQueueSceneComponent.prototype.register = function () {
  100719. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  100720. };
  100721. /**
  100722. * Rebuilds the elements related to this component in case of
  100723. * context lost for instance.
  100724. */
  100725. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  100726. // Nothing to do for this component
  100727. };
  100728. /**
  100729. * Disposes the component and the associated ressources
  100730. */
  100731. SimplicationQueueSceneComponent.prototype.dispose = function () {
  100732. // Nothing to do for this component
  100733. };
  100734. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  100735. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  100736. this.scene._simplificationQueue.executeNext();
  100737. }
  100738. };
  100739. return SimplicationQueueSceneComponent;
  100740. }());
  100741. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  100742. })(BABYLON || (BABYLON = {}));
  100743. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  100744. var BABYLON;
  100745. (function (BABYLON) {
  100746. var MeshLODLevel = /** @class */ (function () {
  100747. function MeshLODLevel(distance, mesh) {
  100748. this.distance = distance;
  100749. this.mesh = mesh;
  100750. }
  100751. return MeshLODLevel;
  100752. }());
  100753. BABYLON.MeshLODLevel = MeshLODLevel;
  100754. })(BABYLON || (BABYLON = {}));
  100755. //# sourceMappingURL=babylon.meshLODLevel.js.map
  100756. var BABYLON;
  100757. (function (BABYLON) {
  100758. /**
  100759. * Defines the root class used to create scene optimization to use with SceneOptimizer
  100760. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100761. */
  100762. var SceneOptimization = /** @class */ (function () {
  100763. /**
  100764. * Creates the SceneOptimization object
  100765. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100766. * @param desc defines the description associated with the optimization
  100767. */
  100768. function SceneOptimization(
  100769. /**
  100770. * Defines the priority of this optimization (0 by default which means first in the list)
  100771. */
  100772. priority) {
  100773. if (priority === void 0) { priority = 0; }
  100774. this.priority = priority;
  100775. }
  100776. /**
  100777. * Gets a string describing the action executed by the current optimization
  100778. * @returns description string
  100779. */
  100780. SceneOptimization.prototype.getDescription = function () {
  100781. return "";
  100782. };
  100783. /**
  100784. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100785. * @param scene defines the current scene where to apply this optimization
  100786. * @param optimizer defines the current optimizer
  100787. * @returns true if everything that can be done was applied
  100788. */
  100789. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100790. return true;
  100791. };
  100792. ;
  100793. return SceneOptimization;
  100794. }());
  100795. BABYLON.SceneOptimization = SceneOptimization;
  100796. /**
  100797. * Defines an optimization used to reduce the size of render target textures
  100798. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100799. */
  100800. var TextureOptimization = /** @class */ (function (_super) {
  100801. __extends(TextureOptimization, _super);
  100802. /**
  100803. * Creates the TextureOptimization object
  100804. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100805. * @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
  100806. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100807. */
  100808. function TextureOptimization(
  100809. /**
  100810. * Defines the priority of this optimization (0 by default which means first in the list)
  100811. */
  100812. priority,
  100813. /**
  100814. * 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
  100815. */
  100816. maximumSize,
  100817. /**
  100818. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100819. */
  100820. step) {
  100821. if (priority === void 0) { priority = 0; }
  100822. if (maximumSize === void 0) { maximumSize = 1024; }
  100823. if (step === void 0) { step = 0.5; }
  100824. var _this = _super.call(this, priority) || this;
  100825. _this.priority = priority;
  100826. _this.maximumSize = maximumSize;
  100827. _this.step = step;
  100828. return _this;
  100829. }
  100830. /**
  100831. * Gets a string describing the action executed by the current optimization
  100832. * @returns description string
  100833. */
  100834. TextureOptimization.prototype.getDescription = function () {
  100835. return "Reducing render target texture size to " + this.maximumSize;
  100836. };
  100837. /**
  100838. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100839. * @param scene defines the current scene where to apply this optimization
  100840. * @param optimizer defines the current optimizer
  100841. * @returns true if everything that can be done was applied
  100842. */
  100843. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100844. var allDone = true;
  100845. for (var index = 0; index < scene.textures.length; index++) {
  100846. var texture = scene.textures[index];
  100847. if (!texture.canRescale || texture.getContext) {
  100848. continue;
  100849. }
  100850. var currentSize = texture.getSize();
  100851. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100852. if (maxDimension > this.maximumSize) {
  100853. texture.scale(this.step);
  100854. allDone = false;
  100855. }
  100856. }
  100857. return allDone;
  100858. };
  100859. return TextureOptimization;
  100860. }(SceneOptimization));
  100861. BABYLON.TextureOptimization = TextureOptimization;
  100862. /**
  100863. * Defines an optimization used to increase or decrease the rendering resolution
  100864. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100865. */
  100866. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100867. __extends(HardwareScalingOptimization, _super);
  100868. /**
  100869. * Creates the HardwareScalingOptimization object
  100870. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100871. * @param maximumScale defines the maximum scale to use (2 by default)
  100872. * @param step defines the step to use between two passes (0.5 by default)
  100873. */
  100874. function HardwareScalingOptimization(
  100875. /**
  100876. * Defines the priority of this optimization (0 by default which means first in the list)
  100877. */
  100878. priority,
  100879. /**
  100880. * Defines the maximum scale to use (2 by default)
  100881. */
  100882. maximumScale,
  100883. /**
  100884. * Defines the step to use between two passes (0.5 by default)
  100885. */
  100886. step) {
  100887. if (priority === void 0) { priority = 0; }
  100888. if (maximumScale === void 0) { maximumScale = 2; }
  100889. if (step === void 0) { step = 0.25; }
  100890. var _this = _super.call(this, priority) || this;
  100891. _this.priority = priority;
  100892. _this.maximumScale = maximumScale;
  100893. _this.step = step;
  100894. _this._currentScale = -1;
  100895. _this._directionOffset = 1;
  100896. return _this;
  100897. }
  100898. /**
  100899. * Gets a string describing the action executed by the current optimization
  100900. * @return description string
  100901. */
  100902. HardwareScalingOptimization.prototype.getDescription = function () {
  100903. return "Setting hardware scaling level to " + this._currentScale;
  100904. };
  100905. /**
  100906. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100907. * @param scene defines the current scene where to apply this optimization
  100908. * @param optimizer defines the current optimizer
  100909. * @returns true if everything that can be done was applied
  100910. */
  100911. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100912. if (this._currentScale === -1) {
  100913. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100914. if (this._currentScale > this.maximumScale) {
  100915. this._directionOffset = -1;
  100916. }
  100917. }
  100918. this._currentScale += this._directionOffset * this.step;
  100919. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100920. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100921. };
  100922. ;
  100923. return HardwareScalingOptimization;
  100924. }(SceneOptimization));
  100925. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100926. /**
  100927. * Defines an optimization used to remove shadows
  100928. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100929. */
  100930. var ShadowsOptimization = /** @class */ (function (_super) {
  100931. __extends(ShadowsOptimization, _super);
  100932. function ShadowsOptimization() {
  100933. return _super !== null && _super.apply(this, arguments) || this;
  100934. }
  100935. /**
  100936. * Gets a string describing the action executed by the current optimization
  100937. * @return description string
  100938. */
  100939. ShadowsOptimization.prototype.getDescription = function () {
  100940. return "Turning shadows on/off";
  100941. };
  100942. /**
  100943. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100944. * @param scene defines the current scene where to apply this optimization
  100945. * @param optimizer defines the current optimizer
  100946. * @returns true if everything that can be done was applied
  100947. */
  100948. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100949. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100950. return true;
  100951. };
  100952. ;
  100953. return ShadowsOptimization;
  100954. }(SceneOptimization));
  100955. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100956. /**
  100957. * Defines an optimization used to turn post-processes off
  100958. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100959. */
  100960. var PostProcessesOptimization = /** @class */ (function (_super) {
  100961. __extends(PostProcessesOptimization, _super);
  100962. function PostProcessesOptimization() {
  100963. return _super !== null && _super.apply(this, arguments) || this;
  100964. }
  100965. /**
  100966. * Gets a string describing the action executed by the current optimization
  100967. * @return description string
  100968. */
  100969. PostProcessesOptimization.prototype.getDescription = function () {
  100970. return "Turning post-processes on/off";
  100971. };
  100972. /**
  100973. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100974. * @param scene defines the current scene where to apply this optimization
  100975. * @param optimizer defines the current optimizer
  100976. * @returns true if everything that can be done was applied
  100977. */
  100978. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100979. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100980. return true;
  100981. };
  100982. ;
  100983. return PostProcessesOptimization;
  100984. }(SceneOptimization));
  100985. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100986. /**
  100987. * Defines an optimization used to turn lens flares off
  100988. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100989. */
  100990. var LensFlaresOptimization = /** @class */ (function (_super) {
  100991. __extends(LensFlaresOptimization, _super);
  100992. function LensFlaresOptimization() {
  100993. return _super !== null && _super.apply(this, arguments) || this;
  100994. }
  100995. /**
  100996. * Gets a string describing the action executed by the current optimization
  100997. * @return description string
  100998. */
  100999. LensFlaresOptimization.prototype.getDescription = function () {
  101000. return "Turning lens flares on/off";
  101001. };
  101002. /**
  101003. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101004. * @param scene defines the current scene where to apply this optimization
  101005. * @param optimizer defines the current optimizer
  101006. * @returns true if everything that can be done was applied
  101007. */
  101008. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  101009. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  101010. return true;
  101011. };
  101012. ;
  101013. return LensFlaresOptimization;
  101014. }(SceneOptimization));
  101015. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  101016. /**
  101017. * Defines an optimization based on user defined callback.
  101018. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101019. */
  101020. var CustomOptimization = /** @class */ (function (_super) {
  101021. __extends(CustomOptimization, _super);
  101022. function CustomOptimization() {
  101023. return _super !== null && _super.apply(this, arguments) || this;
  101024. }
  101025. /**
  101026. * Gets a string describing the action executed by the current optimization
  101027. * @returns description string
  101028. */
  101029. CustomOptimization.prototype.getDescription = function () {
  101030. if (this.onGetDescription) {
  101031. return this.onGetDescription();
  101032. }
  101033. return "Running user defined callback";
  101034. };
  101035. /**
  101036. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101037. * @param scene defines the current scene where to apply this optimization
  101038. * @param optimizer defines the current optimizer
  101039. * @returns true if everything that can be done was applied
  101040. */
  101041. CustomOptimization.prototype.apply = function (scene, optimizer) {
  101042. if (this.onApply) {
  101043. return this.onApply(scene, optimizer);
  101044. }
  101045. return true;
  101046. };
  101047. ;
  101048. return CustomOptimization;
  101049. }(SceneOptimization));
  101050. BABYLON.CustomOptimization = CustomOptimization;
  101051. /**
  101052. * Defines an optimization used to turn particles off
  101053. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101054. */
  101055. var ParticlesOptimization = /** @class */ (function (_super) {
  101056. __extends(ParticlesOptimization, _super);
  101057. function ParticlesOptimization() {
  101058. return _super !== null && _super.apply(this, arguments) || this;
  101059. }
  101060. /**
  101061. * Gets a string describing the action executed by the current optimization
  101062. * @return description string
  101063. */
  101064. ParticlesOptimization.prototype.getDescription = function () {
  101065. return "Turning particles on/off";
  101066. };
  101067. /**
  101068. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101069. * @param scene defines the current scene where to apply this optimization
  101070. * @param optimizer defines the current optimizer
  101071. * @returns true if everything that can be done was applied
  101072. */
  101073. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  101074. scene.particlesEnabled = optimizer.isInImprovementMode;
  101075. return true;
  101076. };
  101077. ;
  101078. return ParticlesOptimization;
  101079. }(SceneOptimization));
  101080. BABYLON.ParticlesOptimization = ParticlesOptimization;
  101081. /**
  101082. * Defines an optimization used to turn render targets off
  101083. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101084. */
  101085. var RenderTargetsOptimization = /** @class */ (function (_super) {
  101086. __extends(RenderTargetsOptimization, _super);
  101087. function RenderTargetsOptimization() {
  101088. return _super !== null && _super.apply(this, arguments) || this;
  101089. }
  101090. /**
  101091. * Gets a string describing the action executed by the current optimization
  101092. * @return description string
  101093. */
  101094. RenderTargetsOptimization.prototype.getDescription = function () {
  101095. return "Turning render targets off";
  101096. };
  101097. /**
  101098. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101099. * @param scene defines the current scene where to apply this optimization
  101100. * @param optimizer defines the current optimizer
  101101. * @returns true if everything that can be done was applied
  101102. */
  101103. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  101104. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  101105. return true;
  101106. };
  101107. ;
  101108. return RenderTargetsOptimization;
  101109. }(SceneOptimization));
  101110. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  101111. /**
  101112. * Defines an optimization used to merge meshes with compatible materials
  101113. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101114. */
  101115. var MergeMeshesOptimization = /** @class */ (function (_super) {
  101116. __extends(MergeMeshesOptimization, _super);
  101117. function MergeMeshesOptimization() {
  101118. var _this = _super !== null && _super.apply(this, arguments) || this;
  101119. _this._canBeMerged = function (abstractMesh) {
  101120. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  101121. return false;
  101122. }
  101123. var mesh = abstractMesh;
  101124. if (mesh.isDisposed()) {
  101125. return false;
  101126. }
  101127. if (!mesh.isVisible || !mesh.isEnabled()) {
  101128. return false;
  101129. }
  101130. if (mesh.instances.length > 0) {
  101131. return false;
  101132. }
  101133. if (mesh.skeleton || mesh.hasLODLevels) {
  101134. return false;
  101135. }
  101136. return true;
  101137. };
  101138. return _this;
  101139. }
  101140. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  101141. /**
  101142. * Gets or sets a boolean which defines if optimization octree has to be updated
  101143. */
  101144. get: function () {
  101145. return MergeMeshesOptimization._UpdateSelectionTree;
  101146. },
  101147. /**
  101148. * Gets or sets a boolean which defines if optimization octree has to be updated
  101149. */
  101150. set: function (value) {
  101151. MergeMeshesOptimization._UpdateSelectionTree = value;
  101152. },
  101153. enumerable: true,
  101154. configurable: true
  101155. });
  101156. /**
  101157. * Gets a string describing the action executed by the current optimization
  101158. * @return description string
  101159. */
  101160. MergeMeshesOptimization.prototype.getDescription = function () {
  101161. return "Merging similar meshes together";
  101162. };
  101163. /**
  101164. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  101165. * @param scene defines the current scene where to apply this optimization
  101166. * @param optimizer defines the current optimizer
  101167. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  101168. * @returns true if everything that can be done was applied
  101169. */
  101170. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  101171. var globalPool = scene.meshes.slice(0);
  101172. var globalLength = globalPool.length;
  101173. for (var index = 0; index < globalLength; index++) {
  101174. var currentPool = new Array();
  101175. var current = globalPool[index];
  101176. // Checks
  101177. if (!this._canBeMerged(current)) {
  101178. continue;
  101179. }
  101180. currentPool.push(current);
  101181. // Find compatible meshes
  101182. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  101183. var otherMesh = globalPool[subIndex];
  101184. if (!this._canBeMerged(otherMesh)) {
  101185. continue;
  101186. }
  101187. if (otherMesh.material !== current.material) {
  101188. continue;
  101189. }
  101190. if (otherMesh.checkCollisions !== current.checkCollisions) {
  101191. continue;
  101192. }
  101193. currentPool.push(otherMesh);
  101194. globalLength--;
  101195. globalPool.splice(subIndex, 1);
  101196. subIndex--;
  101197. }
  101198. if (currentPool.length < 2) {
  101199. continue;
  101200. }
  101201. // Merge meshes
  101202. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  101203. }
  101204. // Call the octree system optimization if it is defined.
  101205. var sceneAsAny = scene;
  101206. if (sceneAsAny.createOrUpdateSelectionOctree) {
  101207. if (updateSelectionTree != undefined) {
  101208. if (updateSelectionTree) {
  101209. sceneAsAny.createOrUpdateSelectionOctree();
  101210. }
  101211. }
  101212. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  101213. sceneAsAny.createOrUpdateSelectionOctree();
  101214. }
  101215. }
  101216. return true;
  101217. };
  101218. ;
  101219. MergeMeshesOptimization._UpdateSelectionTree = false;
  101220. return MergeMeshesOptimization;
  101221. }(SceneOptimization));
  101222. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  101223. /**
  101224. * Defines a list of options used by SceneOptimizer
  101225. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101226. */
  101227. var SceneOptimizerOptions = /** @class */ (function () {
  101228. /**
  101229. * Creates a new list of options used by SceneOptimizer
  101230. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  101231. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  101232. */
  101233. function SceneOptimizerOptions(
  101234. /**
  101235. * Defines the target frame rate to reach (60 by default)
  101236. */
  101237. targetFrameRate,
  101238. /**
  101239. * Defines the interval between two checkes (2000ms by default)
  101240. */
  101241. trackerDuration) {
  101242. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  101243. if (trackerDuration === void 0) { trackerDuration = 2000; }
  101244. this.targetFrameRate = targetFrameRate;
  101245. this.trackerDuration = trackerDuration;
  101246. /**
  101247. * Gets the list of optimizations to apply
  101248. */
  101249. this.optimizations = new Array();
  101250. }
  101251. /**
  101252. * Add a new optimization
  101253. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  101254. * @returns the current SceneOptimizerOptions
  101255. */
  101256. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  101257. this.optimizations.push(optimization);
  101258. return this;
  101259. };
  101260. /**
  101261. * Add a new custom optimization
  101262. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  101263. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  101264. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  101265. * @returns the current SceneOptimizerOptions
  101266. */
  101267. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  101268. if (priority === void 0) { priority = 0; }
  101269. var optimization = new CustomOptimization(priority);
  101270. optimization.onApply = onApply;
  101271. optimization.onGetDescription = onGetDescription;
  101272. this.optimizations.push(optimization);
  101273. return this;
  101274. };
  101275. /**
  101276. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  101277. * @param targetFrameRate defines the target frame rate (60 by default)
  101278. * @returns a SceneOptimizerOptions object
  101279. */
  101280. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  101281. var result = new SceneOptimizerOptions(targetFrameRate);
  101282. var priority = 0;
  101283. result.addOptimization(new MergeMeshesOptimization(priority));
  101284. result.addOptimization(new ShadowsOptimization(priority));
  101285. result.addOptimization(new LensFlaresOptimization(priority));
  101286. // Next priority
  101287. priority++;
  101288. result.addOptimization(new PostProcessesOptimization(priority));
  101289. result.addOptimization(new ParticlesOptimization(priority));
  101290. // Next priority
  101291. priority++;
  101292. result.addOptimization(new TextureOptimization(priority, 1024));
  101293. return result;
  101294. };
  101295. /**
  101296. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  101297. * @param targetFrameRate defines the target frame rate (60 by default)
  101298. * @returns a SceneOptimizerOptions object
  101299. */
  101300. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  101301. var result = new SceneOptimizerOptions(targetFrameRate);
  101302. var priority = 0;
  101303. result.addOptimization(new MergeMeshesOptimization(priority));
  101304. result.addOptimization(new ShadowsOptimization(priority));
  101305. result.addOptimization(new LensFlaresOptimization(priority));
  101306. // Next priority
  101307. priority++;
  101308. result.addOptimization(new PostProcessesOptimization(priority));
  101309. result.addOptimization(new ParticlesOptimization(priority));
  101310. // Next priority
  101311. priority++;
  101312. result.addOptimization(new TextureOptimization(priority, 512));
  101313. // Next priority
  101314. priority++;
  101315. result.addOptimization(new RenderTargetsOptimization(priority));
  101316. // Next priority
  101317. priority++;
  101318. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  101319. return result;
  101320. };
  101321. /**
  101322. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  101323. * @param targetFrameRate defines the target frame rate (60 by default)
  101324. * @returns a SceneOptimizerOptions object
  101325. */
  101326. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  101327. var result = new SceneOptimizerOptions(targetFrameRate);
  101328. var priority = 0;
  101329. result.addOptimization(new MergeMeshesOptimization(priority));
  101330. result.addOptimization(new ShadowsOptimization(priority));
  101331. result.addOptimization(new LensFlaresOptimization(priority));
  101332. // Next priority
  101333. priority++;
  101334. result.addOptimization(new PostProcessesOptimization(priority));
  101335. result.addOptimization(new ParticlesOptimization(priority));
  101336. // Next priority
  101337. priority++;
  101338. result.addOptimization(new TextureOptimization(priority, 256));
  101339. // Next priority
  101340. priority++;
  101341. result.addOptimization(new RenderTargetsOptimization(priority));
  101342. // Next priority
  101343. priority++;
  101344. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  101345. return result;
  101346. };
  101347. return SceneOptimizerOptions;
  101348. }());
  101349. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  101350. /**
  101351. * Class used to run optimizations in order to reach a target frame rate
  101352. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101353. */
  101354. var SceneOptimizer = /** @class */ (function () {
  101355. /**
  101356. * Creates a new SceneOptimizer
  101357. * @param scene defines the scene to work on
  101358. * @param options defines the options to use with the SceneOptimizer
  101359. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  101360. * @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)
  101361. */
  101362. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  101363. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  101364. if (improvementMode === void 0) { improvementMode = false; }
  101365. var _this = this;
  101366. this._isRunning = false;
  101367. this._currentPriorityLevel = 0;
  101368. this._targetFrameRate = 60;
  101369. this._trackerDuration = 2000;
  101370. this._currentFrameRate = 0;
  101371. this._improvementMode = false;
  101372. /**
  101373. * Defines an observable called when the optimizer reaches the target frame rate
  101374. */
  101375. this.onSuccessObservable = new BABYLON.Observable();
  101376. /**
  101377. * Defines an observable called when the optimizer enables an optimization
  101378. */
  101379. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  101380. /**
  101381. * Defines an observable called when the optimizer is not able to reach the target frame rate
  101382. */
  101383. this.onFailureObservable = new BABYLON.Observable();
  101384. if (!options) {
  101385. this._options = new SceneOptimizerOptions();
  101386. }
  101387. else {
  101388. this._options = options;
  101389. }
  101390. if (this._options.targetFrameRate) {
  101391. this._targetFrameRate = this._options.targetFrameRate;
  101392. }
  101393. if (this._options.trackerDuration) {
  101394. this._trackerDuration = this._options.trackerDuration;
  101395. }
  101396. if (autoGeneratePriorities) {
  101397. var priority = 0;
  101398. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  101399. var optim = _a[_i];
  101400. optim.priority = priority++;
  101401. }
  101402. }
  101403. this._improvementMode = improvementMode;
  101404. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101405. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  101406. _this._sceneDisposeObserver = null;
  101407. _this.dispose();
  101408. });
  101409. }
  101410. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  101411. /**
  101412. * Gets a boolean indicating if the optimizer is in improvement mode
  101413. */
  101414. get: function () {
  101415. return this._improvementMode;
  101416. },
  101417. enumerable: true,
  101418. configurable: true
  101419. });
  101420. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  101421. /**
  101422. * Gets the current priority level (0 at start)
  101423. */
  101424. get: function () {
  101425. return this._currentPriorityLevel;
  101426. },
  101427. enumerable: true,
  101428. configurable: true
  101429. });
  101430. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  101431. /**
  101432. * Gets the current frame rate checked by the SceneOptimizer
  101433. */
  101434. get: function () {
  101435. return this._currentFrameRate;
  101436. },
  101437. enumerable: true,
  101438. configurable: true
  101439. });
  101440. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  101441. /**
  101442. * Gets or sets the current target frame rate (60 by default)
  101443. */
  101444. get: function () {
  101445. return this._targetFrameRate;
  101446. },
  101447. /**
  101448. * Gets or sets the current target frame rate (60 by default)
  101449. */
  101450. set: function (value) {
  101451. this._targetFrameRate = value;
  101452. },
  101453. enumerable: true,
  101454. configurable: true
  101455. });
  101456. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  101457. /**
  101458. * Gets or sets the current interval between two checks (every 2000ms by default)
  101459. */
  101460. get: function () {
  101461. return this._trackerDuration;
  101462. },
  101463. /**
  101464. * Gets or sets the current interval between two checks (every 2000ms by default)
  101465. */
  101466. set: function (value) {
  101467. this._trackerDuration = value;
  101468. },
  101469. enumerable: true,
  101470. configurable: true
  101471. });
  101472. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  101473. /**
  101474. * Gets the list of active optimizations
  101475. */
  101476. get: function () {
  101477. return this._options.optimizations;
  101478. },
  101479. enumerable: true,
  101480. configurable: true
  101481. });
  101482. /**
  101483. * Stops the current optimizer
  101484. */
  101485. SceneOptimizer.prototype.stop = function () {
  101486. this._isRunning = false;
  101487. };
  101488. /**
  101489. * Reset the optimizer to initial step (current priority level = 0)
  101490. */
  101491. SceneOptimizer.prototype.reset = function () {
  101492. this._currentPriorityLevel = 0;
  101493. };
  101494. /**
  101495. * Start the optimizer. By default it will try to reach a specific framerate
  101496. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  101497. */
  101498. SceneOptimizer.prototype.start = function () {
  101499. var _this = this;
  101500. if (this._isRunning) {
  101501. return;
  101502. }
  101503. this._isRunning = true;
  101504. // Let's wait for the scene to be ready before running our check
  101505. this._scene.executeWhenReady(function () {
  101506. setTimeout(function () {
  101507. _this._checkCurrentState();
  101508. }, _this._trackerDuration);
  101509. });
  101510. };
  101511. SceneOptimizer.prototype._checkCurrentState = function () {
  101512. var _this = this;
  101513. if (!this._isRunning) {
  101514. return;
  101515. }
  101516. var scene = this._scene;
  101517. var options = this._options;
  101518. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  101519. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  101520. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  101521. this._isRunning = false;
  101522. this.onSuccessObservable.notifyObservers(this);
  101523. return;
  101524. }
  101525. // Apply current level of optimizations
  101526. var allDone = true;
  101527. var noOptimizationApplied = true;
  101528. for (var index = 0; index < options.optimizations.length; index++) {
  101529. var optimization = options.optimizations[index];
  101530. if (optimization.priority === this._currentPriorityLevel) {
  101531. noOptimizationApplied = false;
  101532. allDone = allDone && optimization.apply(scene, this);
  101533. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  101534. }
  101535. }
  101536. // If no optimization was applied, this is a failure :(
  101537. if (noOptimizationApplied) {
  101538. this._isRunning = false;
  101539. this.onFailureObservable.notifyObservers(this);
  101540. return;
  101541. }
  101542. // If all optimizations were done, move to next level
  101543. if (allDone) {
  101544. this._currentPriorityLevel++;
  101545. }
  101546. // Let's the system running for a specific amount of time before checking FPS
  101547. scene.executeWhenReady(function () {
  101548. setTimeout(function () {
  101549. _this._checkCurrentState();
  101550. }, _this._trackerDuration);
  101551. });
  101552. };
  101553. /**
  101554. * Release all resources
  101555. */
  101556. SceneOptimizer.prototype.dispose = function () {
  101557. this.stop();
  101558. this.onSuccessObservable.clear();
  101559. this.onFailureObservable.clear();
  101560. this.onNewOptimizationAppliedObservable.clear();
  101561. if (this._sceneDisposeObserver) {
  101562. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101563. }
  101564. };
  101565. /**
  101566. * Helper function to create a SceneOptimizer with one single line of code
  101567. * @param scene defines the scene to work on
  101568. * @param options defines the options to use with the SceneOptimizer
  101569. * @param onSuccess defines a callback to call on success
  101570. * @param onFailure defines a callback to call on failure
  101571. * @returns the new SceneOptimizer object
  101572. */
  101573. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  101574. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  101575. if (onSuccess) {
  101576. optimizer.onSuccessObservable.add(function () {
  101577. onSuccess();
  101578. });
  101579. }
  101580. if (onFailure) {
  101581. optimizer.onFailureObservable.add(function () {
  101582. onFailure();
  101583. });
  101584. }
  101585. optimizer.start();
  101586. return optimizer;
  101587. };
  101588. return SceneOptimizer;
  101589. }());
  101590. BABYLON.SceneOptimizer = SceneOptimizer;
  101591. })(BABYLON || (BABYLON = {}));
  101592. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  101593. var BABYLON;
  101594. (function (BABYLON) {
  101595. /**
  101596. * Gets the outline renderer associated with the scene
  101597. * @returns a OutlineRenderer
  101598. */
  101599. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  101600. if (!this._outlineRenderer) {
  101601. this._outlineRenderer = new OutlineRenderer(this);
  101602. }
  101603. return this._outlineRenderer;
  101604. };
  101605. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  101606. get: function () {
  101607. return this._renderOutline;
  101608. },
  101609. set: function (value) {
  101610. if (value) {
  101611. // Lazy Load the component.
  101612. this.getScene().getOutlineRenderer();
  101613. }
  101614. this._renderOutline = value;
  101615. },
  101616. enumerable: true,
  101617. configurable: true
  101618. });
  101619. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  101620. get: function () {
  101621. return this._renderOverlay;
  101622. },
  101623. set: function (value) {
  101624. if (value) {
  101625. // Lazy Load the component.
  101626. this.getScene().getOutlineRenderer();
  101627. }
  101628. this._renderOverlay = value;
  101629. },
  101630. enumerable: true,
  101631. configurable: true
  101632. });
  101633. /**
  101634. * This class is responsible to draw bothe outline/overlay of meshes.
  101635. * It should not be used directly but through the available method on mesh.
  101636. */
  101637. var OutlineRenderer = /** @class */ (function () {
  101638. /**
  101639. * Instantiates a new outline renderer. (There could be only one per scene).
  101640. * @param scene Defines the scene it belongs to
  101641. */
  101642. function OutlineRenderer(scene) {
  101643. /**
  101644. * The name of the component. Each component must have a unique name.
  101645. */
  101646. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  101647. /**
  101648. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  101649. */
  101650. this.zOffset = 1;
  101651. this.scene = scene;
  101652. this._engine = scene.getEngine();
  101653. this.scene._addComponent(this);
  101654. }
  101655. /**
  101656. * Register the component to one instance of a scene.
  101657. */
  101658. OutlineRenderer.prototype.register = function () {
  101659. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  101660. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  101661. };
  101662. /**
  101663. * Rebuilds the elements related to this component in case of
  101664. * context lost for instance.
  101665. */
  101666. OutlineRenderer.prototype.rebuild = function () {
  101667. // Nothing to do here.
  101668. };
  101669. /**
  101670. * Disposes the component and the associated ressources.
  101671. */
  101672. OutlineRenderer.prototype.dispose = function () {
  101673. // Nothing to do here.
  101674. };
  101675. /**
  101676. * Renders the outline in the canvas.
  101677. * @param subMesh Defines the sumesh to render
  101678. * @param batch Defines the batch of meshes in case of instances
  101679. * @param useOverlay Defines if the rendering is for the overlay or the outline
  101680. */
  101681. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  101682. var _this = this;
  101683. if (useOverlay === void 0) { useOverlay = false; }
  101684. var scene = this.scene;
  101685. var engine = scene.getEngine();
  101686. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101687. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  101688. return;
  101689. }
  101690. var mesh = subMesh.getRenderingMesh();
  101691. var material = subMesh.getMaterial();
  101692. if (!material || !scene.activeCamera) {
  101693. return;
  101694. }
  101695. engine.enableEffect(this._effect);
  101696. // Logarithmic depth
  101697. if (material.useLogarithmicDepth) {
  101698. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  101699. }
  101700. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  101701. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  101702. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  101703. // Bones
  101704. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101705. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101706. }
  101707. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  101708. // Alpha test
  101709. if (material && material.needAlphaTesting()) {
  101710. var alphaTexture = material.getAlphaTestTexture();
  101711. if (alphaTexture) {
  101712. this._effect.setTexture("diffuseSampler", alphaTexture);
  101713. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  101714. }
  101715. }
  101716. engine.setZOffset(-this.zOffset);
  101717. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  101718. engine.setZOffset(0);
  101719. };
  101720. /**
  101721. * Returns whether or not the outline renderer is ready for a given submesh.
  101722. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  101723. * @param subMesh Defines the submesh to check readyness for
  101724. * @param useInstances Defines wheter wee are trying to render instances or not
  101725. * @returns true if ready otherwise false
  101726. */
  101727. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  101728. var defines = [];
  101729. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  101730. var mesh = subMesh.getMesh();
  101731. var material = subMesh.getMaterial();
  101732. if (material) {
  101733. // Alpha test
  101734. if (material.needAlphaTesting()) {
  101735. defines.push("#define ALPHATEST");
  101736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101737. attribs.push(BABYLON.VertexBuffer.UVKind);
  101738. defines.push("#define UV1");
  101739. }
  101740. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  101741. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101742. defines.push("#define UV2");
  101743. }
  101744. }
  101745. //Logarithmic depth
  101746. if (material.useLogarithmicDepth) {
  101747. defines.push("#define LOGARITHMICDEPTH");
  101748. }
  101749. }
  101750. // Bones
  101751. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101752. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101753. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101754. if (mesh.numBoneInfluencers > 4) {
  101755. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101756. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101757. }
  101758. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101759. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  101760. }
  101761. else {
  101762. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101763. }
  101764. // Instances
  101765. if (useInstances) {
  101766. defines.push("#define INSTANCES");
  101767. attribs.push("world0");
  101768. attribs.push("world1");
  101769. attribs.push("world2");
  101770. attribs.push("world3");
  101771. }
  101772. // Get correct effect
  101773. var join = defines.join("\n");
  101774. if (this._cachedDefines !== join) {
  101775. this._cachedDefines = join;
  101776. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  101777. }
  101778. return this._effect.isReady();
  101779. };
  101780. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  101781. // Outline - step 1
  101782. this._savedDepthWrite = this._engine.getDepthWrite();
  101783. if (mesh.renderOutline) {
  101784. this._engine.setDepthWrite(false);
  101785. this.render(subMesh, batch);
  101786. this._engine.setDepthWrite(this._savedDepthWrite);
  101787. }
  101788. };
  101789. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101790. // Outline - step 2
  101791. if (mesh.renderOutline && this._savedDepthWrite) {
  101792. this._engine.setDepthWrite(true);
  101793. this._engine.setColorWrite(false);
  101794. this.render(subMesh, batch);
  101795. this._engine.setColorWrite(true);
  101796. }
  101797. // Overlay
  101798. if (mesh.renderOverlay) {
  101799. var currentMode = this._engine.getAlphaMode();
  101800. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101801. this.render(subMesh, batch, true);
  101802. this._engine.setAlphaMode(currentMode);
  101803. }
  101804. };
  101805. return OutlineRenderer;
  101806. }());
  101807. BABYLON.OutlineRenderer = OutlineRenderer;
  101808. })(BABYLON || (BABYLON = {}));
  101809. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101810. var BABYLON;
  101811. (function (BABYLON) {
  101812. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101813. if (this._edgesRenderer) {
  101814. this._edgesRenderer.dispose();
  101815. this._edgesRenderer = null;
  101816. }
  101817. return this;
  101818. };
  101819. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101820. if (epsilon === void 0) { epsilon = 0.95; }
  101821. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101822. this.disableEdgesRendering();
  101823. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101824. return this;
  101825. };
  101826. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101827. get: function () {
  101828. return this._edgesRenderer;
  101829. },
  101830. enumerable: true,
  101831. configurable: true
  101832. });
  101833. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101834. if (epsilon === void 0) { epsilon = 0.95; }
  101835. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101836. this.disableEdgesRendering();
  101837. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101838. return this;
  101839. };
  101840. /**
  101841. * FaceAdjacencies Helper class to generate edges
  101842. */
  101843. var FaceAdjacencies = /** @class */ (function () {
  101844. function FaceAdjacencies() {
  101845. this.edges = new Array();
  101846. this.edgesConnectedCount = 0;
  101847. }
  101848. return FaceAdjacencies;
  101849. }());
  101850. /**
  101851. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101852. */
  101853. var EdgesRenderer = /** @class */ (function () {
  101854. /**
  101855. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101856. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101857. * @param source Mesh used to create edges
  101858. * @param epsilon sum of angles in adjacency to check for edge
  101859. * @param checkVerticesInsteadOfIndices
  101860. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101861. */
  101862. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101863. if (epsilon === void 0) { epsilon = 0.95; }
  101864. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101865. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101866. var _this = this;
  101867. this.edgesWidthScalerForOrthographic = 1000.0;
  101868. this.edgesWidthScalerForPerspective = 50.0;
  101869. this._linesPositions = new Array();
  101870. this._linesNormals = new Array();
  101871. this._linesIndices = new Array();
  101872. this._buffers = {};
  101873. this._checkVerticesInsteadOfIndices = false;
  101874. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101875. this.isEnabled = true;
  101876. this._source = source;
  101877. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101878. this._epsilon = epsilon;
  101879. this._prepareRessources();
  101880. if (generateEdgesLines) {
  101881. this._generateEdgesLines();
  101882. }
  101883. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101884. _this._rebuild();
  101885. });
  101886. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101887. _this.dispose();
  101888. });
  101889. }
  101890. EdgesRenderer.prototype._prepareRessources = function () {
  101891. if (this._lineShader) {
  101892. return;
  101893. }
  101894. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101895. attributes: ["position", "normal"],
  101896. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101897. });
  101898. this._lineShader.disableDepthWrite = true;
  101899. this._lineShader.backFaceCulling = false;
  101900. };
  101901. /** @hidden */
  101902. EdgesRenderer.prototype._rebuild = function () {
  101903. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101904. if (buffer) {
  101905. buffer._rebuild();
  101906. }
  101907. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101908. if (buffer) {
  101909. buffer._rebuild();
  101910. }
  101911. var scene = this._source.getScene();
  101912. var engine = scene.getEngine();
  101913. this._ib = engine.createIndexBuffer(this._linesIndices);
  101914. };
  101915. /**
  101916. * Releases the required resources for the edges renderer
  101917. */
  101918. EdgesRenderer.prototype.dispose = function () {
  101919. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101920. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101921. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101922. if (buffer) {
  101923. buffer.dispose();
  101924. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101925. }
  101926. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101927. if (buffer) {
  101928. buffer.dispose();
  101929. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101930. }
  101931. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101932. this._lineShader.dispose();
  101933. };
  101934. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101935. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101936. return 0;
  101937. }
  101938. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101939. return 1;
  101940. }
  101941. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101942. return 2;
  101943. }
  101944. return -1;
  101945. };
  101946. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101947. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101948. return 0;
  101949. }
  101950. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101951. return 1;
  101952. }
  101953. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101954. return 2;
  101955. }
  101956. return -1;
  101957. };
  101958. /**
  101959. * Checks if the pair of p0 and p1 is en edge
  101960. * @param faceIndex
  101961. * @param edge
  101962. * @param faceNormals
  101963. * @param p0
  101964. * @param p1
  101965. * @private
  101966. */
  101967. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101968. var needToCreateLine;
  101969. if (edge === undefined) {
  101970. needToCreateLine = true;
  101971. }
  101972. else {
  101973. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101974. needToCreateLine = dotProduct < this._epsilon;
  101975. }
  101976. if (needToCreateLine) {
  101977. var offset = this._linesPositions.length / 3;
  101978. var normal = p0.subtract(p1);
  101979. normal.normalize();
  101980. // Positions
  101981. this._linesPositions.push(p0.x);
  101982. this._linesPositions.push(p0.y);
  101983. this._linesPositions.push(p0.z);
  101984. this._linesPositions.push(p0.x);
  101985. this._linesPositions.push(p0.y);
  101986. this._linesPositions.push(p0.z);
  101987. this._linesPositions.push(p1.x);
  101988. this._linesPositions.push(p1.y);
  101989. this._linesPositions.push(p1.z);
  101990. this._linesPositions.push(p1.x);
  101991. this._linesPositions.push(p1.y);
  101992. this._linesPositions.push(p1.z);
  101993. // Normals
  101994. this._linesNormals.push(p1.x);
  101995. this._linesNormals.push(p1.y);
  101996. this._linesNormals.push(p1.z);
  101997. this._linesNormals.push(-1);
  101998. this._linesNormals.push(p1.x);
  101999. this._linesNormals.push(p1.y);
  102000. this._linesNormals.push(p1.z);
  102001. this._linesNormals.push(1);
  102002. this._linesNormals.push(p0.x);
  102003. this._linesNormals.push(p0.y);
  102004. this._linesNormals.push(p0.z);
  102005. this._linesNormals.push(-1);
  102006. this._linesNormals.push(p0.x);
  102007. this._linesNormals.push(p0.y);
  102008. this._linesNormals.push(p0.z);
  102009. this._linesNormals.push(1);
  102010. // Indices
  102011. this._linesIndices.push(offset);
  102012. this._linesIndices.push(offset + 1);
  102013. this._linesIndices.push(offset + 2);
  102014. this._linesIndices.push(offset);
  102015. this._linesIndices.push(offset + 2);
  102016. this._linesIndices.push(offset + 3);
  102017. }
  102018. };
  102019. /**
  102020. * Generates lines edges from adjacencjes
  102021. * @private
  102022. */
  102023. EdgesRenderer.prototype._generateEdgesLines = function () {
  102024. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102025. var indices = this._source.getIndices();
  102026. if (!indices || !positions) {
  102027. return;
  102028. }
  102029. // First let's find adjacencies
  102030. var adjacencies = new Array();
  102031. var faceNormals = new Array();
  102032. var index;
  102033. var faceAdjacencies;
  102034. // Prepare faces
  102035. for (index = 0; index < indices.length; index += 3) {
  102036. faceAdjacencies = new FaceAdjacencies();
  102037. var p0Index = indices[index];
  102038. var p1Index = indices[index + 1];
  102039. var p2Index = indices[index + 2];
  102040. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  102041. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  102042. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  102043. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  102044. faceNormal.normalize();
  102045. faceNormals.push(faceNormal);
  102046. adjacencies.push(faceAdjacencies);
  102047. }
  102048. // Scan
  102049. for (index = 0; index < adjacencies.length; index++) {
  102050. faceAdjacencies = adjacencies[index];
  102051. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  102052. var otherFaceAdjacencies = adjacencies[otherIndex];
  102053. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  102054. break;
  102055. }
  102056. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  102057. continue;
  102058. }
  102059. var otherP0 = indices[otherIndex * 3];
  102060. var otherP1 = indices[otherIndex * 3 + 1];
  102061. var otherP2 = indices[otherIndex * 3 + 2];
  102062. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  102063. var otherEdgeIndex = 0;
  102064. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  102065. continue;
  102066. }
  102067. switch (edgeIndex) {
  102068. case 0:
  102069. if (this._checkVerticesInsteadOfIndices) {
  102070. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102071. }
  102072. else {
  102073. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  102074. }
  102075. break;
  102076. case 1:
  102077. if (this._checkVerticesInsteadOfIndices) {
  102078. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102079. }
  102080. else {
  102081. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  102082. }
  102083. break;
  102084. case 2:
  102085. if (this._checkVerticesInsteadOfIndices) {
  102086. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  102087. }
  102088. else {
  102089. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  102090. }
  102091. break;
  102092. }
  102093. if (otherEdgeIndex === -1) {
  102094. continue;
  102095. }
  102096. faceAdjacencies.edges[edgeIndex] = otherIndex;
  102097. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  102098. faceAdjacencies.edgesConnectedCount++;
  102099. otherFaceAdjacencies.edgesConnectedCount++;
  102100. if (faceAdjacencies.edgesConnectedCount === 3) {
  102101. break;
  102102. }
  102103. }
  102104. }
  102105. }
  102106. // Create lines
  102107. for (index = 0; index < adjacencies.length; index++) {
  102108. // 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
  102109. var current = adjacencies[index];
  102110. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  102111. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  102112. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  102113. }
  102114. // Merge into a single mesh
  102115. var engine = this._source.getScene().getEngine();
  102116. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  102117. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  102118. this._ib = engine.createIndexBuffer(this._linesIndices);
  102119. this._indicesCount = this._linesIndices.length;
  102120. };
  102121. /**
  102122. * Checks wether or not the edges renderer is ready to render.
  102123. * @return true if ready, otherwise false.
  102124. */
  102125. EdgesRenderer.prototype.isReady = function () {
  102126. return this._lineShader.isReady();
  102127. };
  102128. /**
  102129. * Renders the edges of the attached mesh,
  102130. */
  102131. EdgesRenderer.prototype.render = function () {
  102132. var scene = this._source.getScene();
  102133. if (!this.isReady() || !scene.activeCamera) {
  102134. return;
  102135. }
  102136. var engine = scene.getEngine();
  102137. this._lineShader._preBind();
  102138. if (this._source.edgesColor.a !== 1) {
  102139. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  102140. }
  102141. else {
  102142. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102143. }
  102144. // VBOs
  102145. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  102146. scene.resetCachedMaterial();
  102147. this._lineShader.setColor4("color", this._source.edgesColor);
  102148. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  102149. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  102150. }
  102151. else {
  102152. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  102153. }
  102154. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  102155. this._lineShader.bind(this._source.getWorldMatrix());
  102156. // Draw order
  102157. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  102158. this._lineShader.unbind();
  102159. };
  102160. return EdgesRenderer;
  102161. }());
  102162. BABYLON.EdgesRenderer = EdgesRenderer;
  102163. })(BABYLON || (BABYLON = {}));
  102164. //# sourceMappingURL=babylon.edgesRenderer.js.map
  102165. var BABYLON;
  102166. (function (BABYLON) {
  102167. /**
  102168. * FaceAdjacencies Helper class to generate edges
  102169. */
  102170. var FaceAdjacencies = /** @class */ (function () {
  102171. function FaceAdjacencies() {
  102172. this.edges = new Array();
  102173. this.edgesConnectedCount = 0;
  102174. }
  102175. return FaceAdjacencies;
  102176. }());
  102177. /**
  102178. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  102179. */
  102180. var LineEdgesRenderer = /** @class */ (function (_super) {
  102181. __extends(LineEdgesRenderer, _super);
  102182. /**
  102183. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  102184. * @param source LineMesh used to generate edges
  102185. * @param epsilon not important (specified angle for edge detection)
  102186. * @param checkVerticesInsteadOfIndices not important for LineMesh
  102187. */
  102188. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  102189. if (epsilon === void 0) { epsilon = 0.95; }
  102190. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  102191. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  102192. _this._generateEdgesLines();
  102193. return _this;
  102194. }
  102195. /**
  102196. * Always create the edge since its a line so only important things are p0 and p1
  102197. * @param faceIndex not important for LineMesh
  102198. * @param edge not important for LineMesh
  102199. * @param faceNormals not important for LineMesh
  102200. * @param p0 beginnig of line
  102201. * @param p1 end of line
  102202. */
  102203. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  102204. var offset = this._linesPositions.length / 3;
  102205. var normal = p0.subtract(p1);
  102206. normal.normalize();
  102207. // Positions
  102208. this._linesPositions.push(p0.x);
  102209. this._linesPositions.push(p0.y);
  102210. this._linesPositions.push(p0.z);
  102211. this._linesPositions.push(p0.x);
  102212. this._linesPositions.push(p0.y);
  102213. this._linesPositions.push(p0.z);
  102214. this._linesPositions.push(p1.x);
  102215. this._linesPositions.push(p1.y);
  102216. this._linesPositions.push(p1.z);
  102217. this._linesPositions.push(p1.x);
  102218. this._linesPositions.push(p1.y);
  102219. this._linesPositions.push(p1.z);
  102220. // Normals
  102221. this._linesNormals.push(p1.x);
  102222. this._linesNormals.push(p1.y);
  102223. this._linesNormals.push(p1.z);
  102224. this._linesNormals.push(-1);
  102225. this._linesNormals.push(p1.x);
  102226. this._linesNormals.push(p1.y);
  102227. this._linesNormals.push(p1.z);
  102228. this._linesNormals.push(1);
  102229. this._linesNormals.push(p0.x);
  102230. this._linesNormals.push(p0.y);
  102231. this._linesNormals.push(p0.z);
  102232. this._linesNormals.push(-1);
  102233. this._linesNormals.push(p0.x);
  102234. this._linesNormals.push(p0.y);
  102235. this._linesNormals.push(p0.z);
  102236. this._linesNormals.push(1);
  102237. // Indices
  102238. this._linesIndices.push(offset);
  102239. this._linesIndices.push(offset + 1);
  102240. this._linesIndices.push(offset + 2);
  102241. this._linesIndices.push(offset);
  102242. this._linesIndices.push(offset + 2);
  102243. this._linesIndices.push(offset + 3);
  102244. };
  102245. /**
  102246. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  102247. */
  102248. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  102249. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102250. var indices = this._source.getIndices();
  102251. if (!indices || !positions) {
  102252. return;
  102253. }
  102254. // First let's find adjacencies
  102255. var adjacencies = new Array();
  102256. var faceNormals = new Array();
  102257. var index;
  102258. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  102259. var currentAdjecancy = new FaceAdjacencies();
  102260. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  102261. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  102262. adjacencies.push(currentAdjecancy);
  102263. }
  102264. // Create lines
  102265. for (index = 0; index < adjacencies.length; index++) {
  102266. // 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
  102267. var current = adjacencies[index];
  102268. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  102269. }
  102270. // Merge into a single mesh
  102271. var engine = this._source.getScene().getEngine();
  102272. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  102273. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  102274. this._ib = engine.createIndexBuffer(this._linesIndices);
  102275. this._indicesCount = this._linesIndices.length;
  102276. };
  102277. return LineEdgesRenderer;
  102278. }(BABYLON.EdgesRenderer));
  102279. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  102280. })(BABYLON || (BABYLON = {}));
  102281. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  102282. var BABYLON;
  102283. (function (BABYLON) {
  102284. // Adds the parser to the scene parsers.
  102285. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  102286. if (parsedData.effectLayers) {
  102287. if (!container.effectLayers) {
  102288. container.effectLayers = new Array();
  102289. }
  102290. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  102291. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  102292. container.effectLayers.push(effectLayer);
  102293. }
  102294. }
  102295. });
  102296. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  102297. var index = this.effectLayers.indexOf(toRemove);
  102298. if (index !== -1) {
  102299. this.effectLayers.splice(index, 1);
  102300. }
  102301. return index;
  102302. };
  102303. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  102304. this.effectLayers.push(newEffectLayer);
  102305. };
  102306. /**
  102307. * Defines the layer scene component responsible to manage any effect layers
  102308. * in a given scene.
  102309. */
  102310. var EffectLayerSceneComponent = /** @class */ (function () {
  102311. /**
  102312. * Creates a new instance of the component for the given scene
  102313. * @param scene Defines the scene to register the component in
  102314. */
  102315. function EffectLayerSceneComponent(scene) {
  102316. /**
  102317. * The component name helpfull to identify the component in the list of scene components.
  102318. */
  102319. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  102320. this._renderEffects = false;
  102321. this._needStencil = false;
  102322. this._previousStencilState = false;
  102323. this.scene = scene;
  102324. this._engine = scene.getEngine();
  102325. scene.effectLayers = new Array();
  102326. }
  102327. /**
  102328. * Registers the component in a given scene
  102329. */
  102330. EffectLayerSceneComponent.prototype.register = function () {
  102331. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  102332. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  102333. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  102334. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  102335. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  102336. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  102337. };
  102338. /**
  102339. * Rebuilds the elements related to this component in case of
  102340. * context lost for instance.
  102341. */
  102342. EffectLayerSceneComponent.prototype.rebuild = function () {
  102343. var layers = this.scene.effectLayers;
  102344. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102345. var effectLayer = layers_1[_i];
  102346. effectLayer._rebuild();
  102347. }
  102348. };
  102349. /**
  102350. * Serializes the component data to the specified json object
  102351. * @param serializationObject The object to serialize to
  102352. */
  102353. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  102354. // Effect layers
  102355. serializationObject.effectLayers = [];
  102356. var layers = this.scene.effectLayers;
  102357. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102358. var effectLayer = layers_2[_i];
  102359. if (effectLayer.serialize) {
  102360. serializationObject.effectLayers.push(effectLayer.serialize());
  102361. }
  102362. }
  102363. };
  102364. /**
  102365. * Adds all the element from the container to the scene
  102366. * @param container the container holding the elements
  102367. */
  102368. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  102369. var _this = this;
  102370. if (!container.effectLayers) {
  102371. return;
  102372. }
  102373. container.effectLayers.forEach(function (o) {
  102374. _this.scene.addEffectLayer(o);
  102375. });
  102376. };
  102377. /**
  102378. * Removes all the elements in the container from the scene
  102379. * @param container contains the elements to remove
  102380. */
  102381. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  102382. var _this = this;
  102383. if (!container.effectLayers) {
  102384. return;
  102385. }
  102386. container.effectLayers.forEach(function (o) {
  102387. _this.scene.removeEffectLayer(o);
  102388. });
  102389. };
  102390. /**
  102391. * Disposes the component and the associated ressources.
  102392. */
  102393. EffectLayerSceneComponent.prototype.dispose = function () {
  102394. var layers = this.scene.effectLayers;
  102395. while (layers.length) {
  102396. layers[0].dispose();
  102397. }
  102398. };
  102399. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  102400. var layers = this.scene.effectLayers;
  102401. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  102402. var layer = layers_3[_i];
  102403. if (!layer.hasMesh(mesh)) {
  102404. continue;
  102405. }
  102406. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  102407. var subMesh = _b[_a];
  102408. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  102409. return false;
  102410. }
  102411. }
  102412. }
  102413. return true;
  102414. };
  102415. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  102416. this._renderEffects = false;
  102417. this._needStencil = false;
  102418. var layers = this.scene.effectLayers;
  102419. if (layers && layers.length > 0) {
  102420. this._previousStencilState = this._engine.getStencilBuffer();
  102421. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  102422. var effectLayer = layers_4[_i];
  102423. if (effectLayer.shouldRender() &&
  102424. (!effectLayer.camera ||
  102425. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  102426. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  102427. this._renderEffects = true;
  102428. this._needStencil = this._needStencil || effectLayer.needStencil();
  102429. var renderTarget = effectLayer._mainTexture;
  102430. if (renderTarget._shouldRender()) {
  102431. this.scene.incrementRenderId();
  102432. renderTarget.render(false, false);
  102433. }
  102434. }
  102435. }
  102436. this.scene.incrementRenderId();
  102437. }
  102438. };
  102439. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  102440. // Activate effect Layer stencil
  102441. if (this._needStencil) {
  102442. this._engine.setStencilBuffer(true);
  102443. }
  102444. };
  102445. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  102446. // Restore effect Layer stencil
  102447. if (this._needStencil) {
  102448. this._engine.setStencilBuffer(this._previousStencilState);
  102449. }
  102450. };
  102451. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  102452. if (this._renderEffects) {
  102453. this._engine.setDepthBuffer(false);
  102454. var layers = this.scene.effectLayers;
  102455. for (var i = 0; i < layers.length; i++) {
  102456. var effectLayer = layers[i];
  102457. if (effectLayer.renderingGroupId === renderingGroupId) {
  102458. if (effectLayer.shouldRender()) {
  102459. effectLayer.render();
  102460. }
  102461. }
  102462. }
  102463. this._engine.setDepthBuffer(true);
  102464. }
  102465. };
  102466. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  102467. if (this._renderEffects) {
  102468. this._draw(-1);
  102469. }
  102470. };
  102471. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  102472. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  102473. this._draw(index);
  102474. }
  102475. };
  102476. return EffectLayerSceneComponent;
  102477. }());
  102478. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  102479. })(BABYLON || (BABYLON = {}));
  102480. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  102481. var __assign = (this && this.__assign) || function () {
  102482. __assign = Object.assign || function(t) {
  102483. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102484. s = arguments[i];
  102485. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102486. t[p] = s[p];
  102487. }
  102488. return t;
  102489. };
  102490. return __assign.apply(this, arguments);
  102491. };
  102492. var BABYLON;
  102493. (function (BABYLON) {
  102494. /**
  102495. * The effect layer Helps adding post process effect blended with the main pass.
  102496. *
  102497. * This can be for instance use to generate glow or higlight effects on the scene.
  102498. *
  102499. * The effect layer class can not be used directly and is intented to inherited from to be
  102500. * customized per effects.
  102501. */
  102502. var EffectLayer = /** @class */ (function () {
  102503. /**
  102504. * Instantiates a new effect Layer and references it in the scene.
  102505. * @param name The name of the layer
  102506. * @param scene The scene to use the layer in
  102507. */
  102508. function EffectLayer(
  102509. /** The Friendly of the effect in the scene */
  102510. name, scene) {
  102511. this._vertexBuffers = {};
  102512. this._maxSize = 0;
  102513. this._mainTextureDesiredSize = { width: 0, height: 0 };
  102514. this._shouldRender = true;
  102515. this._postProcesses = [];
  102516. this._textures = [];
  102517. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  102518. /**
  102519. * The clear color of the texture used to generate the glow map.
  102520. */
  102521. this.neutralColor = new BABYLON.Color4();
  102522. /**
  102523. * Specifies wether the highlight layer is enabled or not.
  102524. */
  102525. this.isEnabled = true;
  102526. /**
  102527. * An event triggered when the effect layer has been disposed.
  102528. */
  102529. this.onDisposeObservable = new BABYLON.Observable();
  102530. /**
  102531. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  102532. */
  102533. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  102534. /**
  102535. * An event triggered when the generated texture is being merged in the scene.
  102536. */
  102537. this.onBeforeComposeObservable = new BABYLON.Observable();
  102538. /**
  102539. * An event triggered when the generated texture has been merged in the scene.
  102540. */
  102541. this.onAfterComposeObservable = new BABYLON.Observable();
  102542. /**
  102543. * An event triggered when the efffect layer changes its size.
  102544. */
  102545. this.onSizeChangedObservable = new BABYLON.Observable();
  102546. this.name = name;
  102547. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102548. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  102549. if (!component) {
  102550. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  102551. this._scene._addComponent(component);
  102552. }
  102553. this._engine = this._scene.getEngine();
  102554. this._maxSize = this._engine.getCaps().maxTextureSize;
  102555. this._scene.effectLayers.push(this);
  102556. // Generate Buffers
  102557. this._generateIndexBuffer();
  102558. this._genrateVertexBuffer();
  102559. }
  102560. Object.defineProperty(EffectLayer.prototype, "camera", {
  102561. /**
  102562. * Gets the camera attached to the layer.
  102563. */
  102564. get: function () {
  102565. return this._effectLayerOptions.camera;
  102566. },
  102567. enumerable: true,
  102568. configurable: true
  102569. });
  102570. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  102571. /**
  102572. * Gets the rendering group id the layer should render in.
  102573. */
  102574. get: function () {
  102575. return this._effectLayerOptions.renderingGroupId;
  102576. },
  102577. enumerable: true,
  102578. configurable: true
  102579. });
  102580. /**
  102581. * Initializes the effect layer with the required options.
  102582. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  102583. */
  102584. EffectLayer.prototype._init = function (options) {
  102585. // Adapt options
  102586. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102587. this._setMainTextureSize();
  102588. this._createMainTexture();
  102589. this._createTextureAndPostProcesses();
  102590. this._mergeEffect = this._createMergeEffect();
  102591. };
  102592. /**
  102593. * Generates the index buffer of the full screen quad blending to the main canvas.
  102594. */
  102595. EffectLayer.prototype._generateIndexBuffer = function () {
  102596. // Indices
  102597. var indices = [];
  102598. indices.push(0);
  102599. indices.push(1);
  102600. indices.push(2);
  102601. indices.push(0);
  102602. indices.push(2);
  102603. indices.push(3);
  102604. this._indexBuffer = this._engine.createIndexBuffer(indices);
  102605. };
  102606. /**
  102607. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  102608. */
  102609. EffectLayer.prototype._genrateVertexBuffer = function () {
  102610. // VBO
  102611. var vertices = [];
  102612. vertices.push(1, 1);
  102613. vertices.push(-1, 1);
  102614. vertices.push(-1, -1);
  102615. vertices.push(1, -1);
  102616. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102618. };
  102619. /**
  102620. * Sets the main texture desired size which is the closest power of two
  102621. * of the engine canvas size.
  102622. */
  102623. EffectLayer.prototype._setMainTextureSize = function () {
  102624. if (this._effectLayerOptions.mainTextureFixedSize) {
  102625. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  102626. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  102627. }
  102628. else {
  102629. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  102630. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  102631. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  102632. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  102633. }
  102634. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  102635. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  102636. };
  102637. /**
  102638. * Creates the main texture for the effect layer.
  102639. */
  102640. EffectLayer.prototype._createMainTexture = function () {
  102641. var _this = this;
  102642. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  102643. width: this._mainTextureDesiredSize.width,
  102644. height: this._mainTextureDesiredSize.height
  102645. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102646. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  102647. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102648. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102649. this._mainTexture.anisotropicFilteringLevel = 1;
  102650. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102651. this._mainTexture.renderParticles = false;
  102652. this._mainTexture.renderList = null;
  102653. this._mainTexture.ignoreCameraViewport = true;
  102654. // Custom render function
  102655. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  102656. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  102657. var index;
  102658. var engine = _this._scene.getEngine();
  102659. if (depthOnlySubMeshes.length) {
  102660. engine.setColorWrite(false);
  102661. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  102662. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  102663. }
  102664. engine.setColorWrite(true);
  102665. }
  102666. for (index = 0; index < opaqueSubMeshes.length; index++) {
  102667. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  102668. }
  102669. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  102670. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  102671. }
  102672. for (index = 0; index < transparentSubMeshes.length; index++) {
  102673. _this._renderSubMesh(transparentSubMeshes.data[index]);
  102674. }
  102675. };
  102676. this._mainTexture.onClearObservable.add(function (engine) {
  102677. engine.clear(_this.neutralColor, true, true, true);
  102678. });
  102679. };
  102680. /**
  102681. * Checks for the readiness of the element composing the layer.
  102682. * @param subMesh the mesh to check for
  102683. * @param useInstances specify wether or not to use instances to render the mesh
  102684. * @param emissiveTexture the associated emissive texture used to generate the glow
  102685. * @return true if ready otherwise, false
  102686. */
  102687. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  102688. var material = subMesh.getMaterial();
  102689. if (!material) {
  102690. return false;
  102691. }
  102692. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  102693. return false;
  102694. }
  102695. var defines = [];
  102696. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102697. var mesh = subMesh.getMesh();
  102698. var uv1 = false;
  102699. var uv2 = false;
  102700. // Alpha test
  102701. if (material && material.needAlphaTesting()) {
  102702. var alphaTexture = material.getAlphaTestTexture();
  102703. if (alphaTexture) {
  102704. defines.push("#define ALPHATEST");
  102705. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102706. alphaTexture.coordinatesIndex === 1) {
  102707. defines.push("#define DIFFUSEUV2");
  102708. uv2 = true;
  102709. }
  102710. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102711. defines.push("#define DIFFUSEUV1");
  102712. uv1 = true;
  102713. }
  102714. }
  102715. }
  102716. // Emissive
  102717. if (emissiveTexture) {
  102718. defines.push("#define EMISSIVE");
  102719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102720. emissiveTexture.coordinatesIndex === 1) {
  102721. defines.push("#define EMISSIVEUV2");
  102722. uv2 = true;
  102723. }
  102724. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102725. defines.push("#define EMISSIVEUV1");
  102726. uv1 = true;
  102727. }
  102728. }
  102729. if (uv1) {
  102730. attribs.push(BABYLON.VertexBuffer.UVKind);
  102731. defines.push("#define UV1");
  102732. }
  102733. if (uv2) {
  102734. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102735. defines.push("#define UV2");
  102736. }
  102737. // Bones
  102738. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  102739. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  102740. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  102741. if (mesh.numBoneInfluencers > 4) {
  102742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  102743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  102744. }
  102745. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  102746. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  102747. }
  102748. else {
  102749. defines.push("#define NUM_BONE_INFLUENCERS 0");
  102750. }
  102751. // Morph targets
  102752. var manager = mesh.morphTargetManager;
  102753. var morphInfluencers = 0;
  102754. if (manager) {
  102755. if (manager.numInfluencers > 0) {
  102756. defines.push("#define MORPHTARGETS");
  102757. morphInfluencers = manager.numInfluencers;
  102758. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  102759. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  102760. }
  102761. }
  102762. // Instances
  102763. if (useInstances) {
  102764. defines.push("#define INSTANCES");
  102765. attribs.push("world0");
  102766. attribs.push("world1");
  102767. attribs.push("world2");
  102768. attribs.push("world3");
  102769. }
  102770. // Get correct effect
  102771. var join = defines.join("\n");
  102772. if (this._cachedDefines !== join) {
  102773. this._cachedDefines = join;
  102774. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  102775. }
  102776. return this._effectLayerMapGenerationEffect.isReady();
  102777. };
  102778. /**
  102779. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  102780. */
  102781. EffectLayer.prototype.render = function () {
  102782. var currentEffect = this._mergeEffect;
  102783. // Check
  102784. if (!currentEffect.isReady())
  102785. return;
  102786. for (var i = 0; i < this._postProcesses.length; i++) {
  102787. if (!this._postProcesses[i].isReady()) {
  102788. return;
  102789. }
  102790. }
  102791. var engine = this._scene.getEngine();
  102792. this.onBeforeComposeObservable.notifyObservers(this);
  102793. // Render
  102794. engine.enableEffect(currentEffect);
  102795. engine.setState(false);
  102796. // VBOs
  102797. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102798. // Cache
  102799. var previousAlphaMode = engine.getAlphaMode();
  102800. // Go Blend.
  102801. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102802. // Blends the map on the main canvas.
  102803. this._internalRender(currentEffect);
  102804. // Restore Alpha
  102805. engine.setAlphaMode(previousAlphaMode);
  102806. this.onAfterComposeObservable.notifyObservers(this);
  102807. // Handle size changes.
  102808. var size = this._mainTexture.getSize();
  102809. this._setMainTextureSize();
  102810. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102811. // Recreate RTT and post processes on size change.
  102812. this.onSizeChangedObservable.notifyObservers(this);
  102813. this._disposeTextureAndPostProcesses();
  102814. this._createMainTexture();
  102815. this._createTextureAndPostProcesses();
  102816. }
  102817. };
  102818. /**
  102819. * Determine if a given mesh will be used in the current effect.
  102820. * @param mesh mesh to test
  102821. * @returns true if the mesh will be used
  102822. */
  102823. EffectLayer.prototype.hasMesh = function (mesh) {
  102824. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102825. return true;
  102826. }
  102827. return false;
  102828. };
  102829. /**
  102830. * Returns true if the layer contains information to display, otherwise false.
  102831. * @returns true if the glow layer should be rendered
  102832. */
  102833. EffectLayer.prototype.shouldRender = function () {
  102834. return this.isEnabled && this._shouldRender;
  102835. };
  102836. /**
  102837. * Returns true if the mesh should render, otherwise false.
  102838. * @param mesh The mesh to render
  102839. * @returns true if it should render otherwise false
  102840. */
  102841. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102842. return true;
  102843. };
  102844. /**
  102845. * Returns true if the mesh should render, otherwise false.
  102846. * @param mesh The mesh to render
  102847. * @returns true if it should render otherwise false
  102848. */
  102849. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102850. return true;
  102851. };
  102852. /**
  102853. * Renders the submesh passed in parameter to the generation map.
  102854. */
  102855. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102856. var _this = this;
  102857. if (!this.shouldRender()) {
  102858. return;
  102859. }
  102860. var material = subMesh.getMaterial();
  102861. var mesh = subMesh.getRenderingMesh();
  102862. var scene = this._scene;
  102863. var engine = scene.getEngine();
  102864. if (!material) {
  102865. return;
  102866. }
  102867. // Do not block in blend mode.
  102868. if (material.needAlphaBlendingForMesh(mesh)) {
  102869. return;
  102870. }
  102871. // Culling
  102872. engine.setState(material.backFaceCulling);
  102873. // Managing instances
  102874. var batch = mesh._getInstancesRenderList(subMesh._id);
  102875. if (batch.mustReturn) {
  102876. return;
  102877. }
  102878. // Early Exit per mesh
  102879. if (!this._shouldRenderMesh(mesh)) {
  102880. return;
  102881. }
  102882. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102883. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102884. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102885. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102886. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102887. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102888. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102889. // Alpha test
  102890. if (material && material.needAlphaTesting()) {
  102891. var alphaTexture = material.getAlphaTestTexture();
  102892. if (alphaTexture) {
  102893. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102894. var textureMatrix = alphaTexture.getTextureMatrix();
  102895. if (textureMatrix) {
  102896. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102897. }
  102898. }
  102899. }
  102900. // Glow emissive only
  102901. if (this._emissiveTextureAndColor.texture) {
  102902. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102903. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102904. }
  102905. // Bones
  102906. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102907. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102908. }
  102909. // Morph targets
  102910. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102911. // Draw
  102912. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102913. }
  102914. else {
  102915. // Need to reset refresh rate of the main map
  102916. this._mainTexture.resetRefreshCounter();
  102917. }
  102918. };
  102919. /**
  102920. * Rebuild the required buffers.
  102921. * @hidden Internal use only.
  102922. */
  102923. EffectLayer.prototype._rebuild = function () {
  102924. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102925. if (vb) {
  102926. vb._rebuild();
  102927. }
  102928. this._generateIndexBuffer();
  102929. };
  102930. /**
  102931. * Dispose only the render target textures and post process.
  102932. */
  102933. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102934. this._mainTexture.dispose();
  102935. for (var i = 0; i < this._postProcesses.length; i++) {
  102936. if (this._postProcesses[i]) {
  102937. this._postProcesses[i].dispose();
  102938. }
  102939. }
  102940. this._postProcesses = [];
  102941. for (var i = 0; i < this._textures.length; i++) {
  102942. if (this._textures[i]) {
  102943. this._textures[i].dispose();
  102944. }
  102945. }
  102946. this._textures = [];
  102947. };
  102948. /**
  102949. * Dispose the highlight layer and free resources.
  102950. */
  102951. EffectLayer.prototype.dispose = function () {
  102952. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102953. if (vertexBuffer) {
  102954. vertexBuffer.dispose();
  102955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102956. }
  102957. if (this._indexBuffer) {
  102958. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102959. this._indexBuffer = null;
  102960. }
  102961. // Clean textures and post processes
  102962. this._disposeTextureAndPostProcesses();
  102963. // Remove from scene
  102964. var index = this._scene.effectLayers.indexOf(this, 0);
  102965. if (index > -1) {
  102966. this._scene.effectLayers.splice(index, 1);
  102967. }
  102968. // Callback
  102969. this.onDisposeObservable.notifyObservers(this);
  102970. this.onDisposeObservable.clear();
  102971. this.onBeforeRenderMainTextureObservable.clear();
  102972. this.onBeforeComposeObservable.clear();
  102973. this.onAfterComposeObservable.clear();
  102974. this.onSizeChangedObservable.clear();
  102975. };
  102976. /**
  102977. * Gets the class name of the effect layer
  102978. * @returns the string with the class name of the effect layer
  102979. */
  102980. EffectLayer.prototype.getClassName = function () {
  102981. return "EffectLayer";
  102982. };
  102983. /**
  102984. * Creates an effect layer from parsed effect layer data
  102985. * @param parsedEffectLayer defines effect layer data
  102986. * @param scene defines the current scene
  102987. * @param rootUrl defines the root URL containing the effect layer information
  102988. * @returns a parsed effect Layer
  102989. */
  102990. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102991. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102992. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102993. };
  102994. __decorate([
  102995. BABYLON.serialize()
  102996. ], EffectLayer.prototype, "name", void 0);
  102997. __decorate([
  102998. BABYLON.serializeAsColor4()
  102999. ], EffectLayer.prototype, "neutralColor", void 0);
  103000. __decorate([
  103001. BABYLON.serialize()
  103002. ], EffectLayer.prototype, "isEnabled", void 0);
  103003. __decorate([
  103004. BABYLON.serializeAsCameraReference()
  103005. ], EffectLayer.prototype, "camera", null);
  103006. __decorate([
  103007. BABYLON.serialize()
  103008. ], EffectLayer.prototype, "renderingGroupId", null);
  103009. return EffectLayer;
  103010. }());
  103011. BABYLON.EffectLayer = EffectLayer;
  103012. })(BABYLON || (BABYLON = {}));
  103013. //# sourceMappingURL=babylon.effectLayer.js.map
  103014. var BABYLON;
  103015. (function (BABYLON) {
  103016. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  103017. for (var index = 0; index < this.effectLayers.length; index++) {
  103018. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  103019. return this.effectLayers[index];
  103020. }
  103021. }
  103022. return null;
  103023. };
  103024. /**
  103025. * Special Glow Blur post process only blurring the alpha channel
  103026. * It enforces keeping the most luminous color in the color channel.
  103027. */
  103028. var GlowBlurPostProcess = /** @class */ (function (_super) {
  103029. __extends(GlowBlurPostProcess, _super);
  103030. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  103031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  103032. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  103033. _this.direction = direction;
  103034. _this.kernel = kernel;
  103035. _this.onApplyObservable.add(function (effect) {
  103036. effect.setFloat2("screenSize", _this.width, _this.height);
  103037. effect.setVector2("direction", _this.direction);
  103038. effect.setFloat("blurWidth", _this.kernel);
  103039. });
  103040. return _this;
  103041. }
  103042. return GlowBlurPostProcess;
  103043. }(BABYLON.PostProcess));
  103044. /**
  103045. * The highlight layer Helps adding a glow effect around a mesh.
  103046. *
  103047. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103048. * glowy meshes to your scene.
  103049. *
  103050. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  103051. */
  103052. var HighlightLayer = /** @class */ (function (_super) {
  103053. __extends(HighlightLayer, _super);
  103054. /**
  103055. * Instantiates a new highlight Layer and references it to the scene..
  103056. * @param name The name of the layer
  103057. * @param scene The scene to use the layer in
  103058. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  103059. */
  103060. function HighlightLayer(name, scene, options) {
  103061. var _this = _super.call(this, name, scene) || this;
  103062. _this.name = name;
  103063. /**
  103064. * Specifies whether or not the inner glow is ACTIVE in the layer.
  103065. */
  103066. _this.innerGlow = true;
  103067. /**
  103068. * Specifies whether or not the outer glow is ACTIVE in the layer.
  103069. */
  103070. _this.outerGlow = true;
  103071. /**
  103072. * An event triggered when the highlight layer is being blurred.
  103073. */
  103074. _this.onBeforeBlurObservable = new BABYLON.Observable();
  103075. /**
  103076. * An event triggered when the highlight layer has been blurred.
  103077. */
  103078. _this.onAfterBlurObservable = new BABYLON.Observable();
  103079. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  103080. _this._meshes = {};
  103081. _this._excludedMeshes = {};
  103082. _this.neutralColor = HighlightLayer.NeutralColor;
  103083. // Warn on stencil
  103084. if (!_this._engine.isStencilEnable) {
  103085. 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 }");
  103086. }
  103087. // Adapt options
  103088. _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);
  103089. // Initialize the layer
  103090. _this._init({
  103091. alphaBlendingMode: _this._options.alphaBlendingMode,
  103092. camera: _this._options.camera,
  103093. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103094. mainTextureRatio: _this._options.mainTextureRatio,
  103095. renderingGroupId: _this._options.renderingGroupId
  103096. });
  103097. // Do not render as long as no meshes have been added
  103098. _this._shouldRender = false;
  103099. return _this;
  103100. }
  103101. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  103102. /**
  103103. * Gets the horizontal size of the blur.
  103104. */
  103105. get: function () {
  103106. return this._horizontalBlurPostprocess.kernel;
  103107. },
  103108. /**
  103109. * Specifies the horizontal size of the blur.
  103110. */
  103111. set: function (value) {
  103112. this._horizontalBlurPostprocess.kernel = value;
  103113. },
  103114. enumerable: true,
  103115. configurable: true
  103116. });
  103117. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  103118. /**
  103119. * Gets the vertical size of the blur.
  103120. */
  103121. get: function () {
  103122. return this._verticalBlurPostprocess.kernel;
  103123. },
  103124. /**
  103125. * Specifies the vertical size of the blur.
  103126. */
  103127. set: function (value) {
  103128. this._verticalBlurPostprocess.kernel = value;
  103129. },
  103130. enumerable: true,
  103131. configurable: true
  103132. });
  103133. /**
  103134. * Get the effect name of the layer.
  103135. * @return The effect name
  103136. */
  103137. HighlightLayer.prototype.getEffectName = function () {
  103138. return HighlightLayer.EffectName;
  103139. };
  103140. /**
  103141. * Create the merge effect. This is the shader use to blit the information back
  103142. * to the main canvas at the end of the scene rendering.
  103143. */
  103144. HighlightLayer.prototype._createMergeEffect = function () {
  103145. // Effect
  103146. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  103147. };
  103148. /**
  103149. * Creates the render target textures and post processes used in the highlight layer.
  103150. */
  103151. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  103152. var _this = this;
  103153. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  103154. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  103155. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103156. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103157. var textureType = 0;
  103158. if (this._engine.getCaps().textureHalfFloatRender) {
  103159. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103160. }
  103161. else {
  103162. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103163. }
  103164. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  103165. width: blurTextureWidth,
  103166. height: blurTextureHeight
  103167. }, this._scene, false, true, textureType);
  103168. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103169. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103170. this._blurTexture.anisotropicFilteringLevel = 16;
  103171. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  103172. this._blurTexture.renderParticles = false;
  103173. this._blurTexture.ignoreCameraViewport = true;
  103174. this._textures = [this._blurTexture];
  103175. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  103176. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103177. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  103178. effect.setTexture("textureSampler", _this._mainTexture);
  103179. });
  103180. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103181. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  103182. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  103183. });
  103184. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  103185. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  103186. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  103187. });
  103188. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  103189. }
  103190. else {
  103191. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  103192. width: blurTextureWidth,
  103193. height: blurTextureHeight
  103194. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103195. this._horizontalBlurPostprocess.width = blurTextureWidth;
  103196. this._horizontalBlurPostprocess.height = blurTextureHeight;
  103197. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  103198. effect.setTexture("textureSampler", _this._mainTexture);
  103199. });
  103200. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  103201. width: blurTextureWidth,
  103202. height: blurTextureHeight
  103203. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103204. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  103205. }
  103206. this._mainTexture.onAfterUnbindObservable.add(function () {
  103207. _this.onBeforeBlurObservable.notifyObservers(_this);
  103208. var internalTexture = _this._blurTexture.getInternalTexture();
  103209. if (internalTexture) {
  103210. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  103211. }
  103212. _this.onAfterBlurObservable.notifyObservers(_this);
  103213. });
  103214. // Prevent autoClear.
  103215. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103216. };
  103217. /**
  103218. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103219. */
  103220. HighlightLayer.prototype.needStencil = function () {
  103221. return true;
  103222. };
  103223. /**
  103224. * Checks for the readiness of the element composing the layer.
  103225. * @param subMesh the mesh to check for
  103226. * @param useInstances specify wether or not to use instances to render the mesh
  103227. * @param emissiveTexture the associated emissive texture used to generate the glow
  103228. * @return true if ready otherwise, false
  103229. */
  103230. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  103231. var material = subMesh.getMaterial();
  103232. var mesh = subMesh.getRenderingMesh();
  103233. if (!material || !mesh || !this._meshes) {
  103234. return false;
  103235. }
  103236. var emissiveTexture = null;
  103237. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103238. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103239. emissiveTexture = material.emissiveTexture;
  103240. }
  103241. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103242. };
  103243. /**
  103244. * Implementation specific of rendering the generating effect on the main canvas.
  103245. * @param effect The effect used to render through
  103246. */
  103247. HighlightLayer.prototype._internalRender = function (effect) {
  103248. // Texture
  103249. effect.setTexture("textureSampler", this._blurTexture);
  103250. // Cache
  103251. var engine = this._engine;
  103252. var previousStencilBuffer = engine.getStencilBuffer();
  103253. var previousStencilFunction = engine.getStencilFunction();
  103254. var previousStencilMask = engine.getStencilMask();
  103255. var previousStencilOperationPass = engine.getStencilOperationPass();
  103256. var previousStencilOperationFail = engine.getStencilOperationFail();
  103257. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  103258. var previousStencilReference = engine.getStencilFunctionReference();
  103259. // Stencil operations
  103260. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  103261. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  103262. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  103263. // Draw order
  103264. engine.setStencilMask(0x00);
  103265. engine.setStencilBuffer(true);
  103266. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  103267. // 2 passes inner outer
  103268. if (this.outerGlow) {
  103269. effect.setFloat("offset", 0);
  103270. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  103271. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103272. }
  103273. if (this.innerGlow) {
  103274. effect.setFloat("offset", 1);
  103275. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  103276. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103277. }
  103278. // Restore Cache
  103279. engine.setStencilFunction(previousStencilFunction);
  103280. engine.setStencilMask(previousStencilMask);
  103281. engine.setStencilBuffer(previousStencilBuffer);
  103282. engine.setStencilOperationPass(previousStencilOperationPass);
  103283. engine.setStencilOperationFail(previousStencilOperationFail);
  103284. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  103285. engine.setStencilFunctionReference(previousStencilReference);
  103286. };
  103287. /**
  103288. * Returns true if the layer contains information to display, otherwise false.
  103289. */
  103290. HighlightLayer.prototype.shouldRender = function () {
  103291. if (_super.prototype.shouldRender.call(this)) {
  103292. return this._meshes ? true : false;
  103293. }
  103294. return false;
  103295. };
  103296. /**
  103297. * Returns true if the mesh should render, otherwise false.
  103298. * @param mesh The mesh to render
  103299. * @returns true if it should render otherwise false
  103300. */
  103301. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  103302. // Excluded Mesh
  103303. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  103304. return false;
  103305. }
  103306. ;
  103307. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103308. return false;
  103309. }
  103310. return true;
  103311. };
  103312. /**
  103313. * Sets the required values for both the emissive texture and and the main color.
  103314. */
  103315. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103316. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103317. if (highlightLayerMesh) {
  103318. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  103319. }
  103320. else {
  103321. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103322. }
  103323. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103324. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103325. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  103326. }
  103327. else {
  103328. this._emissiveTextureAndColor.texture = null;
  103329. }
  103330. };
  103331. /**
  103332. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  103333. * @param mesh The mesh to exclude from the highlight layer
  103334. */
  103335. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  103336. if (!this._excludedMeshes) {
  103337. return;
  103338. }
  103339. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103340. if (!meshExcluded) {
  103341. this._excludedMeshes[mesh.uniqueId] = {
  103342. mesh: mesh,
  103343. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  103344. mesh.getEngine().setStencilBuffer(false);
  103345. }),
  103346. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  103347. mesh.getEngine().setStencilBuffer(true);
  103348. }),
  103349. };
  103350. }
  103351. };
  103352. /**
  103353. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  103354. * @param mesh The mesh to highlight
  103355. */
  103356. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  103357. if (!this._excludedMeshes) {
  103358. return;
  103359. }
  103360. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103361. if (meshExcluded) {
  103362. if (meshExcluded.beforeRender) {
  103363. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  103364. }
  103365. if (meshExcluded.afterRender) {
  103366. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  103367. }
  103368. }
  103369. this._excludedMeshes[mesh.uniqueId] = null;
  103370. };
  103371. /**
  103372. * Determine if a given mesh will be highlighted by the current HighlightLayer
  103373. * @param mesh mesh to test
  103374. * @returns true if the mesh will be highlighted by the current HighlightLayer
  103375. */
  103376. HighlightLayer.prototype.hasMesh = function (mesh) {
  103377. if (!this._meshes) {
  103378. return false;
  103379. }
  103380. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103381. return false;
  103382. }
  103383. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  103384. };
  103385. /**
  103386. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  103387. * @param mesh The mesh to highlight
  103388. * @param color The color of the highlight
  103389. * @param glowEmissiveOnly Extract the glow from the emissive texture
  103390. */
  103391. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  103392. var _this = this;
  103393. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  103394. if (!this._meshes) {
  103395. return;
  103396. }
  103397. var meshHighlight = this._meshes[mesh.uniqueId];
  103398. if (meshHighlight) {
  103399. meshHighlight.color = color;
  103400. }
  103401. else {
  103402. this._meshes[mesh.uniqueId] = {
  103403. mesh: mesh,
  103404. color: color,
  103405. // Lambda required for capture due to Observable this context
  103406. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  103407. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  103408. _this._defaultStencilReference(mesh);
  103409. }
  103410. else {
  103411. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  103412. }
  103413. }),
  103414. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  103415. glowEmissiveOnly: glowEmissiveOnly
  103416. };
  103417. mesh.onDisposeObservable.add(function () {
  103418. _this._disposeMesh(mesh);
  103419. });
  103420. }
  103421. this._shouldRender = true;
  103422. };
  103423. /**
  103424. * Remove a mesh from the highlight layer in order to make it stop glowing.
  103425. * @param mesh The mesh to highlight
  103426. */
  103427. HighlightLayer.prototype.removeMesh = function (mesh) {
  103428. if (!this._meshes) {
  103429. return;
  103430. }
  103431. var meshHighlight = this._meshes[mesh.uniqueId];
  103432. if (meshHighlight) {
  103433. if (meshHighlight.observerHighlight) {
  103434. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103435. }
  103436. if (meshHighlight.observerDefault) {
  103437. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103438. }
  103439. delete this._meshes[mesh.uniqueId];
  103440. }
  103441. this._shouldRender = false;
  103442. for (var meshHighlightToCheck in this._meshes) {
  103443. if (this._meshes[meshHighlightToCheck]) {
  103444. this._shouldRender = true;
  103445. break;
  103446. }
  103447. }
  103448. };
  103449. /**
  103450. * Force the stencil to the normal expected value for none glowing parts
  103451. */
  103452. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  103453. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  103454. };
  103455. /**
  103456. * Free any resources and references associated to a mesh.
  103457. * Internal use
  103458. * @param mesh The mesh to free.
  103459. * @hidden
  103460. */
  103461. HighlightLayer.prototype._disposeMesh = function (mesh) {
  103462. this.removeMesh(mesh);
  103463. this.removeExcludedMesh(mesh);
  103464. };
  103465. /**
  103466. * Dispose the highlight layer and free resources.
  103467. */
  103468. HighlightLayer.prototype.dispose = function () {
  103469. if (this._meshes) {
  103470. // Clean mesh references
  103471. for (var id in this._meshes) {
  103472. var meshHighlight = this._meshes[id];
  103473. if (meshHighlight && meshHighlight.mesh) {
  103474. if (meshHighlight.observerHighlight) {
  103475. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103476. }
  103477. if (meshHighlight.observerDefault) {
  103478. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103479. }
  103480. }
  103481. }
  103482. this._meshes = null;
  103483. }
  103484. if (this._excludedMeshes) {
  103485. for (var id in this._excludedMeshes) {
  103486. var meshHighlight = this._excludedMeshes[id];
  103487. if (meshHighlight) {
  103488. if (meshHighlight.beforeRender) {
  103489. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  103490. }
  103491. if (meshHighlight.afterRender) {
  103492. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  103493. }
  103494. }
  103495. }
  103496. this._excludedMeshes = null;
  103497. }
  103498. _super.prototype.dispose.call(this);
  103499. };
  103500. /**
  103501. * Gets the class name of the effect layer
  103502. * @returns the string with the class name of the effect layer
  103503. */
  103504. HighlightLayer.prototype.getClassName = function () {
  103505. return "HighlightLayer";
  103506. };
  103507. /**
  103508. * Serializes this Highlight layer
  103509. * @returns a serialized Highlight layer object
  103510. */
  103511. HighlightLayer.prototype.serialize = function () {
  103512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103513. serializationObject.customType = "BABYLON.HighlightLayer";
  103514. // Highlighted meshes
  103515. serializationObject.meshes = [];
  103516. if (this._meshes) {
  103517. for (var m in this._meshes) {
  103518. var mesh = this._meshes[m];
  103519. if (mesh) {
  103520. serializationObject.meshes.push({
  103521. glowEmissiveOnly: mesh.glowEmissiveOnly,
  103522. color: mesh.color.asArray(),
  103523. meshId: mesh.mesh.id
  103524. });
  103525. }
  103526. }
  103527. }
  103528. // Excluded meshes
  103529. serializationObject.excludedMeshes = [];
  103530. if (this._excludedMeshes) {
  103531. for (var e in this._excludedMeshes) {
  103532. var excludedMesh = this._excludedMeshes[e];
  103533. if (excludedMesh) {
  103534. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  103535. }
  103536. }
  103537. }
  103538. return serializationObject;
  103539. };
  103540. /**
  103541. * Creates a Highlight layer from parsed Highlight layer data
  103542. * @param parsedHightlightLayer defines the Highlight layer data
  103543. * @param scene defines the current scene
  103544. * @param rootUrl defines the root URL containing the Highlight layer information
  103545. * @returns a parsed Highlight layer
  103546. */
  103547. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  103548. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  103549. var index;
  103550. // Excluded meshes
  103551. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  103552. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  103553. if (mesh) {
  103554. hl.addExcludedMesh(mesh);
  103555. }
  103556. }
  103557. // Included meshes
  103558. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  103559. var highlightedMesh = parsedHightlightLayer.meshes[index];
  103560. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  103561. if (mesh) {
  103562. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  103563. }
  103564. }
  103565. return hl;
  103566. };
  103567. /**
  103568. * Effect Name of the highlight layer.
  103569. */
  103570. HighlightLayer.EffectName = "HighlightLayer";
  103571. /**
  103572. * The neutral color used during the preparation of the glow effect.
  103573. * This is black by default as the blend operation is a blend operation.
  103574. */
  103575. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  103576. /**
  103577. * Stencil value used for glowing meshes.
  103578. */
  103579. HighlightLayer.GlowingMeshStencilReference = 0x02;
  103580. /**
  103581. * Stencil value used for the other meshes in the scene.
  103582. */
  103583. HighlightLayer.NormalMeshStencilReference = 0x01;
  103584. __decorate([
  103585. BABYLON.serialize()
  103586. ], HighlightLayer.prototype, "innerGlow", void 0);
  103587. __decorate([
  103588. BABYLON.serialize()
  103589. ], HighlightLayer.prototype, "outerGlow", void 0);
  103590. __decorate([
  103591. BABYLON.serialize()
  103592. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  103593. __decorate([
  103594. BABYLON.serialize()
  103595. ], HighlightLayer.prototype, "blurVerticalSize", null);
  103596. __decorate([
  103597. BABYLON.serialize("options")
  103598. ], HighlightLayer.prototype, "_options", void 0);
  103599. return HighlightLayer;
  103600. }(BABYLON.EffectLayer));
  103601. BABYLON.HighlightLayer = HighlightLayer;
  103602. })(BABYLON || (BABYLON = {}));
  103603. //# sourceMappingURL=babylon.highlightLayer.js.map
  103604. var BABYLON;
  103605. (function (BABYLON) {
  103606. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  103607. for (var index = 0; index < this.effectLayers.length; index++) {
  103608. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  103609. return this.effectLayers[index];
  103610. }
  103611. }
  103612. return null;
  103613. };
  103614. /**
  103615. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  103616. *
  103617. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103618. * glowy meshes to your scene.
  103619. *
  103620. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  103621. */
  103622. var GlowLayer = /** @class */ (function (_super) {
  103623. __extends(GlowLayer, _super);
  103624. /**
  103625. * Instantiates a new glow Layer and references it to the scene.
  103626. * @param name The name of the layer
  103627. * @param scene The scene to use the layer in
  103628. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  103629. */
  103630. function GlowLayer(name, scene, options) {
  103631. var _this = _super.call(this, name, scene) || this;
  103632. _this._intensity = 1.0;
  103633. _this._includedOnlyMeshes = [];
  103634. _this._excludedMeshes = [];
  103635. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  103636. // Adapt options
  103637. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  103638. // Initialize the layer
  103639. _this._init({
  103640. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  103641. camera: _this._options.camera,
  103642. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103643. mainTextureRatio: _this._options.mainTextureRatio,
  103644. renderingGroupId: _this._options.renderingGroupId
  103645. });
  103646. return _this;
  103647. }
  103648. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  103649. /**
  103650. * Gets the kernel size of the blur.
  103651. */
  103652. get: function () {
  103653. return this._horizontalBlurPostprocess1.kernel;
  103654. },
  103655. /**
  103656. * Sets the kernel size of the blur.
  103657. */
  103658. set: function (value) {
  103659. this._horizontalBlurPostprocess1.kernel = value;
  103660. this._verticalBlurPostprocess1.kernel = value;
  103661. this._horizontalBlurPostprocess2.kernel = value;
  103662. this._verticalBlurPostprocess2.kernel = value;
  103663. },
  103664. enumerable: true,
  103665. configurable: true
  103666. });
  103667. Object.defineProperty(GlowLayer.prototype, "intensity", {
  103668. /**
  103669. * Gets the glow intensity.
  103670. */
  103671. get: function () {
  103672. return this._intensity;
  103673. },
  103674. /**
  103675. * Sets the glow intensity.
  103676. */
  103677. set: function (value) {
  103678. this._intensity = value;
  103679. },
  103680. enumerable: true,
  103681. configurable: true
  103682. });
  103683. /**
  103684. * Get the effect name of the layer.
  103685. * @return The effect name
  103686. */
  103687. GlowLayer.prototype.getEffectName = function () {
  103688. return GlowLayer.EffectName;
  103689. };
  103690. /**
  103691. * Create the merge effect. This is the shader use to blit the information back
  103692. * to the main canvas at the end of the scene rendering.
  103693. */
  103694. GlowLayer.prototype._createMergeEffect = function () {
  103695. // Effect
  103696. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  103697. };
  103698. /**
  103699. * Creates the render target textures and post processes used in the glow layer.
  103700. */
  103701. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  103702. var _this = this;
  103703. var blurTextureWidth = this._mainTextureDesiredSize.width;
  103704. var blurTextureHeight = this._mainTextureDesiredSize.height;
  103705. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103706. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103707. var textureType = 0;
  103708. if (this._engine.getCaps().textureHalfFloatRender) {
  103709. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103710. }
  103711. else {
  103712. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103713. }
  103714. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  103715. width: blurTextureWidth,
  103716. height: blurTextureHeight
  103717. }, this._scene, false, true, textureType);
  103718. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103719. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103720. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103721. this._blurTexture1.renderParticles = false;
  103722. this._blurTexture1.ignoreCameraViewport = true;
  103723. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  103724. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  103725. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  103726. width: blurTextureWidth2,
  103727. height: blurTextureHeight2
  103728. }, this._scene, false, true, textureType);
  103729. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103730. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103731. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103732. this._blurTexture2.renderParticles = false;
  103733. this._blurTexture2.ignoreCameraViewport = true;
  103734. this._textures = [this._blurTexture1, this._blurTexture2];
  103735. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103736. width: blurTextureWidth,
  103737. height: blurTextureHeight
  103738. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103739. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  103740. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  103741. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  103742. effect.setTexture("textureSampler", _this._mainTexture);
  103743. });
  103744. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103745. width: blurTextureWidth,
  103746. height: blurTextureHeight
  103747. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103748. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103749. width: blurTextureWidth2,
  103750. height: blurTextureHeight2
  103751. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103752. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  103753. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  103754. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  103755. effect.setTexture("textureSampler", _this._blurTexture1);
  103756. });
  103757. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103758. width: blurTextureWidth2,
  103759. height: blurTextureHeight2
  103760. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103761. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103762. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  103763. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103764. this._mainTexture.samples = this._options.mainTextureSamples;
  103765. this._mainTexture.onAfterUnbindObservable.add(function () {
  103766. var internalTexture = _this._blurTexture1.getInternalTexture();
  103767. if (internalTexture) {
  103768. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  103769. internalTexture = _this._blurTexture2.getInternalTexture();
  103770. if (internalTexture) {
  103771. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  103772. }
  103773. }
  103774. });
  103775. // Prevent autoClear.
  103776. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103777. };
  103778. /**
  103779. * Checks for the readiness of the element composing the layer.
  103780. * @param subMesh the mesh to check for
  103781. * @param useInstances specify wether or not to use instances to render the mesh
  103782. * @param emissiveTexture the associated emissive texture used to generate the glow
  103783. * @return true if ready otherwise, false
  103784. */
  103785. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103786. var material = subMesh.getMaterial();
  103787. var mesh = subMesh.getRenderingMesh();
  103788. if (!material || !mesh) {
  103789. return false;
  103790. }
  103791. var emissiveTexture = material.emissiveTexture;
  103792. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103793. };
  103794. /**
  103795. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103796. */
  103797. GlowLayer.prototype.needStencil = function () {
  103798. return false;
  103799. };
  103800. /**
  103801. * Implementation specific of rendering the generating effect on the main canvas.
  103802. * @param effect The effect used to render through
  103803. */
  103804. GlowLayer.prototype._internalRender = function (effect) {
  103805. // Texture
  103806. effect.setTexture("textureSampler", this._blurTexture1);
  103807. effect.setTexture("textureSampler2", this._blurTexture2);
  103808. effect.setFloat("offset", this._intensity);
  103809. // Cache
  103810. var engine = this._engine;
  103811. var previousStencilBuffer = engine.getStencilBuffer();
  103812. // Draw order
  103813. engine.setStencilBuffer(false);
  103814. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103815. // Draw order
  103816. engine.setStencilBuffer(previousStencilBuffer);
  103817. };
  103818. /**
  103819. * Sets the required values for both the emissive texture and and the main color.
  103820. */
  103821. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103822. var textureLevel = 1.0;
  103823. if (this.customEmissiveTextureSelector) {
  103824. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103825. }
  103826. else {
  103827. if (material) {
  103828. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103829. if (this._emissiveTextureAndColor.texture) {
  103830. textureLevel = this._emissiveTextureAndColor.texture.level;
  103831. }
  103832. }
  103833. else {
  103834. this._emissiveTextureAndColor.texture = null;
  103835. }
  103836. }
  103837. if (this.customEmissiveColorSelector) {
  103838. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103839. }
  103840. else {
  103841. if (material.emissiveColor) {
  103842. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103843. }
  103844. else {
  103845. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103846. }
  103847. }
  103848. };
  103849. /**
  103850. * Returns true if the mesh should render, otherwise false.
  103851. * @param mesh The mesh to render
  103852. * @returns true if it should render otherwise false
  103853. */
  103854. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103855. return this.hasMesh(mesh);
  103856. };
  103857. /**
  103858. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103859. * @param mesh The mesh to exclude from the glow layer
  103860. */
  103861. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103862. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103863. this._excludedMeshes.push(mesh.uniqueId);
  103864. }
  103865. };
  103866. /**
  103867. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103868. * @param mesh The mesh to remove
  103869. */
  103870. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103871. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103872. if (index !== -1) {
  103873. this._excludedMeshes.splice(index, 1);
  103874. }
  103875. };
  103876. /**
  103877. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103878. * @param mesh The mesh to include in the glow layer
  103879. */
  103880. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103881. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103882. this._includedOnlyMeshes.push(mesh.uniqueId);
  103883. }
  103884. };
  103885. /**
  103886. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103887. * @param mesh The mesh to remove
  103888. */
  103889. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103890. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103891. if (index !== -1) {
  103892. this._includedOnlyMeshes.splice(index, 1);
  103893. }
  103894. };
  103895. /**
  103896. * Determine if a given mesh will be used in the glow layer
  103897. * @param mesh The mesh to test
  103898. * @returns true if the mesh will be highlighted by the current glow layer
  103899. */
  103900. GlowLayer.prototype.hasMesh = function (mesh) {
  103901. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103902. return false;
  103903. }
  103904. // Included Mesh
  103905. if (this._includedOnlyMeshes.length) {
  103906. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103907. }
  103908. ;
  103909. // Excluded Mesh
  103910. if (this._excludedMeshes.length) {
  103911. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103912. }
  103913. ;
  103914. return true;
  103915. };
  103916. /**
  103917. * Free any resources and references associated to a mesh.
  103918. * Internal use
  103919. * @param mesh The mesh to free.
  103920. * @hidden
  103921. */
  103922. GlowLayer.prototype._disposeMesh = function (mesh) {
  103923. this.removeIncludedOnlyMesh(mesh);
  103924. this.removeExcludedMesh(mesh);
  103925. };
  103926. /**
  103927. * Gets the class name of the effect layer
  103928. * @returns the string with the class name of the effect layer
  103929. */
  103930. GlowLayer.prototype.getClassName = function () {
  103931. return "GlowLayer";
  103932. };
  103933. /**
  103934. * Serializes this glow layer
  103935. * @returns a serialized glow layer object
  103936. */
  103937. GlowLayer.prototype.serialize = function () {
  103938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103939. serializationObject.customType = "BABYLON.GlowLayer";
  103940. var index;
  103941. // Included meshes
  103942. serializationObject.includedMeshes = [];
  103943. if (this._includedOnlyMeshes.length) {
  103944. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103945. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103946. if (mesh) {
  103947. serializationObject.includedMeshes.push(mesh.id);
  103948. }
  103949. }
  103950. }
  103951. // Excluded meshes
  103952. serializationObject.excludedMeshes = [];
  103953. if (this._excludedMeshes.length) {
  103954. for (index = 0; index < this._excludedMeshes.length; index++) {
  103955. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103956. if (mesh) {
  103957. serializationObject.excludedMeshes.push(mesh.id);
  103958. }
  103959. }
  103960. }
  103961. return serializationObject;
  103962. };
  103963. /**
  103964. * Creates a Glow Layer from parsed glow layer data
  103965. * @param parsedGlowLayer defines glow layer data
  103966. * @param scene defines the current scene
  103967. * @param rootUrl defines the root URL containing the glow layer information
  103968. * @returns a parsed Glow Layer
  103969. */
  103970. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103971. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103972. var index;
  103973. // Excluded meshes
  103974. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103975. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103976. if (mesh) {
  103977. gl.addExcludedMesh(mesh);
  103978. }
  103979. }
  103980. // Included meshes
  103981. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103982. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103983. if (mesh) {
  103984. gl.addIncludedOnlyMesh(mesh);
  103985. }
  103986. }
  103987. return gl;
  103988. };
  103989. /**
  103990. * Effect Name of the layer.
  103991. */
  103992. GlowLayer.EffectName = "GlowLayer";
  103993. /**
  103994. * The default blur kernel size used for the glow.
  103995. */
  103996. GlowLayer.DefaultBlurKernelSize = 32;
  103997. /**
  103998. * The default texture size ratio used for the glow.
  103999. */
  104000. GlowLayer.DefaultTextureRatio = 0.5;
  104001. __decorate([
  104002. BABYLON.serialize()
  104003. ], GlowLayer.prototype, "blurKernelSize", null);
  104004. __decorate([
  104005. BABYLON.serialize()
  104006. ], GlowLayer.prototype, "intensity", null);
  104007. __decorate([
  104008. BABYLON.serialize("options")
  104009. ], GlowLayer.prototype, "_options", void 0);
  104010. return GlowLayer;
  104011. }(BABYLON.EffectLayer));
  104012. BABYLON.GlowLayer = GlowLayer;
  104013. })(BABYLON || (BABYLON = {}));
  104014. //# sourceMappingURL=babylon.glowLayer.js.map
  104015. var BABYLON;
  104016. (function (BABYLON) {
  104017. /**
  104018. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  104019. */
  104020. var AssetTaskState;
  104021. (function (AssetTaskState) {
  104022. /**
  104023. * Initialization
  104024. */
  104025. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  104026. /**
  104027. * Running
  104028. */
  104029. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  104030. /**
  104031. * Done
  104032. */
  104033. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  104034. /**
  104035. * Error
  104036. */
  104037. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  104038. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  104039. /**
  104040. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  104041. */
  104042. var AbstractAssetTask = /** @class */ (function () {
  104043. /**
  104044. * Creates a new {BABYLON.AssetsManager}
  104045. * @param name defines the name of the task
  104046. */
  104047. function AbstractAssetTask(
  104048. /**
  104049. * Task name
  104050. */ name) {
  104051. this.name = name;
  104052. this._isCompleted = false;
  104053. this._taskState = AssetTaskState.INIT;
  104054. }
  104055. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  104056. /**
  104057. * Get if the task is completed
  104058. */
  104059. get: function () {
  104060. return this._isCompleted;
  104061. },
  104062. enumerable: true,
  104063. configurable: true
  104064. });
  104065. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  104066. /**
  104067. * Gets the current state of the task
  104068. */
  104069. get: function () {
  104070. return this._taskState;
  104071. },
  104072. enumerable: true,
  104073. configurable: true
  104074. });
  104075. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  104076. /**
  104077. * Gets the current error object (if task is in error)
  104078. */
  104079. get: function () {
  104080. return this._errorObject;
  104081. },
  104082. enumerable: true,
  104083. configurable: true
  104084. });
  104085. /**
  104086. * Internal only
  104087. * @hidden
  104088. */
  104089. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  104090. if (this._errorObject) {
  104091. return;
  104092. }
  104093. this._errorObject = {
  104094. message: message,
  104095. exception: exception
  104096. };
  104097. };
  104098. /**
  104099. * Execute the current task
  104100. * @param scene defines the scene where you want your assets to be loaded
  104101. * @param onSuccess is a callback called when the task is successfully executed
  104102. * @param onError is a callback called if an error occurs
  104103. */
  104104. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104105. var _this = this;
  104106. this._taskState = AssetTaskState.RUNNING;
  104107. this.runTask(scene, function () {
  104108. _this.onDoneCallback(onSuccess, onError);
  104109. }, function (msg, exception) {
  104110. _this.onErrorCallback(onError, msg, exception);
  104111. });
  104112. };
  104113. /**
  104114. * Execute the current task
  104115. * @param scene defines the scene where you want your assets to be loaded
  104116. * @param onSuccess is a callback called when the task is successfully executed
  104117. * @param onError is a callback called if an error occurs
  104118. */
  104119. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104120. throw new Error("runTask is not implemented");
  104121. };
  104122. /**
  104123. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  104124. * This can be used with failed tasks that have the reason for failure fixed.
  104125. */
  104126. AbstractAssetTask.prototype.reset = function () {
  104127. this._taskState = AssetTaskState.INIT;
  104128. };
  104129. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  104130. this._taskState = AssetTaskState.ERROR;
  104131. this._errorObject = {
  104132. message: message,
  104133. exception: exception
  104134. };
  104135. if (this.onError) {
  104136. this.onError(this, message, exception);
  104137. }
  104138. onError();
  104139. };
  104140. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  104141. try {
  104142. this._taskState = AssetTaskState.DONE;
  104143. this._isCompleted = true;
  104144. if (this.onSuccess) {
  104145. this.onSuccess(this);
  104146. }
  104147. onSuccess();
  104148. }
  104149. catch (e) {
  104150. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  104151. }
  104152. };
  104153. return AbstractAssetTask;
  104154. }());
  104155. BABYLON.AbstractAssetTask = AbstractAssetTask;
  104156. /**
  104157. * Class used to share progress information about assets loading
  104158. */
  104159. var AssetsProgressEvent = /** @class */ (function () {
  104160. /**
  104161. * Creates a {BABYLON.AssetsProgressEvent}
  104162. * @param remainingCount defines the number of remaining tasks to process
  104163. * @param totalCount defines the total number of tasks
  104164. * @param task defines the task that was just processed
  104165. */
  104166. function AssetsProgressEvent(remainingCount, totalCount, task) {
  104167. this.remainingCount = remainingCount;
  104168. this.totalCount = totalCount;
  104169. this.task = task;
  104170. }
  104171. return AssetsProgressEvent;
  104172. }());
  104173. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  104174. /**
  104175. * Define a task used by {BABYLON.AssetsManager} to load meshes
  104176. */
  104177. var MeshAssetTask = /** @class */ (function (_super) {
  104178. __extends(MeshAssetTask, _super);
  104179. /**
  104180. * Creates a new {BABYLON.MeshAssetTask}
  104181. * @param name defines the name of the task
  104182. * @param meshesNames defines the list of mesh's names you want to load
  104183. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  104184. * @param sceneFilename defines the filename of the scene to load from
  104185. */
  104186. function MeshAssetTask(
  104187. /**
  104188. * Defines the name of the task
  104189. */
  104190. name,
  104191. /**
  104192. * Defines the list of mesh's names you want to load
  104193. */
  104194. meshesNames,
  104195. /**
  104196. * Defines the root url to use as a base to load your meshes and associated resources
  104197. */
  104198. rootUrl,
  104199. /**
  104200. * Defines the filename of the scene to load from
  104201. */
  104202. sceneFilename) {
  104203. var _this = _super.call(this, name) || this;
  104204. _this.name = name;
  104205. _this.meshesNames = meshesNames;
  104206. _this.rootUrl = rootUrl;
  104207. _this.sceneFilename = sceneFilename;
  104208. return _this;
  104209. }
  104210. /**
  104211. * Execute the current task
  104212. * @param scene defines the scene where you want your assets to be loaded
  104213. * @param onSuccess is a callback called when the task is successfully executed
  104214. * @param onError is a callback called if an error occurs
  104215. */
  104216. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104217. var _this = this;
  104218. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  104219. _this.loadedMeshes = meshes;
  104220. _this.loadedParticleSystems = particleSystems;
  104221. _this.loadedSkeletons = skeletons;
  104222. onSuccess();
  104223. }, null, function (scene, message, exception) {
  104224. onError(message, exception);
  104225. });
  104226. };
  104227. return MeshAssetTask;
  104228. }(AbstractAssetTask));
  104229. BABYLON.MeshAssetTask = MeshAssetTask;
  104230. /**
  104231. * Define a task used by {BABYLON.AssetsManager} to load text content
  104232. */
  104233. var TextFileAssetTask = /** @class */ (function (_super) {
  104234. __extends(TextFileAssetTask, _super);
  104235. /**
  104236. * Creates a new TextFileAssetTask object
  104237. * @param name defines the name of the task
  104238. * @param url defines the location of the file to load
  104239. */
  104240. function TextFileAssetTask(
  104241. /**
  104242. * Defines the name of the task
  104243. */
  104244. name,
  104245. /**
  104246. * Defines the location of the file to load
  104247. */
  104248. url) {
  104249. var _this = _super.call(this, name) || this;
  104250. _this.name = name;
  104251. _this.url = url;
  104252. return _this;
  104253. }
  104254. /**
  104255. * Execute the current task
  104256. * @param scene defines the scene where you want your assets to be loaded
  104257. * @param onSuccess is a callback called when the task is successfully executed
  104258. * @param onError is a callback called if an error occurs
  104259. */
  104260. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104261. var _this = this;
  104262. scene._loadFile(this.url, function (data) {
  104263. _this.text = data;
  104264. onSuccess();
  104265. }, undefined, false, false, function (request, exception) {
  104266. if (request) {
  104267. onError(request.status + " " + request.statusText, exception);
  104268. }
  104269. });
  104270. };
  104271. return TextFileAssetTask;
  104272. }(AbstractAssetTask));
  104273. BABYLON.TextFileAssetTask = TextFileAssetTask;
  104274. /**
  104275. * Define a task used by {BABYLON.AssetsManager} to load binary data
  104276. */
  104277. var BinaryFileAssetTask = /** @class */ (function (_super) {
  104278. __extends(BinaryFileAssetTask, _super);
  104279. /**
  104280. * Creates a new BinaryFileAssetTask object
  104281. * @param name defines the name of the new task
  104282. * @param url defines the location of the file to load
  104283. */
  104284. function BinaryFileAssetTask(
  104285. /**
  104286. * Defines the name of the task
  104287. */
  104288. name,
  104289. /**
  104290. * Defines the location of the file to load
  104291. */
  104292. url) {
  104293. var _this = _super.call(this, name) || this;
  104294. _this.name = name;
  104295. _this.url = url;
  104296. return _this;
  104297. }
  104298. /**
  104299. * Execute the current task
  104300. * @param scene defines the scene where you want your assets to be loaded
  104301. * @param onSuccess is a callback called when the task is successfully executed
  104302. * @param onError is a callback called if an error occurs
  104303. */
  104304. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104305. var _this = this;
  104306. scene._loadFile(this.url, function (data) {
  104307. _this.data = data;
  104308. onSuccess();
  104309. }, undefined, true, true, function (request, exception) {
  104310. if (request) {
  104311. onError(request.status + " " + request.statusText, exception);
  104312. }
  104313. });
  104314. };
  104315. return BinaryFileAssetTask;
  104316. }(AbstractAssetTask));
  104317. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  104318. /**
  104319. * Define a task used by {BABYLON.AssetsManager} to load images
  104320. */
  104321. var ImageAssetTask = /** @class */ (function (_super) {
  104322. __extends(ImageAssetTask, _super);
  104323. /**
  104324. * Creates a new ImageAssetTask
  104325. * @param name defines the name of the task
  104326. * @param url defines the location of the image to load
  104327. */
  104328. function ImageAssetTask(
  104329. /**
  104330. * Defines the name of the task
  104331. */
  104332. name,
  104333. /**
  104334. * Defines the location of the image to load
  104335. */
  104336. url) {
  104337. var _this = _super.call(this, name) || this;
  104338. _this.name = name;
  104339. _this.url = url;
  104340. return _this;
  104341. }
  104342. /**
  104343. * Execute the current task
  104344. * @param scene defines the scene where you want your assets to be loaded
  104345. * @param onSuccess is a callback called when the task is successfully executed
  104346. * @param onError is a callback called if an error occurs
  104347. */
  104348. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104349. var _this = this;
  104350. var img = new Image();
  104351. BABYLON.Tools.SetCorsBehavior(this.url, img);
  104352. img.onload = function () {
  104353. _this.image = img;
  104354. onSuccess();
  104355. };
  104356. img.onerror = function (err) {
  104357. onError("Error loading image", err);
  104358. };
  104359. img.src = this.url;
  104360. };
  104361. return ImageAssetTask;
  104362. }(AbstractAssetTask));
  104363. BABYLON.ImageAssetTask = ImageAssetTask;
  104364. /**
  104365. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  104366. */
  104367. var TextureAssetTask = /** @class */ (function (_super) {
  104368. __extends(TextureAssetTask, _super);
  104369. /**
  104370. * Creates a new TextureAssetTask object
  104371. * @param name defines the name of the task
  104372. * @param url defines the location of the file to load
  104373. * @param noMipmap defines if mipmap should not be generated (default is false)
  104374. * @param invertY defines if texture must be inverted on Y axis (default is false)
  104375. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104376. */
  104377. function TextureAssetTask(
  104378. /**
  104379. * Defines the name of the task
  104380. */
  104381. name,
  104382. /**
  104383. * Defines the location of the file to load
  104384. */
  104385. url,
  104386. /**
  104387. * Defines if mipmap should not be generated (default is false)
  104388. */
  104389. noMipmap,
  104390. /**
  104391. * Defines if texture must be inverted on Y axis (default is false)
  104392. */
  104393. invertY,
  104394. /**
  104395. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104396. */
  104397. samplingMode) {
  104398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104399. var _this = _super.call(this, name) || this;
  104400. _this.name = name;
  104401. _this.url = url;
  104402. _this.noMipmap = noMipmap;
  104403. _this.invertY = invertY;
  104404. _this.samplingMode = samplingMode;
  104405. return _this;
  104406. }
  104407. /**
  104408. * Execute the current task
  104409. * @param scene defines the scene where you want your assets to be loaded
  104410. * @param onSuccess is a callback called when the task is successfully executed
  104411. * @param onError is a callback called if an error occurs
  104412. */
  104413. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104414. var onload = function () {
  104415. onSuccess();
  104416. };
  104417. var onerror = function (message, exception) {
  104418. onError(message, exception);
  104419. };
  104420. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  104421. };
  104422. return TextureAssetTask;
  104423. }(AbstractAssetTask));
  104424. BABYLON.TextureAssetTask = TextureAssetTask;
  104425. /**
  104426. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  104427. */
  104428. var CubeTextureAssetTask = /** @class */ (function (_super) {
  104429. __extends(CubeTextureAssetTask, _super);
  104430. /**
  104431. * Creates a new CubeTextureAssetTask
  104432. * @param name defines the name of the task
  104433. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104434. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104435. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104436. * @param files defines the explicit list of files (undefined by default)
  104437. */
  104438. function CubeTextureAssetTask(
  104439. /**
  104440. * Defines the name of the task
  104441. */
  104442. name,
  104443. /**
  104444. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104445. */
  104446. url,
  104447. /**
  104448. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104449. */
  104450. extensions,
  104451. /**
  104452. * Defines if mipmaps should not be generated (default is false)
  104453. */
  104454. noMipmap,
  104455. /**
  104456. * Defines the explicit list of files (undefined by default)
  104457. */
  104458. files) {
  104459. var _this = _super.call(this, name) || this;
  104460. _this.name = name;
  104461. _this.url = url;
  104462. _this.extensions = extensions;
  104463. _this.noMipmap = noMipmap;
  104464. _this.files = files;
  104465. return _this;
  104466. }
  104467. /**
  104468. * Execute the current task
  104469. * @param scene defines the scene where you want your assets to be loaded
  104470. * @param onSuccess is a callback called when the task is successfully executed
  104471. * @param onError is a callback called if an error occurs
  104472. */
  104473. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104474. var onload = function () {
  104475. onSuccess();
  104476. };
  104477. var onerror = function (message, exception) {
  104478. onError(message, exception);
  104479. };
  104480. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  104481. };
  104482. return CubeTextureAssetTask;
  104483. }(AbstractAssetTask));
  104484. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  104485. /**
  104486. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  104487. */
  104488. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  104489. __extends(HDRCubeTextureAssetTask, _super);
  104490. /**
  104491. * Creates a new HDRCubeTextureAssetTask object
  104492. * @param name defines the name of the task
  104493. * @param url defines the location of the file to load
  104494. * @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.
  104495. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104496. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104497. * @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)
  104498. * @param reserved Internal use only
  104499. */
  104500. function HDRCubeTextureAssetTask(
  104501. /**
  104502. * Defines the name of the task
  104503. */
  104504. name,
  104505. /**
  104506. * Defines the location of the file to load
  104507. */
  104508. url,
  104509. /**
  104510. * Defines the desired size (the more it increases the longer the generation will be)
  104511. */
  104512. size,
  104513. /**
  104514. * Defines if mipmaps should not be generated (default is false)
  104515. */
  104516. noMipmap,
  104517. /**
  104518. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104519. */
  104520. generateHarmonics,
  104521. /**
  104522. * 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)
  104523. */
  104524. gammaSpace,
  104525. /**
  104526. * Internal Use Only
  104527. */
  104528. reserved) {
  104529. if (noMipmap === void 0) { noMipmap = false; }
  104530. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104531. if (gammaSpace === void 0) { gammaSpace = false; }
  104532. if (reserved === void 0) { reserved = false; }
  104533. var _this = _super.call(this, name) || this;
  104534. _this.name = name;
  104535. _this.url = url;
  104536. _this.size = size;
  104537. _this.noMipmap = noMipmap;
  104538. _this.generateHarmonics = generateHarmonics;
  104539. _this.gammaSpace = gammaSpace;
  104540. _this.reserved = reserved;
  104541. return _this;
  104542. }
  104543. /**
  104544. * Execute the current task
  104545. * @param scene defines the scene where you want your assets to be loaded
  104546. * @param onSuccess is a callback called when the task is successfully executed
  104547. * @param onError is a callback called if an error occurs
  104548. */
  104549. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104550. var onload = function () {
  104551. onSuccess();
  104552. };
  104553. var onerror = function (message, exception) {
  104554. onError(message, exception);
  104555. };
  104556. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  104557. };
  104558. return HDRCubeTextureAssetTask;
  104559. }(AbstractAssetTask));
  104560. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  104561. /**
  104562. * This class can be used to easily import assets into a scene
  104563. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  104564. */
  104565. var AssetsManager = /** @class */ (function () {
  104566. /**
  104567. * Creates a new AssetsManager
  104568. * @param scene defines the scene to work on
  104569. */
  104570. function AssetsManager(scene) {
  104571. this._isLoading = false;
  104572. this._tasks = new Array();
  104573. this._waitingTasksCount = 0;
  104574. this._totalTasksCount = 0;
  104575. /**
  104576. * Observable called when all tasks are processed
  104577. */
  104578. this.onTaskSuccessObservable = new BABYLON.Observable();
  104579. /**
  104580. * Observable called when a task had an error
  104581. */
  104582. this.onTaskErrorObservable = new BABYLON.Observable();
  104583. /**
  104584. * Observable called when a task is successful
  104585. */
  104586. this.onTasksDoneObservable = new BABYLON.Observable();
  104587. /**
  104588. * Observable called when a task is done (whatever the result is)
  104589. */
  104590. this.onProgressObservable = new BABYLON.Observable();
  104591. /**
  104592. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  104593. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  104594. */
  104595. this.useDefaultLoadingScreen = true;
  104596. this._scene = scene;
  104597. }
  104598. /**
  104599. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  104600. * @param taskName defines the name of the new task
  104601. * @param meshesNames defines the name of meshes to load
  104602. * @param rootUrl defines the root url to use to locate files
  104603. * @param sceneFilename defines the filename of the scene file
  104604. * @returns a new {BABYLON.MeshAssetTask} object
  104605. */
  104606. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  104607. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  104608. this._tasks.push(task);
  104609. return task;
  104610. };
  104611. /**
  104612. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  104613. * @param taskName defines the name of the new task
  104614. * @param url defines the url of the file to load
  104615. * @returns a new {BABYLON.TextFileAssetTask} object
  104616. */
  104617. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  104618. var task = new TextFileAssetTask(taskName, url);
  104619. this._tasks.push(task);
  104620. return task;
  104621. };
  104622. /**
  104623. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  104624. * @param taskName defines the name of the new task
  104625. * @param url defines the url of the file to load
  104626. * @returns a new {BABYLON.BinaryFileAssetTask} object
  104627. */
  104628. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  104629. var task = new BinaryFileAssetTask(taskName, url);
  104630. this._tasks.push(task);
  104631. return task;
  104632. };
  104633. /**
  104634. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  104635. * @param taskName defines the name of the new task
  104636. * @param url defines the url of the file to load
  104637. * @returns a new {BABYLON.ImageAssetTask} object
  104638. */
  104639. AssetsManager.prototype.addImageTask = function (taskName, url) {
  104640. var task = new ImageAssetTask(taskName, url);
  104641. this._tasks.push(task);
  104642. return task;
  104643. };
  104644. /**
  104645. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  104646. * @param taskName defines the name of the new task
  104647. * @param url defines the url of the file to load
  104648. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104649. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  104650. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  104651. * @returns a new {BABYLON.TextureAssetTask} object
  104652. */
  104653. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  104654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104655. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  104656. this._tasks.push(task);
  104657. return task;
  104658. };
  104659. /**
  104660. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  104661. * @param taskName defines the name of the new task
  104662. * @param url defines the url of the file to load
  104663. * @param extensions defines the extension to use to load the cube map (can be null)
  104664. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104665. * @param files defines the list of files to load (can be null)
  104666. * @returns a new {BABYLON.CubeTextureAssetTask} object
  104667. */
  104668. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  104669. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  104670. this._tasks.push(task);
  104671. return task;
  104672. };
  104673. /**
  104674. *
  104675. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  104676. * @param taskName defines the name of the new task
  104677. * @param url defines the url of the file to load
  104678. * @param size defines the size you want for the cubemap (can be null)
  104679. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104680. * @param generateHarmonics defines if you want to automatically generate (true by default)
  104681. * @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)
  104682. * @param reserved Internal use only
  104683. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  104684. */
  104685. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  104686. if (noMipmap === void 0) { noMipmap = false; }
  104687. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104688. if (gammaSpace === void 0) { gammaSpace = false; }
  104689. if (reserved === void 0) { reserved = false; }
  104690. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  104691. this._tasks.push(task);
  104692. return task;
  104693. };
  104694. /**
  104695. * Remove a task from the assets manager.
  104696. * @param task the task to remove
  104697. */
  104698. AssetsManager.prototype.removeTask = function (task) {
  104699. var index = this._tasks.indexOf(task);
  104700. if (index > -1) {
  104701. this._tasks.splice(index, 1);
  104702. }
  104703. };
  104704. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  104705. this._waitingTasksCount--;
  104706. try {
  104707. if (this.onProgress) {
  104708. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  104709. }
  104710. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  104711. }
  104712. catch (e) {
  104713. BABYLON.Tools.Error("Error running progress callbacks.");
  104714. console.log(e);
  104715. }
  104716. if (this._waitingTasksCount === 0) {
  104717. try {
  104718. if (this.onFinish) {
  104719. this.onFinish(this._tasks);
  104720. }
  104721. // Let's remove successfull tasks
  104722. var currentTasks = this._tasks.slice();
  104723. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  104724. var task = currentTasks_1[_i];
  104725. if (task.taskState === AssetTaskState.DONE) {
  104726. var index = this._tasks.indexOf(task);
  104727. if (index > -1) {
  104728. this._tasks.splice(index, 1);
  104729. }
  104730. }
  104731. }
  104732. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104733. }
  104734. catch (e) {
  104735. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  104736. console.log(e);
  104737. }
  104738. this._isLoading = false;
  104739. this._scene.getEngine().hideLoadingUI();
  104740. }
  104741. };
  104742. AssetsManager.prototype._runTask = function (task) {
  104743. var _this = this;
  104744. var done = function () {
  104745. try {
  104746. if (_this.onTaskSuccess) {
  104747. _this.onTaskSuccess(task);
  104748. }
  104749. _this.onTaskSuccessObservable.notifyObservers(task);
  104750. _this._decreaseWaitingTasksCount(task);
  104751. }
  104752. catch (e) {
  104753. error("Error executing task success callbacks", e);
  104754. }
  104755. };
  104756. var error = function (message, exception) {
  104757. task._setErrorObject(message, exception);
  104758. if (_this.onTaskError) {
  104759. _this.onTaskError(task);
  104760. }
  104761. _this.onTaskErrorObservable.notifyObservers(task);
  104762. _this._decreaseWaitingTasksCount(task);
  104763. };
  104764. task.run(this._scene, done, error);
  104765. };
  104766. /**
  104767. * Reset the {BABYLON.AssetsManager} and remove all tasks
  104768. * @return the current instance of the {BABYLON.AssetsManager}
  104769. */
  104770. AssetsManager.prototype.reset = function () {
  104771. this._isLoading = false;
  104772. this._tasks = new Array();
  104773. return this;
  104774. };
  104775. /**
  104776. * Start the loading process
  104777. * @return the current instance of the {BABYLON.AssetsManager}
  104778. */
  104779. AssetsManager.prototype.load = function () {
  104780. if (this._isLoading) {
  104781. return this;
  104782. }
  104783. this._isLoading = true;
  104784. this._waitingTasksCount = this._tasks.length;
  104785. this._totalTasksCount = this._tasks.length;
  104786. if (this._waitingTasksCount === 0) {
  104787. this._isLoading = false;
  104788. if (this.onFinish) {
  104789. this.onFinish(this._tasks);
  104790. }
  104791. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104792. return this;
  104793. }
  104794. if (this.useDefaultLoadingScreen) {
  104795. this._scene.getEngine().displayLoadingUI();
  104796. }
  104797. for (var index = 0; index < this._tasks.length; index++) {
  104798. var task = this._tasks[index];
  104799. if (task.taskState === AssetTaskState.INIT) {
  104800. this._runTask(task);
  104801. }
  104802. }
  104803. return this;
  104804. };
  104805. return AssetsManager;
  104806. }());
  104807. BABYLON.AssetsManager = AssetsManager;
  104808. })(BABYLON || (BABYLON = {}));
  104809. //# sourceMappingURL=babylon.assetsManager.js.map
  104810. var BABYLON;
  104811. (function (BABYLON) {
  104812. var serializedGeometries = [];
  104813. var serializeGeometry = function (geometry, serializationGeometries) {
  104814. if (serializedGeometries[geometry.id]) {
  104815. return;
  104816. }
  104817. if (geometry.doNotSerialize) {
  104818. return;
  104819. }
  104820. if (geometry instanceof BABYLON.BoxGeometry) {
  104821. serializationGeometries.boxes.push(geometry.serialize());
  104822. }
  104823. else if (geometry instanceof BABYLON.SphereGeometry) {
  104824. serializationGeometries.spheres.push(geometry.serialize());
  104825. }
  104826. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104827. serializationGeometries.cylinders.push(geometry.serialize());
  104828. }
  104829. else if (geometry instanceof BABYLON.TorusGeometry) {
  104830. serializationGeometries.toruses.push(geometry.serialize());
  104831. }
  104832. else if (geometry instanceof BABYLON.GroundGeometry) {
  104833. serializationGeometries.grounds.push(geometry.serialize());
  104834. }
  104835. else if (geometry instanceof BABYLON.Plane) {
  104836. serializationGeometries.planes.push(geometry.serialize());
  104837. }
  104838. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104839. serializationGeometries.torusKnots.push(geometry.serialize());
  104840. }
  104841. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104842. throw new Error("Unknown primitive type");
  104843. }
  104844. else {
  104845. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104846. }
  104847. serializedGeometries[geometry.id] = true;
  104848. };
  104849. var serializeMesh = function (mesh, serializationScene) {
  104850. var serializationObject = {};
  104851. // Geometry
  104852. var geometry = mesh._geometry;
  104853. if (geometry) {
  104854. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104855. // 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
  104856. serializeGeometry(geometry, serializationScene.geometries);
  104857. }
  104858. }
  104859. // Custom
  104860. if (mesh.serialize) {
  104861. mesh.serialize(serializationObject);
  104862. }
  104863. return serializationObject;
  104864. };
  104865. var finalizeSingleMesh = function (mesh, serializationObject) {
  104866. //only works if the mesh is already loaded
  104867. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104868. //serialize material
  104869. if (mesh.material) {
  104870. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104871. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104872. serializationObject.materials = serializationObject.materials || [];
  104873. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104874. serializationObject.multiMaterials.push(mesh.material.serialize());
  104875. var _loop_1 = function (submaterial) {
  104876. if (submaterial) {
  104877. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104878. serializationObject.materials.push(submaterial.serialize());
  104879. }
  104880. }
  104881. };
  104882. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104883. var submaterial = _a[_i];
  104884. _loop_1(submaterial);
  104885. }
  104886. }
  104887. }
  104888. else {
  104889. serializationObject.materials = serializationObject.materials || [];
  104890. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104891. serializationObject.materials.push(mesh.material.serialize());
  104892. }
  104893. }
  104894. }
  104895. //serialize geometry
  104896. var geometry = mesh._geometry;
  104897. if (geometry) {
  104898. if (!serializationObject.geometries) {
  104899. serializationObject.geometries = {};
  104900. serializationObject.geometries.boxes = [];
  104901. serializationObject.geometries.spheres = [];
  104902. serializationObject.geometries.cylinders = [];
  104903. serializationObject.geometries.toruses = [];
  104904. serializationObject.geometries.grounds = [];
  104905. serializationObject.geometries.planes = [];
  104906. serializationObject.geometries.torusKnots = [];
  104907. serializationObject.geometries.vertexData = [];
  104908. }
  104909. serializeGeometry(geometry, serializationObject.geometries);
  104910. }
  104911. // Skeletons
  104912. if (mesh.skeleton) {
  104913. serializationObject.skeletons = serializationObject.skeletons || [];
  104914. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104915. }
  104916. //serialize the actual mesh
  104917. serializationObject.meshes = serializationObject.meshes || [];
  104918. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104919. }
  104920. };
  104921. var SceneSerializer = /** @class */ (function () {
  104922. function SceneSerializer() {
  104923. }
  104924. SceneSerializer.ClearCache = function () {
  104925. serializedGeometries = [];
  104926. };
  104927. SceneSerializer.Serialize = function (scene) {
  104928. var serializationObject = {};
  104929. SceneSerializer.ClearCache();
  104930. // Scene
  104931. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104932. serializationObject.autoClear = scene.autoClear;
  104933. serializationObject.clearColor = scene.clearColor.asArray();
  104934. serializationObject.ambientColor = scene.ambientColor.asArray();
  104935. serializationObject.gravity = scene.gravity.asArray();
  104936. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104937. serializationObject.workerCollisions = scene.workerCollisions;
  104938. // Fog
  104939. if (scene.fogMode && scene.fogMode !== 0) {
  104940. serializationObject.fogMode = scene.fogMode;
  104941. serializationObject.fogColor = scene.fogColor.asArray();
  104942. serializationObject.fogStart = scene.fogStart;
  104943. serializationObject.fogEnd = scene.fogEnd;
  104944. serializationObject.fogDensity = scene.fogDensity;
  104945. }
  104946. //Physics
  104947. if (scene.isPhysicsEnabled()) {
  104948. var physicEngine = scene.getPhysicsEngine();
  104949. if (physicEngine) {
  104950. serializationObject.physicsEnabled = true;
  104951. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104952. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104953. }
  104954. }
  104955. // Metadata
  104956. if (scene.metadata) {
  104957. serializationObject.metadata = scene.metadata;
  104958. }
  104959. // Morph targets
  104960. serializationObject.morphTargetManagers = [];
  104961. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104962. var abstractMesh = _a[_i];
  104963. var manager = abstractMesh.morphTargetManager;
  104964. if (manager) {
  104965. serializationObject.morphTargetManagers.push(manager.serialize());
  104966. }
  104967. }
  104968. // Lights
  104969. serializationObject.lights = [];
  104970. var index;
  104971. var light;
  104972. for (index = 0; index < scene.lights.length; index++) {
  104973. light = scene.lights[index];
  104974. if (!light.doNotSerialize) {
  104975. serializationObject.lights.push(light.serialize());
  104976. }
  104977. }
  104978. // Cameras
  104979. serializationObject.cameras = [];
  104980. for (index = 0; index < scene.cameras.length; index++) {
  104981. var camera = scene.cameras[index];
  104982. if (!camera.doNotSerialize) {
  104983. serializationObject.cameras.push(camera.serialize());
  104984. }
  104985. }
  104986. if (scene.activeCamera) {
  104987. serializationObject.activeCameraID = scene.activeCamera.id;
  104988. }
  104989. // Animations
  104990. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104991. // Materials
  104992. serializationObject.materials = [];
  104993. serializationObject.multiMaterials = [];
  104994. var material;
  104995. for (index = 0; index < scene.materials.length; index++) {
  104996. material = scene.materials[index];
  104997. if (!material.doNotSerialize) {
  104998. serializationObject.materials.push(material.serialize());
  104999. }
  105000. }
  105001. // MultiMaterials
  105002. serializationObject.multiMaterials = [];
  105003. for (index = 0; index < scene.multiMaterials.length; index++) {
  105004. var multiMaterial = scene.multiMaterials[index];
  105005. serializationObject.multiMaterials.push(multiMaterial.serialize());
  105006. }
  105007. // Environment texture
  105008. if (scene.environmentTexture) {
  105009. serializationObject.environmentTexture = scene.environmentTexture.name;
  105010. }
  105011. // Skeletons
  105012. serializationObject.skeletons = [];
  105013. for (index = 0; index < scene.skeletons.length; index++) {
  105014. var skeleton = scene.skeletons[index];
  105015. if (!skeleton.doNotSerialize) {
  105016. serializationObject.skeletons.push(skeleton.serialize());
  105017. }
  105018. }
  105019. // Transform nodes
  105020. serializationObject.transformNodes = [];
  105021. for (index = 0; index < scene.transformNodes.length; index++) {
  105022. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  105023. }
  105024. // Geometries
  105025. serializationObject.geometries = {};
  105026. serializationObject.geometries.boxes = [];
  105027. serializationObject.geometries.spheres = [];
  105028. serializationObject.geometries.cylinders = [];
  105029. serializationObject.geometries.toruses = [];
  105030. serializationObject.geometries.grounds = [];
  105031. serializationObject.geometries.planes = [];
  105032. serializationObject.geometries.torusKnots = [];
  105033. serializationObject.geometries.vertexData = [];
  105034. serializedGeometries = [];
  105035. var geometries = scene.getGeometries();
  105036. for (index = 0; index < geometries.length; index++) {
  105037. var geometry = geometries[index];
  105038. if (geometry.isReady()) {
  105039. serializeGeometry(geometry, serializationObject.geometries);
  105040. }
  105041. }
  105042. // Meshes
  105043. serializationObject.meshes = [];
  105044. for (index = 0; index < scene.meshes.length; index++) {
  105045. var abstractMesh = scene.meshes[index];
  105046. if (abstractMesh instanceof BABYLON.Mesh) {
  105047. var mesh = abstractMesh;
  105048. if (!mesh.doNotSerialize) {
  105049. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  105050. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  105051. }
  105052. }
  105053. }
  105054. }
  105055. // Particles Systems
  105056. serializationObject.particleSystems = [];
  105057. for (index = 0; index < scene.particleSystems.length; index++) {
  105058. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  105059. }
  105060. // Action Manager
  105061. if (scene.actionManager) {
  105062. serializationObject.actions = scene.actionManager.serialize("scene");
  105063. }
  105064. // Components
  105065. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  105066. var component = _c[_b];
  105067. component.serialize(serializationObject);
  105068. }
  105069. return serializationObject;
  105070. };
  105071. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  105072. if (withParents === void 0) { withParents = false; }
  105073. if (withChildren === void 0) { withChildren = false; }
  105074. var serializationObject = {};
  105075. SceneSerializer.ClearCache();
  105076. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  105077. if (withParents || withChildren) {
  105078. //deliberate for loop! not for each, appended should be processed as well.
  105079. for (var i = 0; i < toSerialize.length; ++i) {
  105080. if (withChildren) {
  105081. toSerialize[i].getDescendants().forEach(function (node) {
  105082. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  105083. toSerialize.push(node);
  105084. }
  105085. });
  105086. }
  105087. //make sure the array doesn't contain the object already
  105088. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  105089. toSerialize.push(toSerialize[i].parent);
  105090. }
  105091. }
  105092. }
  105093. toSerialize.forEach(function (mesh) {
  105094. finalizeSingleMesh(mesh, serializationObject);
  105095. });
  105096. return serializationObject;
  105097. };
  105098. return SceneSerializer;
  105099. }());
  105100. BABYLON.SceneSerializer = SceneSerializer;
  105101. })(BABYLON || (BABYLON = {}));
  105102. //# sourceMappingURL=babylon.sceneSerializer.js.map
  105103. var BABYLON;
  105104. (function (BABYLON) {
  105105. /**
  105106. * Class used to generate realtime reflection / refraction cube textures
  105107. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  105108. */
  105109. var ReflectionProbe = /** @class */ (function () {
  105110. /**
  105111. * Creates a new reflection probe
  105112. * @param name defines the name of the probe
  105113. * @param size defines the texture resolution (for each face)
  105114. * @param scene defines the hosting scene
  105115. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  105116. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  105117. */
  105118. function ReflectionProbe(
  105119. /** defines the name of the probe */
  105120. name, size, scene, generateMipMaps, useFloat) {
  105121. if (generateMipMaps === void 0) { generateMipMaps = true; }
  105122. if (useFloat === void 0) { useFloat = false; }
  105123. var _this = this;
  105124. this.name = name;
  105125. this._viewMatrix = BABYLON.Matrix.Identity();
  105126. this._target = BABYLON.Vector3.Zero();
  105127. this._add = BABYLON.Vector3.Zero();
  105128. this._invertYAxis = false;
  105129. /** Gets or sets probe position (center of the cube map) */
  105130. this.position = BABYLON.Vector3.Zero();
  105131. this._scene = scene;
  105132. // Create the scene field if not exist.
  105133. if (!this._scene.reflectionProbes) {
  105134. this._scene.reflectionProbes = new Array();
  105135. }
  105136. this._scene.reflectionProbes.push(this);
  105137. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  105138. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  105139. switch (faceIndex) {
  105140. case 0:
  105141. _this._add.copyFromFloats(1, 0, 0);
  105142. break;
  105143. case 1:
  105144. _this._add.copyFromFloats(-1, 0, 0);
  105145. break;
  105146. case 2:
  105147. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  105148. break;
  105149. case 3:
  105150. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  105151. break;
  105152. case 4:
  105153. _this._add.copyFromFloats(0, 0, 1);
  105154. break;
  105155. case 5:
  105156. _this._add.copyFromFloats(0, 0, -1);
  105157. break;
  105158. }
  105159. if (_this._attachedMesh) {
  105160. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  105161. }
  105162. _this.position.addToRef(_this._add, _this._target);
  105163. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  105164. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  105165. scene._forcedViewPosition = _this.position;
  105166. });
  105167. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  105168. scene._forcedViewPosition = null;
  105169. scene.updateTransformMatrix(true);
  105170. });
  105171. if (scene.activeCamera) {
  105172. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  105173. }
  105174. }
  105175. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  105176. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  105177. get: function () {
  105178. return this._renderTargetTexture.samples;
  105179. },
  105180. set: function (value) {
  105181. this._renderTargetTexture.samples = value;
  105182. },
  105183. enumerable: true,
  105184. configurable: true
  105185. });
  105186. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  105187. /** Gets or sets the refresh rate to use (on every frame by default) */
  105188. get: function () {
  105189. return this._renderTargetTexture.refreshRate;
  105190. },
  105191. set: function (value) {
  105192. this._renderTargetTexture.refreshRate = value;
  105193. },
  105194. enumerable: true,
  105195. configurable: true
  105196. });
  105197. /**
  105198. * Gets the hosting scene
  105199. * @returns a Scene
  105200. */
  105201. ReflectionProbe.prototype.getScene = function () {
  105202. return this._scene;
  105203. };
  105204. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  105205. /** Gets the internal CubeTexture used to render to */
  105206. get: function () {
  105207. return this._renderTargetTexture;
  105208. },
  105209. enumerable: true,
  105210. configurable: true
  105211. });
  105212. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  105213. /** Gets the list of meshes to render */
  105214. get: function () {
  105215. return this._renderTargetTexture.renderList;
  105216. },
  105217. enumerable: true,
  105218. configurable: true
  105219. });
  105220. /**
  105221. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  105222. * @param mesh defines the mesh to attach to
  105223. */
  105224. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  105225. this._attachedMesh = mesh;
  105226. };
  105227. /**
  105228. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  105229. * @param renderingGroupId The rendering group id corresponding to its index
  105230. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  105231. */
  105232. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  105233. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  105234. };
  105235. /**
  105236. * Clean all associated resources
  105237. */
  105238. ReflectionProbe.prototype.dispose = function () {
  105239. var index = this._scene.reflectionProbes.indexOf(this);
  105240. if (index !== -1) {
  105241. // Remove from the scene if found
  105242. this._scene.reflectionProbes.splice(index, 1);
  105243. }
  105244. if (this._renderTargetTexture) {
  105245. this._renderTargetTexture.dispose();
  105246. this._renderTargetTexture = null;
  105247. }
  105248. };
  105249. return ReflectionProbe;
  105250. }());
  105251. BABYLON.ReflectionProbe = ReflectionProbe;
  105252. })(BABYLON || (BABYLON = {}));
  105253. //# sourceMappingURL=babylon.reflectionProbe.js.map
  105254. var BABYLON;
  105255. (function (BABYLON) {
  105256. /**
  105257. * Defines the layer scene component responsible to manage any layers
  105258. * in a given scene.
  105259. */
  105260. var LayerSceneComponent = /** @class */ (function () {
  105261. /**
  105262. * Creates a new instance of the component for the given scene
  105263. * @param scene Defines the scene to register the component in
  105264. */
  105265. function LayerSceneComponent(scene) {
  105266. /**
  105267. * The component name helpfull to identify the component in the list of scene components.
  105268. */
  105269. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  105270. this.scene = scene;
  105271. this._engine = scene.getEngine();
  105272. scene.layers = new Array();
  105273. }
  105274. /**
  105275. * Registers the component in a given scene
  105276. */
  105277. LayerSceneComponent.prototype.register = function () {
  105278. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  105279. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  105280. };
  105281. /**
  105282. * Rebuilds the elements related to this component in case of
  105283. * context lost for instance.
  105284. */
  105285. LayerSceneComponent.prototype.rebuild = function () {
  105286. var layers = this.scene.layers;
  105287. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  105288. var layer = layers_1[_i];
  105289. layer._rebuild();
  105290. }
  105291. };
  105292. /**
  105293. * Disposes the component and the associated ressources.
  105294. */
  105295. LayerSceneComponent.prototype.dispose = function () {
  105296. var layers = this.scene.layers;
  105297. while (layers.length) {
  105298. layers[0].dispose();
  105299. }
  105300. };
  105301. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  105302. var layers = this.scene.layers;
  105303. if (layers.length) {
  105304. this._engine.setDepthBuffer(false);
  105305. var cameraLayerMask = camera.layerMask;
  105306. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105307. var layer = layers_2[_i];
  105308. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  105309. layer.render();
  105310. }
  105311. }
  105312. this._engine.setDepthBuffer(true);
  105313. }
  105314. };
  105315. LayerSceneComponent.prototype._drawBackground = function (camera) {
  105316. this._draw(camera, true);
  105317. };
  105318. LayerSceneComponent.prototype._drawForeground = function (camera) {
  105319. this._draw(camera, false);
  105320. };
  105321. return LayerSceneComponent;
  105322. }());
  105323. BABYLON.LayerSceneComponent = LayerSceneComponent;
  105324. })(BABYLON || (BABYLON = {}));
  105325. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  105326. var BABYLON;
  105327. (function (BABYLON) {
  105328. var Layer = /** @class */ (function () {
  105329. function Layer(name, imgUrl, scene, isBackground, color) {
  105330. this.name = name;
  105331. this.scale = new BABYLON.Vector2(1, 1);
  105332. this.offset = new BABYLON.Vector2(0, 0);
  105333. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  105334. this.layerMask = 0x0FFFFFFF;
  105335. this._vertexBuffers = {};
  105336. // Events
  105337. /**
  105338. * An event triggered when the layer is disposed.
  105339. */
  105340. this.onDisposeObservable = new BABYLON.Observable();
  105341. /**
  105342. * An event triggered before rendering the scene
  105343. */
  105344. this.onBeforeRenderObservable = new BABYLON.Observable();
  105345. /**
  105346. * An event triggered after rendering the scene
  105347. */
  105348. this.onAfterRenderObservable = new BABYLON.Observable();
  105349. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  105350. this.isBackground = isBackground === undefined ? true : isBackground;
  105351. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  105352. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  105353. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  105354. if (!layerComponent) {
  105355. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  105356. this._scene._addComponent(layerComponent);
  105357. }
  105358. this._scene.layers.push(this);
  105359. var engine = this._scene.getEngine();
  105360. // VBO
  105361. var vertices = [];
  105362. vertices.push(1, 1);
  105363. vertices.push(-1, 1);
  105364. vertices.push(-1, -1);
  105365. vertices.push(1, -1);
  105366. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105367. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105368. this._createIndexBuffer();
  105369. // Effects
  105370. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  105371. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  105372. }
  105373. Object.defineProperty(Layer.prototype, "onDispose", {
  105374. set: function (callback) {
  105375. if (this._onDisposeObserver) {
  105376. this.onDisposeObservable.remove(this._onDisposeObserver);
  105377. }
  105378. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105379. },
  105380. enumerable: true,
  105381. configurable: true
  105382. });
  105383. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  105384. set: function (callback) {
  105385. if (this._onBeforeRenderObserver) {
  105386. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  105387. }
  105388. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  105389. },
  105390. enumerable: true,
  105391. configurable: true
  105392. });
  105393. Object.defineProperty(Layer.prototype, "onAfterRender", {
  105394. set: function (callback) {
  105395. if (this._onAfterRenderObserver) {
  105396. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105397. }
  105398. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  105399. },
  105400. enumerable: true,
  105401. configurable: true
  105402. });
  105403. Layer.prototype._createIndexBuffer = function () {
  105404. var engine = this._scene.getEngine();
  105405. // Indices
  105406. var indices = [];
  105407. indices.push(0);
  105408. indices.push(1);
  105409. indices.push(2);
  105410. indices.push(0);
  105411. indices.push(2);
  105412. indices.push(3);
  105413. this._indexBuffer = engine.createIndexBuffer(indices);
  105414. };
  105415. /** @hidden */
  105416. Layer.prototype._rebuild = function () {
  105417. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105418. if (vb) {
  105419. vb._rebuild();
  105420. }
  105421. this._createIndexBuffer();
  105422. };
  105423. Layer.prototype.render = function () {
  105424. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  105425. // Check
  105426. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  105427. return;
  105428. var engine = this._scene.getEngine();
  105429. this.onBeforeRenderObservable.notifyObservers(this);
  105430. // Render
  105431. engine.enableEffect(currentEffect);
  105432. engine.setState(false);
  105433. // Texture
  105434. currentEffect.setTexture("textureSampler", this.texture);
  105435. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  105436. // Color
  105437. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  105438. // Scale / offset
  105439. currentEffect.setVector2("offset", this.offset);
  105440. currentEffect.setVector2("scale", this.scale);
  105441. // VBOs
  105442. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105443. // Draw order
  105444. if (!this.alphaTest) {
  105445. engine.setAlphaMode(this.alphaBlendingMode);
  105446. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105447. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105448. }
  105449. else {
  105450. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105451. }
  105452. this.onAfterRenderObservable.notifyObservers(this);
  105453. };
  105454. Layer.prototype.dispose = function () {
  105455. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105456. if (vertexBuffer) {
  105457. vertexBuffer.dispose();
  105458. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105459. }
  105460. if (this._indexBuffer) {
  105461. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105462. this._indexBuffer = null;
  105463. }
  105464. if (this.texture) {
  105465. this.texture.dispose();
  105466. this.texture = null;
  105467. }
  105468. // Remove from scene
  105469. var index = this._scene.layers.indexOf(this);
  105470. this._scene.layers.splice(index, 1);
  105471. // Callback
  105472. this.onDisposeObservable.notifyObservers(this);
  105473. this.onDisposeObservable.clear();
  105474. this.onAfterRenderObservable.clear();
  105475. this.onBeforeRenderObservable.clear();
  105476. };
  105477. return Layer;
  105478. }());
  105479. BABYLON.Layer = Layer;
  105480. })(BABYLON || (BABYLON = {}));
  105481. //# sourceMappingURL=babylon.layer.js.map
  105482. var BABYLON;
  105483. (function (BABYLON) {
  105484. var TextureTools = /** @class */ (function () {
  105485. function TextureTools() {
  105486. }
  105487. /**
  105488. * Uses the GPU to create a copy texture rescaled at a given size
  105489. * @param texture Texture to copy from
  105490. * @param width Desired width
  105491. * @param height Desired height
  105492. * @return Generated texture
  105493. */
  105494. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  105495. if (useBilinearMode === void 0) { useBilinearMode = true; }
  105496. var scene = texture.getScene();
  105497. var engine = scene.getEngine();
  105498. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  105499. rtt.wrapU = texture.wrapU;
  105500. rtt.wrapV = texture.wrapV;
  105501. rtt.uOffset = texture.uOffset;
  105502. rtt.vOffset = texture.vOffset;
  105503. rtt.uScale = texture.uScale;
  105504. rtt.vScale = texture.vScale;
  105505. rtt.uAng = texture.uAng;
  105506. rtt.vAng = texture.vAng;
  105507. rtt.wAng = texture.wAng;
  105508. rtt.coordinatesIndex = texture.coordinatesIndex;
  105509. rtt.level = texture.level;
  105510. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  105511. rtt._texture.isReady = false;
  105512. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105513. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105514. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105515. passPostProcess.getEffect().executeWhenCompiled(function () {
  105516. passPostProcess.onApply = function (effect) {
  105517. effect.setTexture("textureSampler", texture);
  105518. };
  105519. var internalTexture = rtt.getInternalTexture();
  105520. if (internalTexture) {
  105521. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  105522. engine.unBindFramebuffer(internalTexture);
  105523. rtt.disposeFramebufferObjects();
  105524. passPostProcess.dispose();
  105525. internalTexture.isReady = true;
  105526. }
  105527. });
  105528. return rtt;
  105529. };
  105530. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  105531. if (!scene._environmentBRDFTexture) {
  105532. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105533. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105534. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105535. scene._environmentBRDFTexture = texture;
  105536. }
  105537. return scene._environmentBRDFTexture;
  105538. };
  105539. 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=";
  105540. return TextureTools;
  105541. }());
  105542. BABYLON.TextureTools = TextureTools;
  105543. })(BABYLON || (BABYLON = {}));
  105544. //# sourceMappingURL=babylon.textureTools.js.map
  105545. var BABYLON;
  105546. (function (BABYLON) {
  105547. var FramingBehavior = /** @class */ (function () {
  105548. function FramingBehavior() {
  105549. this._mode = FramingBehavior.FitFrustumSidesMode;
  105550. this._radiusScale = 1.0;
  105551. this._positionScale = 0.5;
  105552. this._defaultElevation = 0.3;
  105553. this._elevationReturnTime = 1500;
  105554. this._elevationReturnWaitTime = 1000;
  105555. this._zoomStopsAnimation = false;
  105556. this._framingTime = 1500;
  105557. this._isPointerDown = false;
  105558. this._lastInteractionTime = -Infinity;
  105559. // Framing control
  105560. this._animatables = new Array();
  105561. this._betaIsAnimating = false;
  105562. }
  105563. Object.defineProperty(FramingBehavior.prototype, "name", {
  105564. get: function () {
  105565. return "Framing";
  105566. },
  105567. enumerable: true,
  105568. configurable: true
  105569. });
  105570. Object.defineProperty(FramingBehavior.prototype, "mode", {
  105571. /**
  105572. * Gets current mode used by the behavior.
  105573. */
  105574. get: function () {
  105575. return this._mode;
  105576. },
  105577. /**
  105578. * Sets the current mode used by the behavior
  105579. */
  105580. set: function (mode) {
  105581. this._mode = mode;
  105582. },
  105583. enumerable: true,
  105584. configurable: true
  105585. });
  105586. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  105587. /**
  105588. * Gets the scale applied to the radius
  105589. */
  105590. get: function () {
  105591. return this._radiusScale;
  105592. },
  105593. /**
  105594. * Sets the scale applied to the radius (1 by default)
  105595. */
  105596. set: function (radius) {
  105597. this._radiusScale = radius;
  105598. },
  105599. enumerable: true,
  105600. configurable: true
  105601. });
  105602. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  105603. /**
  105604. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105605. */
  105606. get: function () {
  105607. return this._positionScale;
  105608. },
  105609. /**
  105610. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105611. */
  105612. set: function (scale) {
  105613. this._positionScale = scale;
  105614. },
  105615. enumerable: true,
  105616. configurable: true
  105617. });
  105618. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  105619. /**
  105620. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105621. * behaviour is triggered, in radians.
  105622. */
  105623. get: function () {
  105624. return this._defaultElevation;
  105625. },
  105626. /**
  105627. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105628. * behaviour is triggered, in radians.
  105629. */
  105630. set: function (elevation) {
  105631. this._defaultElevation = elevation;
  105632. },
  105633. enumerable: true,
  105634. configurable: true
  105635. });
  105636. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  105637. /**
  105638. * Gets the time (in milliseconds) taken to return to the default beta position.
  105639. * Negative value indicates camera should not return to default.
  105640. */
  105641. get: function () {
  105642. return this._elevationReturnTime;
  105643. },
  105644. /**
  105645. * Sets the time (in milliseconds) taken to return to the default beta position.
  105646. * Negative value indicates camera should not return to default.
  105647. */
  105648. set: function (speed) {
  105649. this._elevationReturnTime = speed;
  105650. },
  105651. enumerable: true,
  105652. configurable: true
  105653. });
  105654. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  105655. /**
  105656. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105657. */
  105658. get: function () {
  105659. return this._elevationReturnWaitTime;
  105660. },
  105661. /**
  105662. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105663. */
  105664. set: function (time) {
  105665. this._elevationReturnWaitTime = time;
  105666. },
  105667. enumerable: true,
  105668. configurable: true
  105669. });
  105670. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  105671. /**
  105672. * Gets the flag that indicates if user zooming should stop animation.
  105673. */
  105674. get: function () {
  105675. return this._zoomStopsAnimation;
  105676. },
  105677. /**
  105678. * Sets the flag that indicates if user zooming should stop animation.
  105679. */
  105680. set: function (flag) {
  105681. this._zoomStopsAnimation = flag;
  105682. },
  105683. enumerable: true,
  105684. configurable: true
  105685. });
  105686. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  105687. /**
  105688. * Gets the transition time when framing the mesh, in milliseconds
  105689. */
  105690. get: function () {
  105691. return this._framingTime;
  105692. },
  105693. /**
  105694. * Sets the transition time when framing the mesh, in milliseconds
  105695. */
  105696. set: function (time) {
  105697. this._framingTime = time;
  105698. },
  105699. enumerable: true,
  105700. configurable: true
  105701. });
  105702. FramingBehavior.prototype.init = function () {
  105703. // Do notihng
  105704. };
  105705. FramingBehavior.prototype.attach = function (camera) {
  105706. var _this = this;
  105707. this._attachedCamera = camera;
  105708. var scene = this._attachedCamera.getScene();
  105709. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  105710. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105711. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105712. _this._isPointerDown = true;
  105713. return;
  105714. }
  105715. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105716. _this._isPointerDown = false;
  105717. }
  105718. });
  105719. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105720. if (mesh) {
  105721. _this.zoomOnMesh(mesh);
  105722. }
  105723. });
  105724. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105725. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105726. _this._applyUserInteraction();
  105727. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  105728. // back to the default position after a given timeout
  105729. _this._maintainCameraAboveGround();
  105730. });
  105731. };
  105732. FramingBehavior.prototype.detach = function () {
  105733. if (!this._attachedCamera) {
  105734. return;
  105735. }
  105736. var scene = this._attachedCamera.getScene();
  105737. if (this._onPrePointerObservableObserver) {
  105738. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105739. }
  105740. if (this._onAfterCheckInputsObserver) {
  105741. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105742. }
  105743. if (this._onMeshTargetChangedObserver) {
  105744. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105745. }
  105746. this._attachedCamera = null;
  105747. };
  105748. /**
  105749. * Targets the given mesh and updates zoom level accordingly.
  105750. * @param mesh The mesh to target.
  105751. * @param radius Optional. If a cached radius position already exists, overrides default.
  105752. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105753. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105754. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105755. */
  105756. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105757. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105758. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105759. mesh.computeWorldMatrix(true);
  105760. var boundingBox = mesh.getBoundingInfo().boundingBox;
  105761. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  105762. };
  105763. /**
  105764. * Targets the given mesh with its children and updates zoom level accordingly.
  105765. * @param mesh The mesh to target.
  105766. * @param radius Optional. If a cached radius position already exists, overrides default.
  105767. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105768. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105769. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105770. */
  105771. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105772. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105773. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105774. mesh.computeWorldMatrix(true);
  105775. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  105776. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105777. };
  105778. /**
  105779. * Targets the given meshes with their children and updates zoom level accordingly.
  105780. * @param meshes The mesh to target.
  105781. * @param radius Optional. If a cached radius position already exists, overrides default.
  105782. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105783. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105784. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105785. */
  105786. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105787. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105788. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105789. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105790. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105791. for (var i = 0; i < meshes.length; i++) {
  105792. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105793. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105794. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105795. }
  105796. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105797. };
  105798. /**
  105799. * Targets the given mesh and updates zoom level accordingly.
  105800. * @param mesh The mesh to target.
  105801. * @param radius Optional. If a cached radius position already exists, overrides default.
  105802. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105803. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105804. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105805. */
  105806. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105807. var _this = this;
  105808. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105809. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105810. var zoomTarget;
  105811. if (!this._attachedCamera) {
  105812. return;
  105813. }
  105814. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105815. var bottom = minimumWorld.y;
  105816. var top = maximumWorld.y;
  105817. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105818. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105819. if (focusOnOriginXZ) {
  105820. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105821. }
  105822. else {
  105823. var centerWorld = minimumWorld.add(radiusWorld);
  105824. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105825. }
  105826. if (!this._vectorTransition) {
  105827. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105828. }
  105829. this._betaIsAnimating = true;
  105830. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105831. if (animatable) {
  105832. this._animatables.push(animatable);
  105833. }
  105834. // sets the radius and lower radius bounds
  105835. // Small delta ensures camera is not always at lower zoom limit.
  105836. var radius = 0;
  105837. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105838. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105839. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105840. radius = position;
  105841. }
  105842. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105843. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105844. if (this._attachedCamera.lowerRadiusLimit === null) {
  105845. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105846. }
  105847. }
  105848. // Set sensibilities
  105849. var extend = maximumWorld.subtract(minimumWorld).length();
  105850. this._attachedCamera.panningSensibility = 5000 / extend;
  105851. this._attachedCamera.wheelPrecision = 100 / radius;
  105852. // transition to new radius
  105853. if (!this._radiusTransition) {
  105854. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105855. }
  105856. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105857. _this.stopAllAnimations();
  105858. if (onAnimationEnd) {
  105859. onAnimationEnd();
  105860. }
  105861. if (_this._attachedCamera) {
  105862. _this._attachedCamera.storeState();
  105863. }
  105864. });
  105865. if (animatable) {
  105866. this._animatables.push(animatable);
  105867. }
  105868. };
  105869. /**
  105870. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105871. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105872. * frustum width.
  105873. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105874. * to fully enclose the mesh in the viewing frustum.
  105875. */
  105876. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105877. var size = maximumWorld.subtract(minimumWorld);
  105878. var boxVectorGlobalDiagonal = size.length();
  105879. var frustumSlope = this._getFrustumSlope();
  105880. // Formula for setting distance
  105881. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105882. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105883. // Horizon distance
  105884. var radius = radiusWithoutFraming * this._radiusScale;
  105885. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105886. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105887. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105888. var camera = this._attachedCamera;
  105889. if (!camera) {
  105890. return 0;
  105891. }
  105892. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105893. // Don't exceed the requested limit
  105894. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105895. }
  105896. // Don't exceed the upper radius limit
  105897. if (camera.upperRadiusLimit) {
  105898. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105899. }
  105900. return distance;
  105901. };
  105902. /**
  105903. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105904. * is automatically returned to its default position (expected to be above ground plane).
  105905. */
  105906. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105907. var _this = this;
  105908. if (this._elevationReturnTime < 0) {
  105909. return;
  105910. }
  105911. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105912. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105913. var limitBeta = Math.PI * 0.5;
  105914. // Bring the camera back up if below the ground plane
  105915. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105916. this._betaIsAnimating = true;
  105917. //Transition to new position
  105918. this.stopAllAnimations();
  105919. if (!this._betaTransition) {
  105920. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105921. }
  105922. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105923. _this._clearAnimationLocks();
  105924. _this.stopAllAnimations();
  105925. });
  105926. if (animatabe) {
  105927. this._animatables.push(animatabe);
  105928. }
  105929. }
  105930. };
  105931. /**
  105932. * Returns the frustum slope based on the canvas ratio and camera FOV
  105933. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105934. */
  105935. FramingBehavior.prototype._getFrustumSlope = function () {
  105936. // Calculate the viewport ratio
  105937. // Aspect Ratio is Height/Width.
  105938. var camera = this._attachedCamera;
  105939. if (!camera) {
  105940. return BABYLON.Vector2.Zero();
  105941. }
  105942. var engine = camera.getScene().getEngine();
  105943. var aspectRatio = engine.getAspectRatio(camera);
  105944. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105945. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105946. var frustumSlopeY = Math.tan(camera.fov / 2);
  105947. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105948. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105949. // along the forward vector.
  105950. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105951. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105952. };
  105953. /**
  105954. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105955. */
  105956. FramingBehavior.prototype._clearAnimationLocks = function () {
  105957. this._betaIsAnimating = false;
  105958. };
  105959. /**
  105960. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105961. */
  105962. FramingBehavior.prototype._applyUserInteraction = function () {
  105963. if (this.isUserIsMoving) {
  105964. this._lastInteractionTime = BABYLON.Tools.Now;
  105965. this.stopAllAnimations();
  105966. this._clearAnimationLocks();
  105967. }
  105968. };
  105969. /**
  105970. * Stops and removes all animations that have been applied to the camera
  105971. */
  105972. FramingBehavior.prototype.stopAllAnimations = function () {
  105973. if (this._attachedCamera) {
  105974. this._attachedCamera.animations = [];
  105975. }
  105976. while (this._animatables.length) {
  105977. if (this._animatables[0]) {
  105978. this._animatables[0].onAnimationEnd = null;
  105979. this._animatables[0].stop();
  105980. }
  105981. this._animatables.shift();
  105982. }
  105983. };
  105984. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105985. /**
  105986. * Gets a value indicating if the user is moving the camera
  105987. */
  105988. get: function () {
  105989. if (!this._attachedCamera) {
  105990. return false;
  105991. }
  105992. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105993. this._attachedCamera.inertialBetaOffset !== 0 ||
  105994. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105995. this._attachedCamera.inertialPanningX !== 0 ||
  105996. this._attachedCamera.inertialPanningY !== 0 ||
  105997. this._isPointerDown;
  105998. },
  105999. enumerable: true,
  106000. configurable: true
  106001. });
  106002. /**
  106003. * The easing function used by animations
  106004. */
  106005. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  106006. /**
  106007. * The easing mode used by animations
  106008. */
  106009. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  106010. // Statics
  106011. /**
  106012. * The camera can move all the way towards the mesh.
  106013. */
  106014. FramingBehavior.IgnoreBoundsSizeMode = 0;
  106015. /**
  106016. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  106017. */
  106018. FramingBehavior.FitFrustumSidesMode = 1;
  106019. return FramingBehavior;
  106020. }());
  106021. BABYLON.FramingBehavior = FramingBehavior;
  106022. })(BABYLON || (BABYLON = {}));
  106023. //# sourceMappingURL=babylon.framingBehavior.js.map
  106024. var BABYLON;
  106025. (function (BABYLON) {
  106026. /**
  106027. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  106028. */
  106029. var BouncingBehavior = /** @class */ (function () {
  106030. function BouncingBehavior() {
  106031. /**
  106032. * The duration of the animation, in milliseconds
  106033. */
  106034. this.transitionDuration = 450;
  106035. /**
  106036. * Length of the distance animated by the transition when lower radius is reached
  106037. */
  106038. this.lowerRadiusTransitionRange = 2;
  106039. /**
  106040. * Length of the distance animated by the transition when upper radius is reached
  106041. */
  106042. this.upperRadiusTransitionRange = -2;
  106043. this._autoTransitionRange = false;
  106044. // Animations
  106045. this._radiusIsAnimating = false;
  106046. this._radiusBounceTransition = null;
  106047. this._animatables = new Array();
  106048. }
  106049. Object.defineProperty(BouncingBehavior.prototype, "name", {
  106050. get: function () {
  106051. return "Bouncing";
  106052. },
  106053. enumerable: true,
  106054. configurable: true
  106055. });
  106056. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  106057. /**
  106058. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  106059. */
  106060. get: function () {
  106061. return this._autoTransitionRange;
  106062. },
  106063. /**
  106064. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  106065. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  106066. */
  106067. set: function (value) {
  106068. var _this = this;
  106069. if (this._autoTransitionRange === value) {
  106070. return;
  106071. }
  106072. this._autoTransitionRange = value;
  106073. var camera = this._attachedCamera;
  106074. if (!camera) {
  106075. return;
  106076. }
  106077. if (value) {
  106078. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  106079. if (!mesh) {
  106080. return;
  106081. }
  106082. mesh.computeWorldMatrix(true);
  106083. var diagonal = mesh.getBoundingInfo().diagonalLength;
  106084. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  106085. _this.upperRadiusTransitionRange = diagonal * 0.05;
  106086. });
  106087. }
  106088. else if (this._onMeshTargetChangedObserver) {
  106089. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  106090. }
  106091. },
  106092. enumerable: true,
  106093. configurable: true
  106094. });
  106095. BouncingBehavior.prototype.init = function () {
  106096. // Do notihng
  106097. };
  106098. BouncingBehavior.prototype.attach = function (camera) {
  106099. var _this = this;
  106100. this._attachedCamera = camera;
  106101. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106102. if (!_this._attachedCamera) {
  106103. return;
  106104. }
  106105. // Add the bounce animation to the lower radius limit
  106106. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  106107. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  106108. }
  106109. // Add the bounce animation to the upper radius limit
  106110. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  106111. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  106112. }
  106113. });
  106114. };
  106115. BouncingBehavior.prototype.detach = function () {
  106116. if (!this._attachedCamera) {
  106117. return;
  106118. }
  106119. if (this._onAfterCheckInputsObserver) {
  106120. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106121. }
  106122. if (this._onMeshTargetChangedObserver) {
  106123. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  106124. }
  106125. this._attachedCamera = null;
  106126. };
  106127. /**
  106128. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  106129. * @param radiusLimit The limit to check against.
  106130. * @return Bool to indicate if at limit.
  106131. */
  106132. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  106133. if (!this._attachedCamera) {
  106134. return false;
  106135. }
  106136. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  106137. return true;
  106138. }
  106139. return false;
  106140. };
  106141. /**
  106142. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  106143. * @param radiusDelta The delta by which to animate to. Can be negative.
  106144. */
  106145. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  106146. var _this = this;
  106147. if (!this._attachedCamera) {
  106148. return;
  106149. }
  106150. if (!this._radiusBounceTransition) {
  106151. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  106152. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  106153. }
  106154. // Prevent zoom until bounce has completed
  106155. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  106156. this._attachedCamera.wheelPrecision = Infinity;
  106157. this._attachedCamera.inertialRadiusOffset = 0;
  106158. // Animate to the radius limit
  106159. this.stopAllAnimations();
  106160. this._radiusIsAnimating = true;
  106161. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  106162. if (animatable) {
  106163. this._animatables.push(animatable);
  106164. }
  106165. };
  106166. /**
  106167. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  106168. */
  106169. BouncingBehavior.prototype._clearAnimationLocks = function () {
  106170. this._radiusIsAnimating = false;
  106171. if (this._attachedCamera) {
  106172. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  106173. }
  106174. };
  106175. /**
  106176. * Stops and removes all animations that have been applied to the camera
  106177. */
  106178. BouncingBehavior.prototype.stopAllAnimations = function () {
  106179. if (this._attachedCamera) {
  106180. this._attachedCamera.animations = [];
  106181. }
  106182. while (this._animatables.length) {
  106183. this._animatables[0].onAnimationEnd = null;
  106184. this._animatables[0].stop();
  106185. this._animatables.shift();
  106186. }
  106187. };
  106188. /**
  106189. * The easing function used by animations
  106190. */
  106191. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  106192. /**
  106193. * The easing mode used by animations
  106194. */
  106195. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  106196. return BouncingBehavior;
  106197. }());
  106198. BABYLON.BouncingBehavior = BouncingBehavior;
  106199. })(BABYLON || (BABYLON = {}));
  106200. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  106201. var BABYLON;
  106202. (function (BABYLON) {
  106203. var AutoRotationBehavior = /** @class */ (function () {
  106204. function AutoRotationBehavior() {
  106205. this._zoomStopsAnimation = false;
  106206. this._idleRotationSpeed = 0.05;
  106207. this._idleRotationWaitTime = 2000;
  106208. this._idleRotationSpinupTime = 2000;
  106209. this._isPointerDown = false;
  106210. this._lastFrameTime = null;
  106211. this._lastInteractionTime = -Infinity;
  106212. this._cameraRotationSpeed = 0;
  106213. this._lastFrameRadius = 0;
  106214. }
  106215. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  106216. get: function () {
  106217. return "AutoRotation";
  106218. },
  106219. enumerable: true,
  106220. configurable: true
  106221. });
  106222. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  106223. /**
  106224. * Gets the flag that indicates if user zooming should stop animation.
  106225. */
  106226. get: function () {
  106227. return this._zoomStopsAnimation;
  106228. },
  106229. /**
  106230. * Sets the flag that indicates if user zooming should stop animation.
  106231. */
  106232. set: function (flag) {
  106233. this._zoomStopsAnimation = flag;
  106234. },
  106235. enumerable: true,
  106236. configurable: true
  106237. });
  106238. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  106239. /**
  106240. * Gets the default speed at which the camera rotates around the model.
  106241. */
  106242. get: function () {
  106243. return this._idleRotationSpeed;
  106244. },
  106245. /**
  106246. * Sets the default speed at which the camera rotates around the model.
  106247. */
  106248. set: function (speed) {
  106249. this._idleRotationSpeed = speed;
  106250. },
  106251. enumerable: true,
  106252. configurable: true
  106253. });
  106254. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  106255. /**
  106256. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  106257. */
  106258. get: function () {
  106259. return this._idleRotationWaitTime;
  106260. },
  106261. /**
  106262. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  106263. */
  106264. set: function (time) {
  106265. this._idleRotationWaitTime = time;
  106266. },
  106267. enumerable: true,
  106268. configurable: true
  106269. });
  106270. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  106271. /**
  106272. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  106273. */
  106274. get: function () {
  106275. return this._idleRotationSpinupTime;
  106276. },
  106277. /**
  106278. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  106279. */
  106280. set: function (time) {
  106281. this._idleRotationSpinupTime = time;
  106282. },
  106283. enumerable: true,
  106284. configurable: true
  106285. });
  106286. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  106287. /**
  106288. * Gets a value indicating if the camera is currently rotating because of this behavior
  106289. */
  106290. get: function () {
  106291. return Math.abs(this._cameraRotationSpeed) > 0;
  106292. },
  106293. enumerable: true,
  106294. configurable: true
  106295. });
  106296. AutoRotationBehavior.prototype.init = function () {
  106297. // Do notihng
  106298. };
  106299. AutoRotationBehavior.prototype.attach = function (camera) {
  106300. var _this = this;
  106301. this._attachedCamera = camera;
  106302. var scene = this._attachedCamera.getScene();
  106303. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  106304. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  106305. _this._isPointerDown = true;
  106306. return;
  106307. }
  106308. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  106309. _this._isPointerDown = false;
  106310. }
  106311. });
  106312. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106313. var now = BABYLON.Tools.Now;
  106314. var dt = 0;
  106315. if (_this._lastFrameTime != null) {
  106316. dt = now - _this._lastFrameTime;
  106317. }
  106318. _this._lastFrameTime = now;
  106319. // Stop the animation if there is user interaction and the animation should stop for this interaction
  106320. _this._applyUserInteraction();
  106321. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  106322. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  106323. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  106324. // Step camera rotation by rotation speed
  106325. if (_this._attachedCamera) {
  106326. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  106327. }
  106328. });
  106329. };
  106330. AutoRotationBehavior.prototype.detach = function () {
  106331. if (!this._attachedCamera) {
  106332. return;
  106333. }
  106334. var scene = this._attachedCamera.getScene();
  106335. if (this._onPrePointerObservableObserver) {
  106336. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  106337. }
  106338. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106339. this._attachedCamera = null;
  106340. };
  106341. /**
  106342. * Returns true if user is scrolling.
  106343. * @return true if user is scrolling.
  106344. */
  106345. AutoRotationBehavior.prototype._userIsZooming = function () {
  106346. if (!this._attachedCamera) {
  106347. return false;
  106348. }
  106349. return this._attachedCamera.inertialRadiusOffset !== 0;
  106350. };
  106351. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  106352. if (!this._attachedCamera) {
  106353. return false;
  106354. }
  106355. var zoomHasHitLimit = false;
  106356. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  106357. zoomHasHitLimit = true;
  106358. }
  106359. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  106360. this._lastFrameRadius = this._attachedCamera.radius;
  106361. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  106362. };
  106363. /**
  106364. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  106365. */
  106366. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  106367. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  106368. this._lastInteractionTime = BABYLON.Tools.Now;
  106369. }
  106370. };
  106371. // Tools
  106372. AutoRotationBehavior.prototype._userIsMoving = function () {
  106373. if (!this._attachedCamera) {
  106374. return false;
  106375. }
  106376. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  106377. this._attachedCamera.inertialBetaOffset !== 0 ||
  106378. this._attachedCamera.inertialRadiusOffset !== 0 ||
  106379. this._attachedCamera.inertialPanningX !== 0 ||
  106380. this._attachedCamera.inertialPanningY !== 0 ||
  106381. this._isPointerDown;
  106382. };
  106383. return AutoRotationBehavior;
  106384. }());
  106385. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  106386. })(BABYLON || (BABYLON = {}));
  106387. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  106388. var BABYLON;
  106389. (function (BABYLON) {
  106390. var NullEngineOptions = /** @class */ (function () {
  106391. function NullEngineOptions() {
  106392. this.renderWidth = 512;
  106393. this.renderHeight = 256;
  106394. this.textureSize = 512;
  106395. this.deterministicLockstep = false;
  106396. this.lockstepMaxSteps = 4;
  106397. }
  106398. return NullEngineOptions;
  106399. }());
  106400. BABYLON.NullEngineOptions = NullEngineOptions;
  106401. /**
  106402. * The null engine class provides support for headless version of babylon.js.
  106403. * This can be used in server side scenario or for testing purposes
  106404. */
  106405. var NullEngine = /** @class */ (function (_super) {
  106406. __extends(NullEngine, _super);
  106407. function NullEngine(options) {
  106408. if (options === void 0) { options = new NullEngineOptions(); }
  106409. var _this = _super.call(this, null) || this;
  106410. if (options.deterministicLockstep === undefined) {
  106411. options.deterministicLockstep = false;
  106412. }
  106413. if (options.lockstepMaxSteps === undefined) {
  106414. options.lockstepMaxSteps = 4;
  106415. }
  106416. _this._options = options;
  106417. // Init caps
  106418. // We consider we are on a webgl1 capable device
  106419. _this._caps = new BABYLON.EngineCapabilities();
  106420. _this._caps.maxTexturesImageUnits = 16;
  106421. _this._caps.maxVertexTextureImageUnits = 16;
  106422. _this._caps.maxTextureSize = 512;
  106423. _this._caps.maxCubemapTextureSize = 512;
  106424. _this._caps.maxRenderTextureSize = 512;
  106425. _this._caps.maxVertexAttribs = 16;
  106426. _this._caps.maxVaryingVectors = 16;
  106427. _this._caps.maxFragmentUniformVectors = 16;
  106428. _this._caps.maxVertexUniformVectors = 16;
  106429. // Extensions
  106430. _this._caps.standardDerivatives = false;
  106431. _this._caps.astc = null;
  106432. _this._caps.s3tc = null;
  106433. _this._caps.pvrtc = null;
  106434. _this._caps.etc1 = null;
  106435. _this._caps.etc2 = null;
  106436. _this._caps.textureAnisotropicFilterExtension = null;
  106437. _this._caps.maxAnisotropy = 0;
  106438. _this._caps.uintIndices = false;
  106439. _this._caps.fragmentDepthSupported = false;
  106440. _this._caps.highPrecisionShaderSupported = true;
  106441. _this._caps.colorBufferFloat = false;
  106442. _this._caps.textureFloat = false;
  106443. _this._caps.textureFloatLinearFiltering = false;
  106444. _this._caps.textureFloatRender = false;
  106445. _this._caps.textureHalfFloat = false;
  106446. _this._caps.textureHalfFloatLinearFiltering = false;
  106447. _this._caps.textureHalfFloatRender = false;
  106448. _this._caps.textureLOD = false;
  106449. _this._caps.drawBuffersExtension = false;
  106450. _this._caps.depthTextureExtension = false;
  106451. _this._caps.vertexArrayObject = false;
  106452. _this._caps.instancedArrays = false;
  106453. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  106454. // Wrappers
  106455. if (typeof URL === "undefined") {
  106456. URL = {
  106457. createObjectURL: function () { },
  106458. revokeObjectURL: function () { }
  106459. };
  106460. }
  106461. if (typeof Blob === "undefined") {
  106462. Blob = function () { };
  106463. }
  106464. return _this;
  106465. }
  106466. NullEngine.prototype.isDeterministicLockStep = function () {
  106467. return this._options.deterministicLockstep;
  106468. };
  106469. NullEngine.prototype.getLockstepMaxSteps = function () {
  106470. return this._options.lockstepMaxSteps;
  106471. };
  106472. NullEngine.prototype.getHardwareScalingLevel = function () {
  106473. return 1.0;
  106474. };
  106475. NullEngine.prototype.createVertexBuffer = function (vertices) {
  106476. return {
  106477. capacity: 0,
  106478. references: 1,
  106479. is32Bits: false
  106480. };
  106481. };
  106482. NullEngine.prototype.createIndexBuffer = function (indices) {
  106483. return {
  106484. capacity: 0,
  106485. references: 1,
  106486. is32Bits: false
  106487. };
  106488. };
  106489. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  106490. if (stencil === void 0) { stencil = false; }
  106491. };
  106492. NullEngine.prototype.getRenderWidth = function (useScreen) {
  106493. if (useScreen === void 0) { useScreen = false; }
  106494. if (!useScreen && this._currentRenderTarget) {
  106495. return this._currentRenderTarget.width;
  106496. }
  106497. return this._options.renderWidth;
  106498. };
  106499. NullEngine.prototype.getRenderHeight = function (useScreen) {
  106500. if (useScreen === void 0) { useScreen = false; }
  106501. if (!useScreen && this._currentRenderTarget) {
  106502. return this._currentRenderTarget.height;
  106503. }
  106504. return this._options.renderHeight;
  106505. };
  106506. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  106507. this._cachedViewport = viewport;
  106508. };
  106509. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  106510. return {
  106511. transformFeedback: null,
  106512. __SPECTOR_rebuildProgram: null
  106513. };
  106514. };
  106515. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  106516. return [];
  106517. };
  106518. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  106519. return [];
  106520. };
  106521. NullEngine.prototype.bindSamplers = function (effect) {
  106522. this._currentEffect = null;
  106523. };
  106524. NullEngine.prototype.enableEffect = function (effect) {
  106525. this._currentEffect = effect;
  106526. if (effect.onBind) {
  106527. effect.onBind(effect);
  106528. }
  106529. if (effect._onBindObservable) {
  106530. effect._onBindObservable.notifyObservers(effect);
  106531. }
  106532. };
  106533. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  106534. if (zOffset === void 0) { zOffset = 0; }
  106535. if (reverseSide === void 0) { reverseSide = false; }
  106536. };
  106537. NullEngine.prototype.setIntArray = function (uniform, array) {
  106538. };
  106539. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  106540. };
  106541. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  106542. };
  106543. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  106544. };
  106545. NullEngine.prototype.setFloatArray = function (uniform, array) {
  106546. };
  106547. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  106548. };
  106549. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  106550. };
  106551. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  106552. };
  106553. NullEngine.prototype.setArray = function (uniform, array) {
  106554. };
  106555. NullEngine.prototype.setArray2 = function (uniform, array) {
  106556. };
  106557. NullEngine.prototype.setArray3 = function (uniform, array) {
  106558. };
  106559. NullEngine.prototype.setArray4 = function (uniform, array) {
  106560. };
  106561. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  106562. };
  106563. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  106564. };
  106565. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  106566. };
  106567. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  106568. };
  106569. NullEngine.prototype.setFloat = function (uniform, value) {
  106570. };
  106571. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  106572. };
  106573. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  106574. };
  106575. NullEngine.prototype.setBool = function (uniform, bool) {
  106576. };
  106577. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  106578. };
  106579. NullEngine.prototype.setColor3 = function (uniform, color3) {
  106580. };
  106581. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  106582. };
  106583. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  106584. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  106585. if (this._alphaMode === mode) {
  106586. return;
  106587. }
  106588. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  106589. if (!noDepthWriteChange) {
  106590. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  106591. }
  106592. this._alphaMode = mode;
  106593. };
  106594. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  106595. };
  106596. NullEngine.prototype.wipeCaches = function (bruteForce) {
  106597. if (this.preventCacheWipeBetweenFrames) {
  106598. return;
  106599. }
  106600. this.resetTextureCache();
  106601. this._currentEffect = null;
  106602. if (bruteForce) {
  106603. this._currentProgram = null;
  106604. this._stencilState.reset();
  106605. this._depthCullingState.reset();
  106606. this._alphaState.reset();
  106607. }
  106608. this._cachedVertexBuffers = null;
  106609. this._cachedIndexBuffer = null;
  106610. this._cachedEffectForVertexBuffers = null;
  106611. };
  106612. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  106613. };
  106614. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  106615. };
  106616. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  106617. };
  106618. /** @hidden */
  106619. NullEngine.prototype._createTexture = function () {
  106620. return {};
  106621. };
  106622. /** @hidden */
  106623. NullEngine.prototype._releaseTexture = function (texture) {
  106624. };
  106625. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  106626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106627. if (onLoad === void 0) { onLoad = null; }
  106628. if (onError === void 0) { onError = null; }
  106629. if (buffer === void 0) { buffer = null; }
  106630. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  106631. var url = String(urlArg);
  106632. texture.url = url;
  106633. texture.generateMipMaps = !noMipmap;
  106634. texture.samplingMode = samplingMode;
  106635. texture.invertY = invertY;
  106636. texture.baseWidth = this._options.textureSize;
  106637. texture.baseHeight = this._options.textureSize;
  106638. texture.width = this._options.textureSize;
  106639. texture.height = this._options.textureSize;
  106640. if (format) {
  106641. texture.format = format;
  106642. }
  106643. texture.isReady = true;
  106644. if (onLoad) {
  106645. onLoad();
  106646. }
  106647. this._internalTexturesCache.push(texture);
  106648. return texture;
  106649. };
  106650. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  106651. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  106652. if (options !== undefined && typeof options === "object") {
  106653. fullOptions.generateMipMaps = options.generateMipMaps;
  106654. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  106655. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  106656. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  106657. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  106658. }
  106659. else {
  106660. fullOptions.generateMipMaps = options;
  106661. fullOptions.generateDepthBuffer = true;
  106662. fullOptions.generateStencilBuffer = false;
  106663. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106664. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106665. }
  106666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  106667. var width = size.width || size;
  106668. var height = size.height || size;
  106669. texture._depthStencilBuffer = {};
  106670. texture._framebuffer = {};
  106671. texture.baseWidth = width;
  106672. texture.baseHeight = height;
  106673. texture.width = width;
  106674. texture.height = height;
  106675. texture.isReady = true;
  106676. texture.samples = 1;
  106677. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  106678. texture.samplingMode = fullOptions.samplingMode;
  106679. texture.type = fullOptions.type;
  106680. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  106681. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  106682. this._internalTexturesCache.push(texture);
  106683. return texture;
  106684. };
  106685. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  106686. texture.samplingMode = samplingMode;
  106687. };
  106688. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  106689. if (this._currentRenderTarget) {
  106690. this.unBindFramebuffer(this._currentRenderTarget);
  106691. }
  106692. this._currentRenderTarget = texture;
  106693. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  106694. if (this._cachedViewport && !forceFullscreenViewport) {
  106695. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  106696. }
  106697. };
  106698. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  106699. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  106700. this._currentRenderTarget = null;
  106701. if (onBeforeUnbind) {
  106702. if (texture._MSAAFramebuffer) {
  106703. this._currentFramebuffer = texture._framebuffer;
  106704. }
  106705. onBeforeUnbind();
  106706. }
  106707. this._currentFramebuffer = null;
  106708. };
  106709. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  106710. var vbo = {
  106711. capacity: 1,
  106712. references: 1,
  106713. is32Bits: false
  106714. };
  106715. return vbo;
  106716. };
  106717. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  106718. if (premulAlpha === void 0) { premulAlpha = false; }
  106719. };
  106720. /**
  106721. * @hidden
  106722. * Get the current error code of the webGL context
  106723. * @returns the error code
  106724. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  106725. */
  106726. NullEngine.prototype.getError = function () {
  106727. return 0;
  106728. };
  106729. /** @hidden */
  106730. NullEngine.prototype._getUnpackAlignement = function () {
  106731. return 1;
  106732. };
  106733. /** @hidden */
  106734. NullEngine.prototype._unpackFlipY = function (value) {
  106735. };
  106736. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  106737. if (offset === void 0) { offset = 0; }
  106738. };
  106739. /**
  106740. * Updates a dynamic vertex buffer.
  106741. * @param vertexBuffer the vertex buffer to update
  106742. * @param data the data used to update the vertex buffer
  106743. * @param byteOffset the byte offset of the data (optional)
  106744. * @param byteLength the byte length of the data (optional)
  106745. */
  106746. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  106747. };
  106748. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  106749. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  106750. this._boundTexturesCache[this._activeChannel] = texture;
  106751. return true;
  106752. }
  106753. return false;
  106754. };
  106755. /** @hidden */
  106756. NullEngine.prototype._bindTexture = function (channel, texture) {
  106757. if (channel < 0) {
  106758. return;
  106759. }
  106760. this._bindTextureDirectly(0, texture);
  106761. };
  106762. /** @hidden */
  106763. NullEngine.prototype._releaseBuffer = function (buffer) {
  106764. buffer.references--;
  106765. if (buffer.references === 0) {
  106766. return true;
  106767. }
  106768. return false;
  106769. };
  106770. NullEngine.prototype.releaseEffects = function () {
  106771. };
  106772. NullEngine.prototype.displayLoadingUI = function () {
  106773. };
  106774. NullEngine.prototype.hideLoadingUI = function () {
  106775. };
  106776. /** @hidden */
  106777. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106778. if (faceIndex === void 0) { faceIndex = 0; }
  106779. if (lod === void 0) { lod = 0; }
  106780. };
  106781. /** @hidden */
  106782. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106783. if (faceIndex === void 0) { faceIndex = 0; }
  106784. if (lod === void 0) { lod = 0; }
  106785. };
  106786. /** @hidden */
  106787. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106788. if (faceIndex === void 0) { faceIndex = 0; }
  106789. if (lod === void 0) { lod = 0; }
  106790. };
  106791. /** @hidden */
  106792. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106793. if (faceIndex === void 0) { faceIndex = 0; }
  106794. if (lod === void 0) { lod = 0; }
  106795. };
  106796. return NullEngine;
  106797. }(BABYLON.Engine));
  106798. BABYLON.NullEngine = NullEngine;
  106799. })(BABYLON || (BABYLON = {}));
  106800. //# sourceMappingURL=babylon.nullEngine.js.map
  106801. var BABYLON;
  106802. (function (BABYLON) {
  106803. /**
  106804. * This class can be used to get instrumentation data from a Babylon engine
  106805. */
  106806. var EngineInstrumentation = /** @class */ (function () {
  106807. function EngineInstrumentation(engine) {
  106808. this.engine = engine;
  106809. this._captureGPUFrameTime = false;
  106810. this._gpuFrameTime = new BABYLON.PerfCounter();
  106811. this._captureShaderCompilationTime = false;
  106812. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106813. // Observers
  106814. this._onBeginFrameObserver = null;
  106815. this._onEndFrameObserver = null;
  106816. this._onBeforeShaderCompilationObserver = null;
  106817. this._onAfterShaderCompilationObserver = null;
  106818. }
  106819. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106820. // Properties
  106821. /**
  106822. * Gets the perf counter used for GPU frame time
  106823. */
  106824. get: function () {
  106825. return this._gpuFrameTime;
  106826. },
  106827. enumerable: true,
  106828. configurable: true
  106829. });
  106830. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106831. /**
  106832. * Gets the GPU frame time capture status
  106833. */
  106834. get: function () {
  106835. return this._captureGPUFrameTime;
  106836. },
  106837. /**
  106838. * Enable or disable the GPU frame time capture
  106839. */
  106840. set: function (value) {
  106841. var _this = this;
  106842. if (value === this._captureGPUFrameTime) {
  106843. return;
  106844. }
  106845. this._captureGPUFrameTime = value;
  106846. if (value) {
  106847. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106848. if (!_this._gpuFrameTimeToken) {
  106849. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106850. }
  106851. });
  106852. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106853. if (!_this._gpuFrameTimeToken) {
  106854. return;
  106855. }
  106856. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106857. if (time > -1) {
  106858. _this._gpuFrameTimeToken = null;
  106859. _this._gpuFrameTime.fetchNewFrame();
  106860. _this._gpuFrameTime.addCount(time, true);
  106861. }
  106862. });
  106863. }
  106864. else {
  106865. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106866. this._onBeginFrameObserver = null;
  106867. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106868. this._onEndFrameObserver = null;
  106869. }
  106870. },
  106871. enumerable: true,
  106872. configurable: true
  106873. });
  106874. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106875. /**
  106876. * Gets the perf counter used for shader compilation time
  106877. */
  106878. get: function () {
  106879. return this._shaderCompilationTime;
  106880. },
  106881. enumerable: true,
  106882. configurable: true
  106883. });
  106884. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106885. /**
  106886. * Gets the shader compilation time capture status
  106887. */
  106888. get: function () {
  106889. return this._captureShaderCompilationTime;
  106890. },
  106891. /**
  106892. * Enable or disable the shader compilation time capture
  106893. */
  106894. set: function (value) {
  106895. var _this = this;
  106896. if (value === this._captureShaderCompilationTime) {
  106897. return;
  106898. }
  106899. this._captureShaderCompilationTime = value;
  106900. if (value) {
  106901. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106902. _this._shaderCompilationTime.fetchNewFrame();
  106903. _this._shaderCompilationTime.beginMonitoring();
  106904. });
  106905. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106906. _this._shaderCompilationTime.endMonitoring();
  106907. });
  106908. }
  106909. else {
  106910. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106911. this._onBeforeShaderCompilationObserver = null;
  106912. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106913. this._onAfterShaderCompilationObserver = null;
  106914. }
  106915. },
  106916. enumerable: true,
  106917. configurable: true
  106918. });
  106919. EngineInstrumentation.prototype.dispose = function () {
  106920. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106921. this._onBeginFrameObserver = null;
  106922. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106923. this._onEndFrameObserver = null;
  106924. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106925. this._onBeforeShaderCompilationObserver = null;
  106926. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106927. this._onAfterShaderCompilationObserver = null;
  106928. this.engine = null;
  106929. };
  106930. return EngineInstrumentation;
  106931. }());
  106932. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106933. })(BABYLON || (BABYLON = {}));
  106934. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106935. var BABYLON;
  106936. (function (BABYLON) {
  106937. /**
  106938. * This class can be used to get instrumentation data from a Babylon engine
  106939. */
  106940. var SceneInstrumentation = /** @class */ (function () {
  106941. function SceneInstrumentation(scene) {
  106942. var _this = this;
  106943. this.scene = scene;
  106944. this._captureActiveMeshesEvaluationTime = false;
  106945. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106946. this._captureRenderTargetsRenderTime = false;
  106947. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106948. this._captureFrameTime = false;
  106949. this._frameTime = new BABYLON.PerfCounter();
  106950. this._captureRenderTime = false;
  106951. this._renderTime = new BABYLON.PerfCounter();
  106952. this._captureInterFrameTime = false;
  106953. this._interFrameTime = new BABYLON.PerfCounter();
  106954. this._captureParticlesRenderTime = false;
  106955. this._particlesRenderTime = new BABYLON.PerfCounter();
  106956. this._captureSpritesRenderTime = false;
  106957. this._spritesRenderTime = new BABYLON.PerfCounter();
  106958. this._capturePhysicsTime = false;
  106959. this._physicsTime = new BABYLON.PerfCounter();
  106960. this._captureAnimationsTime = false;
  106961. this._animationsTime = new BABYLON.PerfCounter();
  106962. this._captureCameraRenderTime = false;
  106963. this._cameraRenderTime = new BABYLON.PerfCounter();
  106964. // Observers
  106965. this._onBeforeActiveMeshesEvaluationObserver = null;
  106966. this._onAfterActiveMeshesEvaluationObserver = null;
  106967. this._onBeforeRenderTargetsRenderObserver = null;
  106968. this._onAfterRenderTargetsRenderObserver = null;
  106969. this._onAfterRenderObserver = null;
  106970. this._onBeforeDrawPhaseObserver = null;
  106971. this._onAfterDrawPhaseObserver = null;
  106972. this._onBeforeAnimationsObserver = null;
  106973. this._onBeforeParticlesRenderingObserver = null;
  106974. this._onAfterParticlesRenderingObserver = null;
  106975. this._onBeforeSpritesRenderingObserver = null;
  106976. this._onAfterSpritesRenderingObserver = null;
  106977. this._onBeforePhysicsObserver = null;
  106978. this._onAfterPhysicsObserver = null;
  106979. this._onAfterAnimationsObserver = null;
  106980. this._onBeforeCameraRenderObserver = null;
  106981. this._onAfterCameraRenderObserver = null;
  106982. // Before render
  106983. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106984. if (_this._captureActiveMeshesEvaluationTime) {
  106985. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106986. }
  106987. if (_this._captureRenderTargetsRenderTime) {
  106988. _this._renderTargetsRenderTime.fetchNewFrame();
  106989. }
  106990. if (_this._captureFrameTime) {
  106991. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106992. _this._frameTime.beginMonitoring();
  106993. }
  106994. if (_this._captureInterFrameTime) {
  106995. _this._interFrameTime.endMonitoring();
  106996. }
  106997. if (_this._captureParticlesRenderTime) {
  106998. _this._particlesRenderTime.fetchNewFrame();
  106999. }
  107000. if (_this._captureSpritesRenderTime) {
  107001. _this._spritesRenderTime.fetchNewFrame();
  107002. }
  107003. if (_this._captureAnimationsTime) {
  107004. _this._animationsTime.beginMonitoring();
  107005. }
  107006. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  107007. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  107008. });
  107009. // After render
  107010. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  107011. if (_this._captureFrameTime) {
  107012. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  107013. _this._frameTime.endMonitoring();
  107014. }
  107015. if (_this._captureRenderTime) {
  107016. _this._renderTime.endMonitoring(false);
  107017. }
  107018. if (_this._captureInterFrameTime) {
  107019. _this._interFrameTime.beginMonitoring();
  107020. }
  107021. });
  107022. }
  107023. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  107024. // Properties
  107025. /**
  107026. * Gets the perf counter used for active meshes evaluation time
  107027. */
  107028. get: function () {
  107029. return this._activeMeshesEvaluationTime;
  107030. },
  107031. enumerable: true,
  107032. configurable: true
  107033. });
  107034. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  107035. /**
  107036. * Gets the active meshes evaluation time capture status
  107037. */
  107038. get: function () {
  107039. return this._captureActiveMeshesEvaluationTime;
  107040. },
  107041. /**
  107042. * Enable or disable the active meshes evaluation time capture
  107043. */
  107044. set: function (value) {
  107045. var _this = this;
  107046. if (value === this._captureActiveMeshesEvaluationTime) {
  107047. return;
  107048. }
  107049. this._captureActiveMeshesEvaluationTime = value;
  107050. if (value) {
  107051. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  107052. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  107053. _this._activeMeshesEvaluationTime.beginMonitoring();
  107054. });
  107055. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  107056. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  107057. _this._activeMeshesEvaluationTime.endMonitoring();
  107058. });
  107059. }
  107060. else {
  107061. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107062. this._onBeforeActiveMeshesEvaluationObserver = null;
  107063. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107064. this._onAfterActiveMeshesEvaluationObserver = null;
  107065. }
  107066. },
  107067. enumerable: true,
  107068. configurable: true
  107069. });
  107070. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  107071. /**
  107072. * Gets the perf counter used for render targets render time
  107073. */
  107074. get: function () {
  107075. return this._renderTargetsRenderTime;
  107076. },
  107077. enumerable: true,
  107078. configurable: true
  107079. });
  107080. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  107081. /**
  107082. * Gets the render targets render time capture status
  107083. */
  107084. get: function () {
  107085. return this._captureRenderTargetsRenderTime;
  107086. },
  107087. /**
  107088. * Enable or disable the render targets render time capture
  107089. */
  107090. set: function (value) {
  107091. var _this = this;
  107092. if (value === this._captureRenderTargetsRenderTime) {
  107093. return;
  107094. }
  107095. this._captureRenderTargetsRenderTime = value;
  107096. if (value) {
  107097. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  107098. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  107099. _this._renderTargetsRenderTime.beginMonitoring();
  107100. });
  107101. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  107102. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  107103. _this._renderTargetsRenderTime.endMonitoring(false);
  107104. });
  107105. }
  107106. else {
  107107. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107108. this._onBeforeRenderTargetsRenderObserver = null;
  107109. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107110. this._onAfterRenderTargetsRenderObserver = null;
  107111. }
  107112. },
  107113. enumerable: true,
  107114. configurable: true
  107115. });
  107116. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  107117. /**
  107118. * Gets the perf counter used for particles render time
  107119. */
  107120. get: function () {
  107121. return this._particlesRenderTime;
  107122. },
  107123. enumerable: true,
  107124. configurable: true
  107125. });
  107126. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  107127. /**
  107128. * Gets the particles render time capture status
  107129. */
  107130. get: function () {
  107131. return this._captureParticlesRenderTime;
  107132. },
  107133. /**
  107134. * Enable or disable the particles render time capture
  107135. */
  107136. set: function (value) {
  107137. var _this = this;
  107138. if (value === this._captureParticlesRenderTime) {
  107139. return;
  107140. }
  107141. this._captureParticlesRenderTime = value;
  107142. if (value) {
  107143. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  107144. BABYLON.Tools.StartPerformanceCounter("Particles");
  107145. _this._particlesRenderTime.beginMonitoring();
  107146. });
  107147. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  107148. BABYLON.Tools.EndPerformanceCounter("Particles");
  107149. _this._particlesRenderTime.endMonitoring(false);
  107150. });
  107151. }
  107152. else {
  107153. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107154. this._onBeforeParticlesRenderingObserver = null;
  107155. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107156. this._onAfterParticlesRenderingObserver = null;
  107157. }
  107158. },
  107159. enumerable: true,
  107160. configurable: true
  107161. });
  107162. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  107163. /**
  107164. * Gets the perf counter used for sprites render time
  107165. */
  107166. get: function () {
  107167. return this._spritesRenderTime;
  107168. },
  107169. enumerable: true,
  107170. configurable: true
  107171. });
  107172. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  107173. /**
  107174. * Gets the sprites render time capture status
  107175. */
  107176. get: function () {
  107177. return this._captureSpritesRenderTime;
  107178. },
  107179. /**
  107180. * Enable or disable the sprites render time capture
  107181. */
  107182. set: function (value) {
  107183. var _this = this;
  107184. if (value === this._captureSpritesRenderTime) {
  107185. return;
  107186. }
  107187. this._captureSpritesRenderTime = value;
  107188. if (!this.scene.spriteManagers) {
  107189. return;
  107190. }
  107191. if (value) {
  107192. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  107193. BABYLON.Tools.StartPerformanceCounter("Sprites");
  107194. _this._spritesRenderTime.beginMonitoring();
  107195. });
  107196. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  107197. BABYLON.Tools.EndPerformanceCounter("Sprites");
  107198. _this._spritesRenderTime.endMonitoring(false);
  107199. });
  107200. }
  107201. else {
  107202. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107203. this._onBeforeSpritesRenderingObserver = null;
  107204. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107205. this._onAfterSpritesRenderingObserver = null;
  107206. }
  107207. },
  107208. enumerable: true,
  107209. configurable: true
  107210. });
  107211. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  107212. /**
  107213. * Gets the perf counter used for physics time
  107214. */
  107215. get: function () {
  107216. return this._physicsTime;
  107217. },
  107218. enumerable: true,
  107219. configurable: true
  107220. });
  107221. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  107222. /**
  107223. * Gets the physics time capture status
  107224. */
  107225. get: function () {
  107226. return this._capturePhysicsTime;
  107227. },
  107228. /**
  107229. * Enable or disable the physics time capture
  107230. */
  107231. set: function (value) {
  107232. var _this = this;
  107233. if (value === this._capturePhysicsTime) {
  107234. return;
  107235. }
  107236. if (!this.scene.onBeforePhysicsObservable) {
  107237. return;
  107238. }
  107239. this._capturePhysicsTime = value;
  107240. if (value) {
  107241. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  107242. BABYLON.Tools.StartPerformanceCounter("Physics");
  107243. _this._physicsTime.beginMonitoring();
  107244. });
  107245. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  107246. BABYLON.Tools.EndPerformanceCounter("Physics");
  107247. _this._physicsTime.endMonitoring();
  107248. });
  107249. }
  107250. else {
  107251. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107252. this._onBeforePhysicsObserver = null;
  107253. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107254. this._onAfterPhysicsObserver = null;
  107255. }
  107256. },
  107257. enumerable: true,
  107258. configurable: true
  107259. });
  107260. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  107261. /**
  107262. * Gets the perf counter used for animations time
  107263. */
  107264. get: function () {
  107265. return this._animationsTime;
  107266. },
  107267. enumerable: true,
  107268. configurable: true
  107269. });
  107270. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  107271. /**
  107272. * Gets the animations time capture status
  107273. */
  107274. get: function () {
  107275. return this._captureAnimationsTime;
  107276. },
  107277. /**
  107278. * Enable or disable the animations time capture
  107279. */
  107280. set: function (value) {
  107281. var _this = this;
  107282. if (value === this._captureAnimationsTime) {
  107283. return;
  107284. }
  107285. this._captureAnimationsTime = value;
  107286. if (value) {
  107287. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  107288. _this._animationsTime.endMonitoring();
  107289. });
  107290. }
  107291. else {
  107292. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107293. this._onAfterAnimationsObserver = null;
  107294. }
  107295. },
  107296. enumerable: true,
  107297. configurable: true
  107298. });
  107299. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  107300. /**
  107301. * Gets the perf counter used for frame time capture
  107302. */
  107303. get: function () {
  107304. return this._frameTime;
  107305. },
  107306. enumerable: true,
  107307. configurable: true
  107308. });
  107309. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  107310. /**
  107311. * Gets the frame time capture status
  107312. */
  107313. get: function () {
  107314. return this._captureFrameTime;
  107315. },
  107316. /**
  107317. * Enable or disable the frame time capture
  107318. */
  107319. set: function (value) {
  107320. this._captureFrameTime = value;
  107321. },
  107322. enumerable: true,
  107323. configurable: true
  107324. });
  107325. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  107326. /**
  107327. * Gets the perf counter used for inter-frames time capture
  107328. */
  107329. get: function () {
  107330. return this._interFrameTime;
  107331. },
  107332. enumerable: true,
  107333. configurable: true
  107334. });
  107335. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  107336. /**
  107337. * Gets the inter-frames time capture status
  107338. */
  107339. get: function () {
  107340. return this._captureInterFrameTime;
  107341. },
  107342. /**
  107343. * Enable or disable the inter-frames time capture
  107344. */
  107345. set: function (value) {
  107346. this._captureInterFrameTime = value;
  107347. },
  107348. enumerable: true,
  107349. configurable: true
  107350. });
  107351. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  107352. /**
  107353. * Gets the perf counter used for render time capture
  107354. */
  107355. get: function () {
  107356. return this._renderTime;
  107357. },
  107358. enumerable: true,
  107359. configurable: true
  107360. });
  107361. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  107362. /**
  107363. * Gets the render time capture status
  107364. */
  107365. get: function () {
  107366. return this._captureRenderTime;
  107367. },
  107368. /**
  107369. * Enable or disable the render time capture
  107370. */
  107371. set: function (value) {
  107372. var _this = this;
  107373. if (value === this._captureRenderTime) {
  107374. return;
  107375. }
  107376. this._captureRenderTime = value;
  107377. if (value) {
  107378. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  107379. _this._renderTime.beginMonitoring();
  107380. BABYLON.Tools.StartPerformanceCounter("Main render");
  107381. });
  107382. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  107383. _this._renderTime.endMonitoring(false);
  107384. BABYLON.Tools.EndPerformanceCounter("Main render");
  107385. });
  107386. }
  107387. else {
  107388. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107389. this._onBeforeDrawPhaseObserver = null;
  107390. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107391. this._onAfterDrawPhaseObserver = null;
  107392. }
  107393. },
  107394. enumerable: true,
  107395. configurable: true
  107396. });
  107397. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  107398. /**
  107399. * Gets the perf counter used for camera render time capture
  107400. */
  107401. get: function () {
  107402. return this._cameraRenderTime;
  107403. },
  107404. enumerable: true,
  107405. configurable: true
  107406. });
  107407. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  107408. /**
  107409. * Gets the camera render time capture status
  107410. */
  107411. get: function () {
  107412. return this._captureCameraRenderTime;
  107413. },
  107414. /**
  107415. * Enable or disable the camera render time capture
  107416. */
  107417. set: function (value) {
  107418. var _this = this;
  107419. if (value === this._captureCameraRenderTime) {
  107420. return;
  107421. }
  107422. this._captureCameraRenderTime = value;
  107423. if (value) {
  107424. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  107425. _this._cameraRenderTime.beginMonitoring();
  107426. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  107427. });
  107428. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  107429. _this._cameraRenderTime.endMonitoring(false);
  107430. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  107431. });
  107432. }
  107433. else {
  107434. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107435. this._onBeforeCameraRenderObserver = null;
  107436. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107437. this._onAfterCameraRenderObserver = null;
  107438. }
  107439. },
  107440. enumerable: true,
  107441. configurable: true
  107442. });
  107443. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  107444. /**
  107445. * Gets the perf counter used for draw calls
  107446. */
  107447. get: function () {
  107448. return this.scene.getEngine()._drawCalls;
  107449. },
  107450. enumerable: true,
  107451. configurable: true
  107452. });
  107453. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  107454. /**
  107455. * Gets the perf counter used for texture collisions
  107456. */
  107457. get: function () {
  107458. return this.scene.getEngine()._textureCollisions;
  107459. },
  107460. enumerable: true,
  107461. configurable: true
  107462. });
  107463. SceneInstrumentation.prototype.dispose = function () {
  107464. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107465. this._onAfterRenderObserver = null;
  107466. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107467. this._onBeforeActiveMeshesEvaluationObserver = null;
  107468. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107469. this._onAfterActiveMeshesEvaluationObserver = null;
  107470. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107471. this._onBeforeRenderTargetsRenderObserver = null;
  107472. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107473. this._onAfterRenderTargetsRenderObserver = null;
  107474. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  107475. this._onBeforeAnimationsObserver = null;
  107476. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107477. this._onBeforeParticlesRenderingObserver = null;
  107478. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107479. this._onAfterParticlesRenderingObserver = null;
  107480. if (this._onBeforeSpritesRenderingObserver) {
  107481. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107482. this._onBeforeSpritesRenderingObserver = null;
  107483. }
  107484. if (this._onAfterSpritesRenderingObserver) {
  107485. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107486. this._onAfterSpritesRenderingObserver = null;
  107487. }
  107488. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107489. this._onBeforeDrawPhaseObserver = null;
  107490. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107491. this._onAfterDrawPhaseObserver = null;
  107492. if (this._onBeforePhysicsObserver) {
  107493. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107494. this._onBeforePhysicsObserver = null;
  107495. }
  107496. if (this._onAfterPhysicsObserver) {
  107497. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107498. this._onAfterPhysicsObserver = null;
  107499. }
  107500. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107501. this._onAfterAnimationsObserver = null;
  107502. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107503. this._onBeforeCameraRenderObserver = null;
  107504. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107505. this._onAfterCameraRenderObserver = null;
  107506. this.scene = null;
  107507. };
  107508. return SceneInstrumentation;
  107509. }());
  107510. BABYLON.SceneInstrumentation = SceneInstrumentation;
  107511. })(BABYLON || (BABYLON = {}));
  107512. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  107513. var BABYLON;
  107514. (function (BABYLON) {
  107515. /**
  107516. * @hidden
  107517. **/
  107518. var _TimeToken = /** @class */ (function () {
  107519. function _TimeToken() {
  107520. this._timeElapsedQueryEnded = false;
  107521. }
  107522. return _TimeToken;
  107523. }());
  107524. BABYLON._TimeToken = _TimeToken;
  107525. })(BABYLON || (BABYLON = {}));
  107526. //# sourceMappingURL=babylon.timeToken.js.map
  107527. var BABYLON;
  107528. (function (BABYLON) {
  107529. /**
  107530. * Background material defines definition.
  107531. * @hidden Mainly internal Use
  107532. */
  107533. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  107534. __extends(BackgroundMaterialDefines, _super);
  107535. /**
  107536. * Constructor of the defines.
  107537. */
  107538. function BackgroundMaterialDefines() {
  107539. var _this = _super.call(this) || this;
  107540. /**
  107541. * True if the diffuse texture is in use.
  107542. */
  107543. _this.DIFFUSE = false;
  107544. /**
  107545. * The direct UV channel to use.
  107546. */
  107547. _this.DIFFUSEDIRECTUV = 0;
  107548. /**
  107549. * True if the diffuse texture is in gamma space.
  107550. */
  107551. _this.GAMMADIFFUSE = false;
  107552. /**
  107553. * True if the diffuse texture has opacity in the alpha channel.
  107554. */
  107555. _this.DIFFUSEHASALPHA = false;
  107556. /**
  107557. * True if you want the material to fade to transparent at grazing angle.
  107558. */
  107559. _this.OPACITYFRESNEL = false;
  107560. /**
  107561. * True if an extra blur needs to be added in the reflection.
  107562. */
  107563. _this.REFLECTIONBLUR = false;
  107564. /**
  107565. * True if you want the material to fade to reflection at grazing angle.
  107566. */
  107567. _this.REFLECTIONFRESNEL = false;
  107568. /**
  107569. * True if you want the material to falloff as far as you move away from the scene center.
  107570. */
  107571. _this.REFLECTIONFALLOFF = false;
  107572. /**
  107573. * False if the current Webgl implementation does not support the texture lod extension.
  107574. */
  107575. _this.TEXTURELODSUPPORT = false;
  107576. /**
  107577. * True to ensure the data are premultiplied.
  107578. */
  107579. _this.PREMULTIPLYALPHA = false;
  107580. /**
  107581. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  107582. */
  107583. _this.USERGBCOLOR = false;
  107584. /**
  107585. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  107586. * stays aligned with the desired configuration.
  107587. */
  107588. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  107589. /**
  107590. * True to add noise in order to reduce the banding effect.
  107591. */
  107592. _this.NOISE = false;
  107593. /**
  107594. * is the reflection texture in BGR color scheme?
  107595. * Mainly used to solve a bug in ios10 video tag
  107596. */
  107597. _this.REFLECTIONBGR = false;
  107598. _this.IMAGEPROCESSING = false;
  107599. _this.VIGNETTE = false;
  107600. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  107601. _this.VIGNETTEBLENDMODEOPAQUE = false;
  107602. _this.TONEMAPPING = false;
  107603. _this.TONEMAPPING_ACES = false;
  107604. _this.CONTRAST = false;
  107605. _this.COLORCURVES = false;
  107606. _this.COLORGRADING = false;
  107607. _this.COLORGRADING3D = false;
  107608. _this.SAMPLER3DGREENDEPTH = false;
  107609. _this.SAMPLER3DBGRMAP = false;
  107610. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  107611. _this.EXPOSURE = false;
  107612. // Reflection.
  107613. _this.REFLECTION = false;
  107614. _this.REFLECTIONMAP_3D = false;
  107615. _this.REFLECTIONMAP_SPHERICAL = false;
  107616. _this.REFLECTIONMAP_PLANAR = false;
  107617. _this.REFLECTIONMAP_CUBIC = false;
  107618. _this.REFLECTIONMAP_PROJECTION = false;
  107619. _this.REFLECTIONMAP_SKYBOX = false;
  107620. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107621. _this.REFLECTIONMAP_EXPLICIT = false;
  107622. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107623. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107624. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107625. _this.INVERTCUBICMAP = false;
  107626. _this.REFLECTIONMAP_OPPOSITEZ = false;
  107627. _this.LODINREFLECTIONALPHA = false;
  107628. _this.GAMMAREFLECTION = false;
  107629. _this.RGBDREFLECTION = false;
  107630. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  107631. // Default BJS.
  107632. _this.MAINUV1 = false;
  107633. _this.MAINUV2 = false;
  107634. _this.UV1 = false;
  107635. _this.UV2 = false;
  107636. _this.CLIPPLANE = false;
  107637. _this.CLIPPLANE2 = false;
  107638. _this.CLIPPLANE3 = false;
  107639. _this.CLIPPLANE4 = false;
  107640. _this.POINTSIZE = false;
  107641. _this.FOG = false;
  107642. _this.NORMAL = false;
  107643. _this.NUM_BONE_INFLUENCERS = 0;
  107644. _this.BonesPerMesh = 0;
  107645. _this.INSTANCES = false;
  107646. _this.SHADOWFLOAT = false;
  107647. _this.rebuild();
  107648. return _this;
  107649. }
  107650. return BackgroundMaterialDefines;
  107651. }(BABYLON.MaterialDefines));
  107652. /**
  107653. * Background material used to create an efficient environement around your scene.
  107654. */
  107655. var BackgroundMaterial = /** @class */ (function (_super) {
  107656. __extends(BackgroundMaterial, _super);
  107657. /**
  107658. * Instantiates a Background Material in the given scene
  107659. * @param name The friendly name of the material
  107660. * @param scene The scene to add the material to
  107661. */
  107662. function BackgroundMaterial(name, scene) {
  107663. var _this = _super.call(this, name, scene) || this;
  107664. /**
  107665. * Key light Color (multiply against the environement texture)
  107666. */
  107667. _this.primaryColor = BABYLON.Color3.White();
  107668. _this._primaryColorShadowLevel = 0;
  107669. _this._primaryColorHighlightLevel = 0;
  107670. /**
  107671. * Reflection Texture used in the material.
  107672. * Should be author in a specific way for the best result (refer to the documentation).
  107673. */
  107674. _this.reflectionTexture = null;
  107675. /**
  107676. * Reflection Texture level of blur.
  107677. *
  107678. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  107679. * texture twice.
  107680. */
  107681. _this.reflectionBlur = 0;
  107682. /**
  107683. * Diffuse Texture used in the material.
  107684. * Should be author in a specific way for the best result (refer to the documentation).
  107685. */
  107686. _this.diffuseTexture = null;
  107687. _this._shadowLights = null;
  107688. /**
  107689. * Specify the list of lights casting shadow on the material.
  107690. * All scene shadow lights will be included if null.
  107691. */
  107692. _this.shadowLights = null;
  107693. /**
  107694. * Helps adjusting the shadow to a softer level if required.
  107695. * 0 means black shadows and 1 means no shadows.
  107696. */
  107697. _this.shadowLevel = 0;
  107698. /**
  107699. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  107700. * It is usually zero but might be interesting to modify according to your setup.
  107701. */
  107702. _this.sceneCenter = BABYLON.Vector3.Zero();
  107703. /**
  107704. * This helps specifying that the material is falling off to the sky box at grazing angle.
  107705. * This helps ensuring a nice transition when the camera goes under the ground.
  107706. */
  107707. _this.opacityFresnel = true;
  107708. /**
  107709. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  107710. * This helps adding a mirror texture on the ground.
  107711. */
  107712. _this.reflectionFresnel = false;
  107713. /**
  107714. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  107715. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  107716. */
  107717. _this.reflectionFalloffDistance = 0.0;
  107718. /**
  107719. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  107720. */
  107721. _this.reflectionAmount = 1.0;
  107722. /**
  107723. * This specifies the weight of the reflection at grazing angle.
  107724. */
  107725. _this.reflectionReflectance0 = 0.05;
  107726. /**
  107727. * This specifies the weight of the reflection at a perpendicular point of view.
  107728. */
  107729. _this.reflectionReflectance90 = 0.5;
  107730. /**
  107731. * Helps to directly use the maps channels instead of their level.
  107732. */
  107733. _this.useRGBColor = true;
  107734. /**
  107735. * This helps reducing the banding effect that could occur on the background.
  107736. */
  107737. _this.enableNoise = false;
  107738. _this._fovMultiplier = 1.0;
  107739. /**
  107740. * Enable the FOV adjustment feature controlled by fovMultiplier.
  107741. */
  107742. _this.useEquirectangularFOV = false;
  107743. _this._maxSimultaneousLights = 4;
  107744. /**
  107745. * Number of Simultaneous lights allowed on the material.
  107746. */
  107747. _this.maxSimultaneousLights = 4;
  107748. /**
  107749. * Keep track of the image processing observer to allow dispose and replace.
  107750. */
  107751. _this._imageProcessingObserver = null;
  107752. /**
  107753. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  107754. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  107755. */
  107756. _this.switchToBGR = false;
  107757. // Temp values kept as cache in the material.
  107758. _this._renderTargets = new BABYLON.SmartArray(16);
  107759. _this._reflectionControls = BABYLON.Vector4.Zero();
  107760. _this._white = BABYLON.Color3.White();
  107761. _this._primaryShadowColor = BABYLON.Color3.Black();
  107762. _this._primaryHighlightColor = BABYLON.Color3.Black();
  107763. // Setup the default processing configuration to the scene.
  107764. _this._attachImageProcessingConfiguration(null);
  107765. _this.getRenderTargetTextures = function () {
  107766. _this._renderTargets.reset();
  107767. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  107768. _this._renderTargets.push(_this._diffuseTexture);
  107769. }
  107770. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  107771. _this._renderTargets.push(_this._reflectionTexture);
  107772. }
  107773. return _this._renderTargets;
  107774. };
  107775. return _this;
  107776. }
  107777. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  107778. /**
  107779. * Experimental Internal Use Only.
  107780. *
  107781. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  107782. * This acts as a helper to set the primary color to a more "human friendly" value.
  107783. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  107784. * output color as close as possible from the chosen value.
  107785. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  107786. * part of lighting setup.)
  107787. */
  107788. get: function () {
  107789. return this.__perceptualColor;
  107790. },
  107791. set: function (value) {
  107792. this.__perceptualColor = value;
  107793. this._computePrimaryColorFromPerceptualColor();
  107794. this._markAllSubMeshesAsLightsDirty();
  107795. },
  107796. enumerable: true,
  107797. configurable: true
  107798. });
  107799. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107800. /**
  107801. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107802. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107803. */
  107804. get: function () {
  107805. return this._primaryColorShadowLevel;
  107806. },
  107807. set: function (value) {
  107808. this._primaryColorShadowLevel = value;
  107809. this._computePrimaryColors();
  107810. this._markAllSubMeshesAsLightsDirty();
  107811. },
  107812. enumerable: true,
  107813. configurable: true
  107814. });
  107815. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107816. /**
  107817. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107818. * The primary color is used at the level chosen to define what the white area would look.
  107819. */
  107820. get: function () {
  107821. return this._primaryColorHighlightLevel;
  107822. },
  107823. set: function (value) {
  107824. this._primaryColorHighlightLevel = value;
  107825. this._computePrimaryColors();
  107826. this._markAllSubMeshesAsLightsDirty();
  107827. },
  107828. enumerable: true,
  107829. configurable: true
  107830. });
  107831. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107832. /**
  107833. * Sets the reflection reflectance fresnel values according to the default standard
  107834. * empirically know to work well :-)
  107835. */
  107836. set: function (value) {
  107837. var reflectionWeight = value;
  107838. if (reflectionWeight < 0.5) {
  107839. reflectionWeight = reflectionWeight * 2.0;
  107840. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107841. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107842. }
  107843. else {
  107844. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107845. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107846. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107847. }
  107848. },
  107849. enumerable: true,
  107850. configurable: true
  107851. });
  107852. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107853. /**
  107854. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107855. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107856. * Recommended to be keep at 1.0 except for special cases.
  107857. */
  107858. get: function () {
  107859. return this._fovMultiplier;
  107860. },
  107861. set: function (value) {
  107862. if (isNaN(value)) {
  107863. value = 1.0;
  107864. }
  107865. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107866. },
  107867. enumerable: true,
  107868. configurable: true
  107869. });
  107870. /**
  107871. * Attaches a new image processing configuration to the PBR Material.
  107872. * @param configuration (if null the scene configuration will be use)
  107873. */
  107874. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107875. var _this = this;
  107876. if (configuration === this._imageProcessingConfiguration) {
  107877. return;
  107878. }
  107879. // Detaches observer.
  107880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107882. }
  107883. // Pick the scene configuration if needed.
  107884. if (!configuration) {
  107885. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107886. }
  107887. else {
  107888. this._imageProcessingConfiguration = configuration;
  107889. }
  107890. // Attaches observer.
  107891. if (this._imageProcessingConfiguration) {
  107892. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107893. _this._computePrimaryColorFromPerceptualColor();
  107894. _this._markAllSubMeshesAsImageProcessingDirty();
  107895. });
  107896. }
  107897. };
  107898. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107899. /**
  107900. * Gets the image processing configuration used either in this material.
  107901. */
  107902. get: function () {
  107903. return this._imageProcessingConfiguration;
  107904. },
  107905. /**
  107906. * Sets the Default image processing configuration used either in the this material.
  107907. *
  107908. * If sets to null, the scene one is in use.
  107909. */
  107910. set: function (value) {
  107911. this._attachImageProcessingConfiguration(value);
  107912. // Ensure the effect will be rebuilt.
  107913. this._markAllSubMeshesAsTexturesDirty();
  107914. },
  107915. enumerable: true,
  107916. configurable: true
  107917. });
  107918. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107919. /**
  107920. * Gets wether the color curves effect is enabled.
  107921. */
  107922. get: function () {
  107923. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107924. },
  107925. /**
  107926. * Sets wether the color curves effect is enabled.
  107927. */
  107928. set: function (value) {
  107929. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107930. },
  107931. enumerable: true,
  107932. configurable: true
  107933. });
  107934. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107935. /**
  107936. * Gets wether the color grading effect is enabled.
  107937. */
  107938. get: function () {
  107939. return this.imageProcessingConfiguration.colorGradingEnabled;
  107940. },
  107941. /**
  107942. * Gets wether the color grading effect is enabled.
  107943. */
  107944. set: function (value) {
  107945. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107946. },
  107947. enumerable: true,
  107948. configurable: true
  107949. });
  107950. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107951. /**
  107952. * Gets wether tonemapping is enabled or not.
  107953. */
  107954. get: function () {
  107955. return this._imageProcessingConfiguration.toneMappingEnabled;
  107956. },
  107957. /**
  107958. * Sets wether tonemapping is enabled or not
  107959. */
  107960. set: function (value) {
  107961. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107962. },
  107963. enumerable: true,
  107964. configurable: true
  107965. });
  107966. ;
  107967. ;
  107968. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107969. /**
  107970. * The camera exposure used on this material.
  107971. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107972. * This corresponds to a photographic exposure.
  107973. */
  107974. get: function () {
  107975. return this._imageProcessingConfiguration.exposure;
  107976. },
  107977. /**
  107978. * The camera exposure used on this material.
  107979. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107980. * This corresponds to a photographic exposure.
  107981. */
  107982. set: function (value) {
  107983. this._imageProcessingConfiguration.exposure = value;
  107984. },
  107985. enumerable: true,
  107986. configurable: true
  107987. });
  107988. ;
  107989. ;
  107990. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107991. /**
  107992. * Gets The camera contrast used on this material.
  107993. */
  107994. get: function () {
  107995. return this._imageProcessingConfiguration.contrast;
  107996. },
  107997. /**
  107998. * Sets The camera contrast used on this material.
  107999. */
  108000. set: function (value) {
  108001. this._imageProcessingConfiguration.contrast = value;
  108002. },
  108003. enumerable: true,
  108004. configurable: true
  108005. });
  108006. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  108007. /**
  108008. * Gets the Color Grading 2D Lookup Texture.
  108009. */
  108010. get: function () {
  108011. return this._imageProcessingConfiguration.colorGradingTexture;
  108012. },
  108013. /**
  108014. * Sets the Color Grading 2D Lookup Texture.
  108015. */
  108016. set: function (value) {
  108017. this.imageProcessingConfiguration.colorGradingTexture = value;
  108018. },
  108019. enumerable: true,
  108020. configurable: true
  108021. });
  108022. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  108023. /**
  108024. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  108025. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  108026. * 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;
  108027. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  108028. */
  108029. get: function () {
  108030. return this.imageProcessingConfiguration.colorCurves;
  108031. },
  108032. /**
  108033. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  108034. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  108035. * 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;
  108036. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  108037. */
  108038. set: function (value) {
  108039. this.imageProcessingConfiguration.colorCurves = value;
  108040. },
  108041. enumerable: true,
  108042. configurable: true
  108043. });
  108044. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  108045. /**
  108046. * Gets a boolean indicating that current material needs to register RTT
  108047. */
  108048. get: function () {
  108049. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108050. return true;
  108051. }
  108052. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108053. return true;
  108054. }
  108055. return false;
  108056. },
  108057. enumerable: true,
  108058. configurable: true
  108059. });
  108060. /**
  108061. * The entire material has been created in order to prevent overdraw.
  108062. * @returns false
  108063. */
  108064. BackgroundMaterial.prototype.needAlphaTesting = function () {
  108065. return true;
  108066. };
  108067. /**
  108068. * The entire material has been created in order to prevent overdraw.
  108069. * @returns true if blending is enable
  108070. */
  108071. BackgroundMaterial.prototype.needAlphaBlending = function () {
  108072. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  108073. };
  108074. /**
  108075. * Checks wether the material is ready to be rendered for a given mesh.
  108076. * @param mesh The mesh to render
  108077. * @param subMesh The submesh to check against
  108078. * @param useInstances Specify wether or not the material is used with instances
  108079. * @returns true if all the dependencies are ready (Textures, Effects...)
  108080. */
  108081. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  108082. var _this = this;
  108083. if (useInstances === void 0) { useInstances = false; }
  108084. if (subMesh.effect && this.isFrozen) {
  108085. if (this._wasPreviouslyReady) {
  108086. return true;
  108087. }
  108088. }
  108089. if (!subMesh._materialDefines) {
  108090. subMesh._materialDefines = new BackgroundMaterialDefines();
  108091. }
  108092. var scene = this.getScene();
  108093. var defines = subMesh._materialDefines;
  108094. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  108095. if (defines._renderId === scene.getRenderId()) {
  108096. return true;
  108097. }
  108098. }
  108099. var engine = scene.getEngine();
  108100. // Lights
  108101. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  108102. defines._needNormals = true;
  108103. // Textures
  108104. if (defines._areTexturesDirty) {
  108105. defines._needUVs = false;
  108106. if (scene.texturesEnabled) {
  108107. if (scene.getEngine().getCaps().textureLOD) {
  108108. defines.TEXTURELODSUPPORT = true;
  108109. }
  108110. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108111. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  108112. return false;
  108113. }
  108114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  108115. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  108116. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  108117. defines.OPACITYFRESNEL = this._opacityFresnel;
  108118. }
  108119. else {
  108120. defines.DIFFUSE = false;
  108121. defines.DIFFUSEHASALPHA = false;
  108122. defines.GAMMADIFFUSE = false;
  108123. defines.OPACITYFRESNEL = false;
  108124. }
  108125. var reflectionTexture = this._reflectionTexture;
  108126. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108127. if (!reflectionTexture.isReadyOrNotBlocking()) {
  108128. return false;
  108129. }
  108130. defines.REFLECTION = true;
  108131. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  108132. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  108133. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  108134. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  108135. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  108136. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  108137. defines.REFLECTIONBGR = this.switchToBGR;
  108138. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  108139. defines.INVERTCUBICMAP = true;
  108140. }
  108141. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  108142. switch (reflectionTexture.coordinatesMode) {
  108143. case BABYLON.Texture.EXPLICIT_MODE:
  108144. defines.REFLECTIONMAP_EXPLICIT = true;
  108145. break;
  108146. case BABYLON.Texture.PLANAR_MODE:
  108147. defines.REFLECTIONMAP_PLANAR = true;
  108148. break;
  108149. case BABYLON.Texture.PROJECTION_MODE:
  108150. defines.REFLECTIONMAP_PROJECTION = true;
  108151. break;
  108152. case BABYLON.Texture.SKYBOX_MODE:
  108153. defines.REFLECTIONMAP_SKYBOX = true;
  108154. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  108155. break;
  108156. case BABYLON.Texture.SPHERICAL_MODE:
  108157. defines.REFLECTIONMAP_SPHERICAL = true;
  108158. break;
  108159. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  108160. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  108161. break;
  108162. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  108163. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  108164. break;
  108165. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  108166. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  108167. break;
  108168. case BABYLON.Texture.CUBIC_MODE:
  108169. case BABYLON.Texture.INVCUBIC_MODE:
  108170. default:
  108171. defines.REFLECTIONMAP_CUBIC = true;
  108172. break;
  108173. }
  108174. if (this.reflectionFresnel) {
  108175. defines.REFLECTIONFRESNEL = true;
  108176. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  108177. this._reflectionControls.x = this.reflectionAmount;
  108178. this._reflectionControls.y = this.reflectionReflectance0;
  108179. this._reflectionControls.z = this.reflectionReflectance90;
  108180. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  108181. }
  108182. else {
  108183. defines.REFLECTIONFRESNEL = false;
  108184. defines.REFLECTIONFALLOFF = false;
  108185. }
  108186. }
  108187. else {
  108188. defines.REFLECTION = false;
  108189. defines.REFLECTIONFRESNEL = false;
  108190. defines.REFLECTIONFALLOFF = false;
  108191. defines.REFLECTIONBLUR = false;
  108192. defines.REFLECTIONMAP_3D = false;
  108193. defines.REFLECTIONMAP_SPHERICAL = false;
  108194. defines.REFLECTIONMAP_PLANAR = false;
  108195. defines.REFLECTIONMAP_CUBIC = false;
  108196. defines.REFLECTIONMAP_PROJECTION = false;
  108197. defines.REFLECTIONMAP_SKYBOX = false;
  108198. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  108199. defines.REFLECTIONMAP_EXPLICIT = false;
  108200. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  108201. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  108202. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  108203. defines.INVERTCUBICMAP = false;
  108204. defines.REFLECTIONMAP_OPPOSITEZ = false;
  108205. defines.LODINREFLECTIONALPHA = false;
  108206. defines.GAMMAREFLECTION = false;
  108207. defines.RGBDREFLECTION = false;
  108208. }
  108209. }
  108210. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  108211. defines.USERGBCOLOR = this._useRGBColor;
  108212. defines.NOISE = this._enableNoise;
  108213. }
  108214. if (defines._areLightsDirty) {
  108215. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  108216. }
  108217. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  108218. if (!this._imageProcessingConfiguration.isReady()) {
  108219. return false;
  108220. }
  108221. this._imageProcessingConfiguration.prepareDefines(defines);
  108222. }
  108223. // Misc.
  108224. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  108225. // Values that need to be evaluated on every frame
  108226. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  108227. // Attribs
  108228. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  108229. if (mesh) {
  108230. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  108231. mesh.createNormals(true);
  108232. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  108233. }
  108234. }
  108235. }
  108236. // Get correct effect
  108237. if (defines.isDirty) {
  108238. defines.markAsProcessed();
  108239. scene.resetCachedMaterial();
  108240. // Fallbacks
  108241. var fallbacks = new BABYLON.EffectFallbacks();
  108242. if (defines.FOG) {
  108243. fallbacks.addFallback(0, "FOG");
  108244. }
  108245. if (defines.POINTSIZE) {
  108246. fallbacks.addFallback(1, "POINTSIZE");
  108247. }
  108248. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  108249. if (defines.NUM_BONE_INFLUENCERS > 0) {
  108250. fallbacks.addCPUSkinningFallback(0, mesh);
  108251. }
  108252. //Attributes
  108253. var attribs = [BABYLON.VertexBuffer.PositionKind];
  108254. if (defines.NORMAL) {
  108255. attribs.push(BABYLON.VertexBuffer.NormalKind);
  108256. }
  108257. if (defines.UV1) {
  108258. attribs.push(BABYLON.VertexBuffer.UVKind);
  108259. }
  108260. if (defines.UV2) {
  108261. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108262. }
  108263. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  108264. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  108265. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  108266. "vFogInfos", "vFogColor", "pointSize",
  108267. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  108268. "vPrimaryColor", "vPrimaryColorShadow",
  108269. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  108270. "shadowLevel", "alpha",
  108271. "vBackgroundCenter", "vReflectionControl",
  108272. "vDiffuseInfos", "diffuseMatrix",
  108273. ];
  108274. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  108275. var uniformBuffers = ["Material", "Scene"];
  108276. if (BABYLON.ImageProcessingConfiguration) {
  108277. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  108278. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  108279. }
  108280. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  108281. uniformsNames: uniforms,
  108282. uniformBuffersNames: uniformBuffers,
  108283. samplers: samplers,
  108284. defines: defines,
  108285. maxSimultaneousLights: this._maxSimultaneousLights
  108286. });
  108287. var onCompiled = function (effect) {
  108288. if (_this.onCompiled) {
  108289. _this.onCompiled(effect);
  108290. }
  108291. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  108292. };
  108293. var join = defines.toString();
  108294. subMesh.setEffect(scene.getEngine().createEffect("background", {
  108295. attributes: attribs,
  108296. uniformsNames: uniforms,
  108297. uniformBuffersNames: uniformBuffers,
  108298. samplers: samplers,
  108299. defines: join,
  108300. fallbacks: fallbacks,
  108301. onCompiled: onCompiled,
  108302. onError: this.onError,
  108303. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  108304. }, engine), defines);
  108305. this.buildUniformLayout();
  108306. }
  108307. if (!subMesh.effect || !subMesh.effect.isReady()) {
  108308. return false;
  108309. }
  108310. defines._renderId = scene.getRenderId();
  108311. this._wasPreviouslyReady = true;
  108312. return true;
  108313. };
  108314. /**
  108315. * Compute the primary color according to the chosen perceptual color.
  108316. */
  108317. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  108318. if (!this.__perceptualColor) {
  108319. return;
  108320. }
  108321. this._primaryColor.copyFrom(this.__perceptualColor);
  108322. // Revert gamma space.
  108323. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  108324. // Revert image processing configuration.
  108325. if (this._imageProcessingConfiguration) {
  108326. // Revert Exposure.
  108327. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  108328. }
  108329. this._computePrimaryColors();
  108330. };
  108331. /**
  108332. * Compute the highlights and shadow colors according to their chosen levels.
  108333. */
  108334. BackgroundMaterial.prototype._computePrimaryColors = function () {
  108335. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  108336. return;
  108337. }
  108338. // Find the highlight color based on the configuration.
  108339. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  108340. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  108341. // Find the shadow color based on the configuration.
  108342. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  108343. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  108344. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  108345. };
  108346. /**
  108347. * Build the uniform buffer used in the material.
  108348. */
  108349. BackgroundMaterial.prototype.buildUniformLayout = function () {
  108350. // Order is important !
  108351. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  108352. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  108353. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  108354. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  108355. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  108356. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  108357. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  108358. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  108359. this._uniformBuffer.addUniform("pointSize", 1);
  108360. this._uniformBuffer.addUniform("shadowLevel", 1);
  108361. this._uniformBuffer.addUniform("alpha", 1);
  108362. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  108363. this._uniformBuffer.addUniform("vReflectionControl", 4);
  108364. this._uniformBuffer.create();
  108365. };
  108366. /**
  108367. * Unbind the material.
  108368. */
  108369. BackgroundMaterial.prototype.unbind = function () {
  108370. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108371. this._uniformBuffer.setTexture("diffuseSampler", null);
  108372. }
  108373. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108374. this._uniformBuffer.setTexture("reflectionSampler", null);
  108375. }
  108376. _super.prototype.unbind.call(this);
  108377. };
  108378. /**
  108379. * Bind only the world matrix to the material.
  108380. * @param world The world matrix to bind.
  108381. */
  108382. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  108383. this._activeEffect.setMatrix("world", world);
  108384. };
  108385. /**
  108386. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  108387. * @param world The world matrix to bind.
  108388. * @param subMesh The submesh to bind for.
  108389. */
  108390. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  108391. var scene = this.getScene();
  108392. var defines = subMesh._materialDefines;
  108393. if (!defines) {
  108394. return;
  108395. }
  108396. var effect = subMesh.effect;
  108397. if (!effect) {
  108398. return;
  108399. }
  108400. this._activeEffect = effect;
  108401. // Matrices
  108402. this.bindOnlyWorldMatrix(world);
  108403. // Bones
  108404. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  108405. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  108406. if (mustRebind) {
  108407. this._uniformBuffer.bindToEffect(effect, "Material");
  108408. this.bindViewProjection(effect);
  108409. var reflectionTexture = this._reflectionTexture;
  108410. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  108411. // Texture uniforms
  108412. if (scene.texturesEnabled) {
  108413. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108414. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  108415. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  108416. }
  108417. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108418. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  108419. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  108420. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  108421. }
  108422. }
  108423. if (this.shadowLevel > 0) {
  108424. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  108425. }
  108426. this._uniformBuffer.updateFloat("alpha", this.alpha);
  108427. // Point size
  108428. if (this.pointsCloud) {
  108429. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  108430. }
  108431. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  108432. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  108433. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  108434. }
  108435. else {
  108436. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  108437. }
  108438. }
  108439. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  108440. // Textures
  108441. if (scene.texturesEnabled) {
  108442. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108443. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  108444. }
  108445. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108446. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  108447. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108448. }
  108449. else if (!defines.REFLECTIONBLUR) {
  108450. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108451. }
  108452. else {
  108453. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  108454. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  108455. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  108456. }
  108457. if (defines.REFLECTIONFRESNEL) {
  108458. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  108459. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  108460. }
  108461. }
  108462. }
  108463. // Clip plane
  108464. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  108465. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  108466. }
  108467. if (mustRebind || !this.isFrozen) {
  108468. if (scene.lightsEnabled) {
  108469. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  108470. }
  108471. // View
  108472. this.bindView(effect);
  108473. // Fog
  108474. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  108475. // image processing
  108476. if (this._imageProcessingConfiguration) {
  108477. this._imageProcessingConfiguration.bind(this._activeEffect);
  108478. }
  108479. }
  108480. this._uniformBuffer.update();
  108481. this._afterBind(mesh, this._activeEffect);
  108482. };
  108483. /**
  108484. * Dispose the material.
  108485. * @param forceDisposeEffect Force disposal of the associated effect.
  108486. * @param forceDisposeTextures Force disposal of the associated textures.
  108487. */
  108488. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  108489. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  108490. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  108491. if (forceDisposeTextures) {
  108492. if (this.diffuseTexture) {
  108493. this.diffuseTexture.dispose();
  108494. }
  108495. if (this.reflectionTexture) {
  108496. this.reflectionTexture.dispose();
  108497. }
  108498. }
  108499. this._renderTargets.dispose();
  108500. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  108501. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  108502. }
  108503. _super.prototype.dispose.call(this, forceDisposeEffect);
  108504. };
  108505. /**
  108506. * Clones the material.
  108507. * @param name The cloned name.
  108508. * @returns The cloned material.
  108509. */
  108510. BackgroundMaterial.prototype.clone = function (name) {
  108511. var _this = this;
  108512. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  108513. };
  108514. /**
  108515. * Serializes the current material to its JSON representation.
  108516. * @returns The JSON representation.
  108517. */
  108518. BackgroundMaterial.prototype.serialize = function () {
  108519. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108520. serializationObject.customType = "BABYLON.BackgroundMaterial";
  108521. return serializationObject;
  108522. };
  108523. /**
  108524. * Gets the class name of the material
  108525. * @returns "BackgroundMaterial"
  108526. */
  108527. BackgroundMaterial.prototype.getClassName = function () {
  108528. return "BackgroundMaterial";
  108529. };
  108530. /**
  108531. * Parse a JSON input to create back a background material.
  108532. * @param source The JSON data to parse
  108533. * @param scene The scene to create the parsed material in
  108534. * @param rootUrl The root url of the assets the material depends upon
  108535. * @returns the instantiated BackgroundMaterial.
  108536. */
  108537. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  108538. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  108539. };
  108540. /**
  108541. * Standard reflectance value at parallel view angle.
  108542. */
  108543. BackgroundMaterial.StandardReflectance0 = 0.05;
  108544. /**
  108545. * Standard reflectance value at grazing angle.
  108546. */
  108547. BackgroundMaterial.StandardReflectance90 = 0.5;
  108548. __decorate([
  108549. BABYLON.serializeAsColor3()
  108550. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  108551. __decorate([
  108552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108553. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  108554. __decorate([
  108555. BABYLON.serializeAsColor3()
  108556. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  108557. __decorate([
  108558. BABYLON.serialize()
  108559. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  108560. __decorate([
  108561. BABYLON.serialize()
  108562. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  108563. __decorate([
  108564. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108565. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  108566. __decorate([
  108567. BABYLON.serializeAsTexture()
  108568. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  108569. __decorate([
  108570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108571. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  108572. __decorate([
  108573. BABYLON.serialize()
  108574. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  108575. __decorate([
  108576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108577. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  108578. __decorate([
  108579. BABYLON.serializeAsTexture()
  108580. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  108581. __decorate([
  108582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108583. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  108584. __decorate([
  108585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108586. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  108587. __decorate([
  108588. BABYLON.serialize()
  108589. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  108590. __decorate([
  108591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108592. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  108593. __decorate([
  108594. BABYLON.serializeAsVector3()
  108595. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  108596. __decorate([
  108597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108598. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  108599. __decorate([
  108600. BABYLON.serialize()
  108601. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  108602. __decorate([
  108603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108604. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  108605. __decorate([
  108606. BABYLON.serialize()
  108607. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  108608. __decorate([
  108609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108610. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  108611. __decorate([
  108612. BABYLON.serialize()
  108613. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  108614. __decorate([
  108615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108616. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  108617. __decorate([
  108618. BABYLON.serialize()
  108619. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  108620. __decorate([
  108621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108622. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  108623. __decorate([
  108624. BABYLON.serialize()
  108625. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  108626. __decorate([
  108627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108628. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  108629. __decorate([
  108630. BABYLON.serialize()
  108631. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  108632. __decorate([
  108633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108634. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  108635. __decorate([
  108636. BABYLON.serialize()
  108637. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  108638. __decorate([
  108639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108640. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  108641. __decorate([
  108642. BABYLON.serialize()
  108643. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  108644. __decorate([
  108645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108646. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  108647. __decorate([
  108648. BABYLON.serialize()
  108649. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  108650. __decorate([
  108651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108652. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  108653. __decorate([
  108654. BABYLON.serializeAsImageProcessingConfiguration()
  108655. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  108656. return BackgroundMaterial;
  108657. }(BABYLON.PushMaterial));
  108658. BABYLON.BackgroundMaterial = BackgroundMaterial;
  108659. })(BABYLON || (BABYLON = {}));
  108660. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  108661. var __assign = (this && this.__assign) || function () {
  108662. __assign = Object.assign || function(t) {
  108663. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108664. s = arguments[i];
  108665. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108666. t[p] = s[p];
  108667. }
  108668. return t;
  108669. };
  108670. return __assign.apply(this, arguments);
  108671. };
  108672. var BABYLON;
  108673. (function (BABYLON) {
  108674. /**
  108675. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  108676. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  108677. * It also helps with the default setup of your imageProcessing configuration.
  108678. */
  108679. var EnvironmentHelper = /** @class */ (function () {
  108680. /**
  108681. * constructor
  108682. * @param options
  108683. * @param scene The scene to add the material to
  108684. */
  108685. function EnvironmentHelper(options, scene) {
  108686. var _this = this;
  108687. this._errorHandler = function (message, exception) {
  108688. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  108689. };
  108690. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  108691. this._scene = scene;
  108692. this.onErrorObservable = new BABYLON.Observable();
  108693. this._setupBackground();
  108694. this._setupImageProcessing();
  108695. }
  108696. /**
  108697. * Creates the default options for the helper.
  108698. */
  108699. EnvironmentHelper._getDefaultOptions = function () {
  108700. return {
  108701. createGround: true,
  108702. groundSize: 15,
  108703. groundTexture: this._groundTextureCDNUrl,
  108704. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108705. groundOpacity: 0.9,
  108706. enableGroundShadow: true,
  108707. groundShadowLevel: 0.5,
  108708. enableGroundMirror: false,
  108709. groundMirrorSizeRatio: 0.3,
  108710. groundMirrorBlurKernel: 64,
  108711. groundMirrorAmount: 1,
  108712. groundMirrorFresnelWeight: 1,
  108713. groundMirrorFallOffDistance: 0,
  108714. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  108715. groundYBias: 0.00001,
  108716. createSkybox: true,
  108717. skyboxSize: 20,
  108718. skyboxTexture: this._skyboxTextureCDNUrl,
  108719. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108720. backgroundYRotation: 0,
  108721. sizeAuto: true,
  108722. rootPosition: BABYLON.Vector3.Zero(),
  108723. setupImageProcessing: true,
  108724. environmentTexture: this._environmentTextureCDNUrl,
  108725. cameraExposure: 0.8,
  108726. cameraContrast: 1.2,
  108727. toneMappingEnabled: true,
  108728. };
  108729. };
  108730. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  108731. /**
  108732. * Gets the root mesh created by the helper.
  108733. */
  108734. get: function () {
  108735. return this._rootMesh;
  108736. },
  108737. enumerable: true,
  108738. configurable: true
  108739. });
  108740. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  108741. /**
  108742. * Gets the skybox created by the helper.
  108743. */
  108744. get: function () {
  108745. return this._skybox;
  108746. },
  108747. enumerable: true,
  108748. configurable: true
  108749. });
  108750. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  108751. /**
  108752. * Gets the skybox texture created by the helper.
  108753. */
  108754. get: function () {
  108755. return this._skyboxTexture;
  108756. },
  108757. enumerable: true,
  108758. configurable: true
  108759. });
  108760. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  108761. /**
  108762. * Gets the skybox material created by the helper.
  108763. */
  108764. get: function () {
  108765. return this._skyboxMaterial;
  108766. },
  108767. enumerable: true,
  108768. configurable: true
  108769. });
  108770. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  108771. /**
  108772. * Gets the ground mesh created by the helper.
  108773. */
  108774. get: function () {
  108775. return this._ground;
  108776. },
  108777. enumerable: true,
  108778. configurable: true
  108779. });
  108780. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  108781. /**
  108782. * Gets the ground texture created by the helper.
  108783. */
  108784. get: function () {
  108785. return this._groundTexture;
  108786. },
  108787. enumerable: true,
  108788. configurable: true
  108789. });
  108790. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108791. /**
  108792. * Gets the ground mirror created by the helper.
  108793. */
  108794. get: function () {
  108795. return this._groundMirror;
  108796. },
  108797. enumerable: true,
  108798. configurable: true
  108799. });
  108800. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108801. /**
  108802. * Gets the ground mirror render list to helps pushing the meshes
  108803. * you wish in the ground reflection.
  108804. */
  108805. get: function () {
  108806. if (this._groundMirror) {
  108807. return this._groundMirror.renderList;
  108808. }
  108809. return null;
  108810. },
  108811. enumerable: true,
  108812. configurable: true
  108813. });
  108814. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108815. /**
  108816. * Gets the ground material created by the helper.
  108817. */
  108818. get: function () {
  108819. return this._groundMaterial;
  108820. },
  108821. enumerable: true,
  108822. configurable: true
  108823. });
  108824. /**
  108825. * Updates the background according to the new options
  108826. * @param options
  108827. */
  108828. EnvironmentHelper.prototype.updateOptions = function (options) {
  108829. var newOptions = __assign({}, this._options, options);
  108830. if (this._ground && !newOptions.createGround) {
  108831. this._ground.dispose();
  108832. this._ground = null;
  108833. }
  108834. if (this._groundMaterial && !newOptions.createGround) {
  108835. this._groundMaterial.dispose();
  108836. this._groundMaterial = null;
  108837. }
  108838. if (this._groundTexture) {
  108839. if (this._options.groundTexture != newOptions.groundTexture) {
  108840. this._groundTexture.dispose();
  108841. this._groundTexture = null;
  108842. }
  108843. }
  108844. if (this._skybox && !newOptions.createSkybox) {
  108845. this._skybox.dispose();
  108846. this._skybox = null;
  108847. }
  108848. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108849. this._skyboxMaterial.dispose();
  108850. this._skyboxMaterial = null;
  108851. }
  108852. if (this._skyboxTexture) {
  108853. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108854. this._skyboxTexture.dispose();
  108855. this._skyboxTexture = null;
  108856. }
  108857. }
  108858. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108859. this._groundMirror.dispose();
  108860. this._groundMirror = null;
  108861. }
  108862. if (this._scene.environmentTexture) {
  108863. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108864. this._scene.environmentTexture.dispose();
  108865. }
  108866. }
  108867. this._options = newOptions;
  108868. this._setupBackground();
  108869. this._setupImageProcessing();
  108870. };
  108871. /**
  108872. * Sets the primary color of all the available elements.
  108873. * @param color the main color to affect to the ground and the background
  108874. */
  108875. EnvironmentHelper.prototype.setMainColor = function (color) {
  108876. if (this.groundMaterial) {
  108877. this.groundMaterial.primaryColor = color;
  108878. }
  108879. if (this.skyboxMaterial) {
  108880. this.skyboxMaterial.primaryColor = color;
  108881. }
  108882. if (this.groundMirror) {
  108883. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108884. }
  108885. };
  108886. /**
  108887. * Setup the image processing according to the specified options.
  108888. */
  108889. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108890. if (this._options.setupImageProcessing) {
  108891. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108892. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108893. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108894. this._setupEnvironmentTexture();
  108895. }
  108896. };
  108897. /**
  108898. * Setup the environment texture according to the specified options.
  108899. */
  108900. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108901. if (this._scene.environmentTexture) {
  108902. return;
  108903. }
  108904. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108905. this._scene.environmentTexture = this._options.environmentTexture;
  108906. return;
  108907. }
  108908. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108909. this._scene.environmentTexture = environmentTexture;
  108910. };
  108911. /**
  108912. * Setup the background according to the specified options.
  108913. */
  108914. EnvironmentHelper.prototype._setupBackground = function () {
  108915. if (!this._rootMesh) {
  108916. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108917. }
  108918. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108919. var sceneSize = this._getSceneSize();
  108920. if (this._options.createGround) {
  108921. this._setupGround(sceneSize);
  108922. this._setupGroundMaterial();
  108923. this._setupGroundDiffuseTexture();
  108924. if (this._options.enableGroundMirror) {
  108925. this._setupGroundMirrorTexture(sceneSize);
  108926. }
  108927. this._setupMirrorInGroundMaterial();
  108928. }
  108929. if (this._options.createSkybox) {
  108930. this._setupSkybox(sceneSize);
  108931. this._setupSkyboxMaterial();
  108932. this._setupSkyboxReflectionTexture();
  108933. }
  108934. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108935. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108936. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108937. };
  108938. /**
  108939. * Get the scene sizes according to the setup.
  108940. */
  108941. EnvironmentHelper.prototype._getSceneSize = function () {
  108942. var _this = this;
  108943. var groundSize = this._options.groundSize;
  108944. var skyboxSize = this._options.skyboxSize;
  108945. var rootPosition = this._options.rootPosition;
  108946. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108947. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108948. }
  108949. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108950. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108951. });
  108952. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108953. if (this._options.sizeAuto) {
  108954. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108955. this._scene.activeCamera.upperRadiusLimit) {
  108956. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108957. skyboxSize = groundSize;
  108958. }
  108959. var sceneDiagonalLenght = sceneDiagonal.length();
  108960. if (sceneDiagonalLenght > groundSize) {
  108961. groundSize = sceneDiagonalLenght * 2;
  108962. skyboxSize = groundSize;
  108963. }
  108964. // 10 % bigger.
  108965. groundSize *= 1.1;
  108966. skyboxSize *= 1.5;
  108967. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108968. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108969. }
  108970. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108971. };
  108972. /**
  108973. * Setup the ground according to the specified options.
  108974. */
  108975. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108976. var _this = this;
  108977. if (!this._ground || this._ground.isDisposed()) {
  108978. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108979. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108980. this._ground.parent = this._rootMesh;
  108981. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108982. }
  108983. this._ground.receiveShadows = this._options.enableGroundShadow;
  108984. };
  108985. /**
  108986. * Setup the ground material according to the specified options.
  108987. */
  108988. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108989. if (!this._groundMaterial) {
  108990. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108991. }
  108992. this._groundMaterial.alpha = this._options.groundOpacity;
  108993. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108994. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108995. this._groundMaterial.primaryColor = this._options.groundColor;
  108996. this._groundMaterial.useRGBColor = false;
  108997. this._groundMaterial.enableNoise = true;
  108998. if (this._ground) {
  108999. this._ground.material = this._groundMaterial;
  109000. }
  109001. };
  109002. /**
  109003. * Setup the ground diffuse texture according to the specified options.
  109004. */
  109005. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  109006. if (!this._groundMaterial) {
  109007. return;
  109008. }
  109009. if (this._groundTexture) {
  109010. return;
  109011. }
  109012. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  109013. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  109014. return;
  109015. }
  109016. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  109017. diffuseTexture.gammaSpace = false;
  109018. diffuseTexture.hasAlpha = true;
  109019. this._groundMaterial.diffuseTexture = diffuseTexture;
  109020. };
  109021. /**
  109022. * Setup the ground mirror texture according to the specified options.
  109023. */
  109024. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  109025. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109026. if (!this._groundMirror) {
  109027. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  109028. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  109029. this._groundMirror.anisotropicFilteringLevel = 1;
  109030. this._groundMirror.wrapU = wrapping;
  109031. this._groundMirror.wrapV = wrapping;
  109032. this._groundMirror.gammaSpace = false;
  109033. if (this._groundMirror.renderList) {
  109034. for (var i = 0; i < this._scene.meshes.length; i++) {
  109035. var mesh = this._scene.meshes[i];
  109036. if (mesh !== this._ground &&
  109037. mesh !== this._skybox &&
  109038. mesh !== this._rootMesh) {
  109039. this._groundMirror.renderList.push(mesh);
  109040. }
  109041. }
  109042. }
  109043. }
  109044. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  109045. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  109046. };
  109047. /**
  109048. * Setup the ground to receive the mirror texture.
  109049. */
  109050. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  109051. if (this._groundMaterial) {
  109052. this._groundMaterial.reflectionTexture = this._groundMirror;
  109053. this._groundMaterial.reflectionFresnel = true;
  109054. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  109055. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  109056. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  109057. }
  109058. };
  109059. /**
  109060. * Setup the skybox according to the specified options.
  109061. */
  109062. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  109063. var _this = this;
  109064. if (!this._skybox || this._skybox.isDisposed()) {
  109065. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  109066. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  109067. }
  109068. this._skybox.parent = this._rootMesh;
  109069. };
  109070. /**
  109071. * Setup the skybox material according to the specified options.
  109072. */
  109073. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  109074. if (!this._skybox) {
  109075. return;
  109076. }
  109077. if (!this._skyboxMaterial) {
  109078. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  109079. }
  109080. this._skyboxMaterial.useRGBColor = false;
  109081. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  109082. this._skyboxMaterial.enableNoise = true;
  109083. this._skybox.material = this._skyboxMaterial;
  109084. };
  109085. /**
  109086. * Setup the skybox reflection texture according to the specified options.
  109087. */
  109088. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  109089. if (!this._skyboxMaterial) {
  109090. return;
  109091. }
  109092. if (this._skyboxTexture) {
  109093. return;
  109094. }
  109095. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  109096. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  109097. return;
  109098. }
  109099. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  109100. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109101. this._skyboxTexture.gammaSpace = false;
  109102. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  109103. };
  109104. /**
  109105. * Dispose all the elements created by the Helper.
  109106. */
  109107. EnvironmentHelper.prototype.dispose = function () {
  109108. if (this._groundMaterial) {
  109109. this._groundMaterial.dispose(true, true);
  109110. }
  109111. if (this._skyboxMaterial) {
  109112. this._skyboxMaterial.dispose(true, true);
  109113. }
  109114. this._rootMesh.dispose(false);
  109115. };
  109116. /**
  109117. * Default ground texture URL.
  109118. */
  109119. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  109120. /**
  109121. * Default skybox texture URL.
  109122. */
  109123. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  109124. /**
  109125. * Default environment texture URL.
  109126. */
  109127. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  109128. return EnvironmentHelper;
  109129. }());
  109130. BABYLON.EnvironmentHelper = EnvironmentHelper;
  109131. })(BABYLON || (BABYLON = {}));
  109132. //# sourceMappingURL=babylon.environmentHelper.js.map
  109133. var BABYLON;
  109134. (function (BABYLON) {
  109135. /** Internal class used to store shapes for emitters */
  109136. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  109137. function ParticleSystemSetEmitterCreationOptions() {
  109138. }
  109139. return ParticleSystemSetEmitterCreationOptions;
  109140. }());
  109141. /**
  109142. * Represents a set of particle systems working together to create a specific effect
  109143. */
  109144. var ParticleSystemSet = /** @class */ (function () {
  109145. function ParticleSystemSet() {
  109146. /**
  109147. * Gets the particle system list
  109148. */
  109149. this.systems = new Array();
  109150. }
  109151. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  109152. /**
  109153. * Gets the emitter node used with this set
  109154. */
  109155. get: function () {
  109156. return this._emitterNode;
  109157. },
  109158. enumerable: true,
  109159. configurable: true
  109160. });
  109161. /**
  109162. * Creates a new emitter mesh as a sphere
  109163. * @param options defines the options used to create the sphere
  109164. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  109165. * @param scene defines the hosting scene
  109166. */
  109167. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  109168. if (this._emitterNode) {
  109169. this._emitterNode.dispose();
  109170. }
  109171. this._emitterCreationOptions = {
  109172. kind: "Sphere",
  109173. options: options,
  109174. renderingGroupId: renderingGroupId
  109175. };
  109176. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  109177. emitterMesh.renderingGroupId = renderingGroupId;
  109178. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  109179. material.emissiveColor = options.color;
  109180. emitterMesh.material = material;
  109181. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109182. var system = _a[_i];
  109183. system.emitter = emitterMesh;
  109184. }
  109185. this._emitterNode = emitterMesh;
  109186. };
  109187. /**
  109188. * Starts all particle systems of the set
  109189. * @param emitter defines an optional mesh to use as emitter for the particle systems
  109190. */
  109191. ParticleSystemSet.prototype.start = function (emitter) {
  109192. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109193. var system = _a[_i];
  109194. if (emitter) {
  109195. system.emitter = emitter;
  109196. }
  109197. system.start();
  109198. }
  109199. };
  109200. /**
  109201. * Release all associated resources
  109202. */
  109203. ParticleSystemSet.prototype.dispose = function () {
  109204. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109205. var system = _a[_i];
  109206. system.dispose();
  109207. }
  109208. this.systems = [];
  109209. if (this._emitterNode) {
  109210. this._emitterNode.dispose();
  109211. this._emitterNode = null;
  109212. }
  109213. };
  109214. /**
  109215. * Serialize the set into a JSON compatible object
  109216. * @returns a JSON compatible representation of the set
  109217. */
  109218. ParticleSystemSet.prototype.serialize = function () {
  109219. var result = {};
  109220. result.systems = [];
  109221. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  109222. var system = _a[_i];
  109223. result.systems.push(system.serialize());
  109224. }
  109225. if (this._emitterNode) {
  109226. result.emitter = this._emitterCreationOptions;
  109227. }
  109228. return result;
  109229. };
  109230. /**
  109231. * Parse a new ParticleSystemSet from a serialized source
  109232. * @param data defines a JSON compatible representation of the set
  109233. * @param scene defines the hosting scene
  109234. * @param gpu defines if we want GPU particles or CPU particles
  109235. * @returns a new ParticleSystemSet
  109236. */
  109237. ParticleSystemSet.Parse = function (data, scene, gpu) {
  109238. if (gpu === void 0) { gpu = false; }
  109239. var result = new ParticleSystemSet();
  109240. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  109241. scene = scene || BABYLON.Engine.LastCreatedScene;
  109242. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  109243. var system = _a[_i];
  109244. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  109245. }
  109246. if (data.emitter) {
  109247. var options = data.emitter.options;
  109248. switch (data.emitter.kind) {
  109249. case "Sphere":
  109250. result.setEmitterAsSphere({
  109251. diameter: options.diameter,
  109252. segments: options.segments,
  109253. color: BABYLON.Color3.FromArray(options.color)
  109254. }, data.emitter.renderingGroupId, scene);
  109255. break;
  109256. }
  109257. }
  109258. return result;
  109259. };
  109260. return ParticleSystemSet;
  109261. }());
  109262. BABYLON.ParticleSystemSet = ParticleSystemSet;
  109263. })(BABYLON || (BABYLON = {}));
  109264. //# sourceMappingURL=babylon.particleSystemSet.js.map
  109265. var BABYLON;
  109266. (function (BABYLON) {
  109267. /**
  109268. * This class is made for on one-liner static method to help creating particle system set.
  109269. */
  109270. var ParticleHelper = /** @class */ (function () {
  109271. function ParticleHelper() {
  109272. }
  109273. /**
  109274. * Create a default particle system that you can tweak
  109275. * @param emitter defines the emitter to use
  109276. * @param capacity defines the system capacity (default is 500 particles)
  109277. * @param scene defines the hosting scene
  109278. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  109279. * @returns the new Particle system
  109280. */
  109281. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  109282. if (capacity === void 0) { capacity = 500; }
  109283. if (useGPU === void 0) { useGPU = false; }
  109284. var system;
  109285. if (useGPU) {
  109286. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  109287. }
  109288. else {
  109289. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  109290. }
  109291. system.emitter = emitter;
  109292. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  109293. system.createConeEmitter(0.1, Math.PI / 4);
  109294. // Particle color
  109295. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  109296. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  109297. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  109298. // Particle Size
  109299. system.minSize = 0.1;
  109300. system.maxSize = 0.1;
  109301. // Emission speed
  109302. system.minEmitPower = 2;
  109303. system.maxEmitPower = 2;
  109304. // Update speed
  109305. system.updateSpeed = 1 / 60;
  109306. system.emitRate = 30;
  109307. return system;
  109308. };
  109309. /**
  109310. * This is the main static method (one-liner) of this helper to create different particle systems
  109311. * @param type This string represents the type to the particle system to create
  109312. * @param scene The scene where the particle system should live
  109313. * @param gpu If the system will use gpu
  109314. * @returns the ParticleSystemSet created
  109315. */
  109316. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  109317. if (gpu === void 0) { gpu = false; }
  109318. if (!scene) {
  109319. scene = BABYLON.Engine.LastCreatedScene;
  109320. ;
  109321. }
  109322. var token = {};
  109323. scene._addPendingData(token);
  109324. return new Promise(function (resolve, reject) {
  109325. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  109326. scene._removePendingData(token);
  109327. return reject("Particle system with GPU is not supported.");
  109328. }
  109329. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  109330. scene._removePendingData(token);
  109331. var newData = JSON.parse(data.toString());
  109332. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  109333. }, undefined, undefined, undefined, function (req, exception) {
  109334. scene._removePendingData(token);
  109335. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  109336. });
  109337. });
  109338. };
  109339. /**
  109340. * Static function used to export a particle system to a ParticleSystemSet variable.
  109341. * Please note that the emitter shape is not exported
  109342. * @param system defines the particle systems to export
  109343. */
  109344. ParticleHelper.ExportSet = function (systems) {
  109345. var set = new BABYLON.ParticleSystemSet();
  109346. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  109347. var system = systems_1[_i];
  109348. set.systems.push(system);
  109349. }
  109350. return set;
  109351. };
  109352. /**
  109353. * Gets or sets base Assets URL
  109354. */
  109355. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  109356. return ParticleHelper;
  109357. }());
  109358. BABYLON.ParticleHelper = ParticleHelper;
  109359. })(BABYLON || (BABYLON = {}));
  109360. //# sourceMappingURL=babylon.particleHelper.js.map
  109361. var BABYLON;
  109362. (function (BABYLON) {
  109363. /**
  109364. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  109365. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  109366. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  109367. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109368. */
  109369. var VideoDome = /** @class */ (function (_super) {
  109370. __extends(VideoDome, _super);
  109371. /**
  109372. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  109373. * @param name Element's name, child elements will append suffixes for their own names.
  109374. * @param urlsOrVideo defines the url(s) or the video element to use
  109375. * @param options An object containing optional or exposed sub element properties
  109376. */
  109377. function VideoDome(name, urlsOrVideo, options, scene) {
  109378. var _this = _super.call(this, name, scene) || this;
  109379. _this._useDirectMapping = false;
  109380. // set defaults and manage values
  109381. name = name || "videoDome";
  109382. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109383. options.clickToPlay = Boolean(options.clickToPlay);
  109384. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  109385. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  109386. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109387. if (options.useDirectMapping === undefined) {
  109388. _this._useDirectMapping = true;
  109389. }
  109390. else {
  109391. _this._useDirectMapping = options.useDirectMapping;
  109392. }
  109393. _this._setReady(false);
  109394. // create
  109395. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  109396. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109397. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  109398. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109399. texture.onLoadObservable.addOnce(function () {
  109400. _this._setReady(true);
  109401. });
  109402. // configure material
  109403. material.useEquirectangularFOV = true;
  109404. material.fovMultiplier = 1.0;
  109405. material.opacityFresnel = false;
  109406. if (_this._useDirectMapping) {
  109407. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109408. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109409. material.diffuseTexture = texture;
  109410. }
  109411. else {
  109412. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109413. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109414. material.reflectionTexture = texture;
  109415. }
  109416. // configure mesh
  109417. _this._mesh.material = material;
  109418. _this._mesh.parent = _this;
  109419. // optional configuration
  109420. if (options.clickToPlay) {
  109421. scene.onPointerUp = function () {
  109422. _this._videoTexture.video.play();
  109423. };
  109424. }
  109425. return _this;
  109426. }
  109427. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  109428. /**
  109429. * Gets the video texture being displayed on the sphere
  109430. */
  109431. get: function () {
  109432. return this._videoTexture;
  109433. },
  109434. enumerable: true,
  109435. configurable: true
  109436. });
  109437. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  109438. /**
  109439. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109440. * Also see the options.resolution property.
  109441. */
  109442. get: function () {
  109443. return this._material.fovMultiplier;
  109444. },
  109445. set: function (value) {
  109446. this._material.fovMultiplier = value;
  109447. },
  109448. enumerable: true,
  109449. configurable: true
  109450. });
  109451. /**
  109452. * Releases resources associated with this node.
  109453. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109454. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109455. */
  109456. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109457. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109458. this._videoTexture.dispose();
  109459. this._mesh.dispose();
  109460. this._material.dispose();
  109461. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109462. };
  109463. return VideoDome;
  109464. }(BABYLON.TransformNode));
  109465. BABYLON.VideoDome = VideoDome;
  109466. })(BABYLON || (BABYLON = {}));
  109467. //# sourceMappingURL=babylon.videoDome.js.map
  109468. var BABYLON;
  109469. (function (BABYLON) {
  109470. /**
  109471. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  109472. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  109473. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  109474. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109475. */
  109476. var PhotoDome = /** @class */ (function (_super) {
  109477. __extends(PhotoDome, _super);
  109478. /**
  109479. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  109480. * @param name Element's name, child elements will append suffixes for their own names.
  109481. * @param urlsOfPhoto defines the url of the photo to display
  109482. * @param options defines an object containing optional or exposed sub element properties
  109483. * @param onError defines a callback called when an error occured while loading the texture
  109484. */
  109485. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  109486. if (onError === void 0) { onError = null; }
  109487. var _this = _super.call(this, name, scene) || this;
  109488. _this._useDirectMapping = false;
  109489. /**
  109490. * Observable raised when an error occured while loading the 360 image
  109491. */
  109492. _this.onLoadErrorObservable = new BABYLON.Observable();
  109493. // set defaults and manage values
  109494. name = name || "photoDome";
  109495. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109496. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109497. if (options.useDirectMapping === undefined) {
  109498. _this._useDirectMapping = true;
  109499. }
  109500. else {
  109501. _this._useDirectMapping = options.useDirectMapping;
  109502. }
  109503. _this._setReady(false);
  109504. // create
  109505. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109506. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109507. // configure material
  109508. material.opacityFresnel = false;
  109509. material.useEquirectangularFOV = true;
  109510. material.fovMultiplier = 1.0;
  109511. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  109512. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  109513. if (onError) {
  109514. onError(message, exception);
  109515. }
  109516. });
  109517. _this.photoTexture.onLoadObservable.addOnce(function () {
  109518. _this._setReady(true);
  109519. });
  109520. // configure mesh
  109521. _this._mesh.material = material;
  109522. _this._mesh.parent = _this;
  109523. return _this;
  109524. }
  109525. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  109526. /**
  109527. * Gets or sets the texture being displayed on the sphere
  109528. */
  109529. get: function () {
  109530. return this._photoTexture;
  109531. },
  109532. set: function (value) {
  109533. if (this._photoTexture === value) {
  109534. return;
  109535. }
  109536. this._photoTexture = value;
  109537. if (this._useDirectMapping) {
  109538. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109539. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109540. this._material.diffuseTexture = this._photoTexture;
  109541. }
  109542. else {
  109543. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109544. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109545. this._material.reflectionTexture = this._photoTexture;
  109546. }
  109547. },
  109548. enumerable: true,
  109549. configurable: true
  109550. });
  109551. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  109552. /**
  109553. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109554. * Also see the options.resolution property.
  109555. */
  109556. get: function () {
  109557. return this._material.fovMultiplier;
  109558. },
  109559. set: function (value) {
  109560. this._material.fovMultiplier = value;
  109561. },
  109562. enumerable: true,
  109563. configurable: true
  109564. });
  109565. /**
  109566. * Releases resources associated with this node.
  109567. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109568. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109569. */
  109570. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109571. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109572. this._photoTexture.dispose();
  109573. this._mesh.dispose();
  109574. this._material.dispose();
  109575. this.onLoadErrorObservable.clear();
  109576. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109577. };
  109578. return PhotoDome;
  109579. }(BABYLON.TransformNode));
  109580. BABYLON.PhotoDome = PhotoDome;
  109581. })(BABYLON || (BABYLON = {}));
  109582. //# sourceMappingURL=babylon.photoDome.js.map
  109583. var BABYLON;
  109584. (function (BABYLON) {
  109585. BABYLON.Engine.prototype.createQuery = function () {
  109586. return this._gl.createQuery();
  109587. };
  109588. BABYLON.Engine.prototype.deleteQuery = function (query) {
  109589. this._gl.deleteQuery(query);
  109590. return this;
  109591. };
  109592. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  109593. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  109594. };
  109595. BABYLON.Engine.prototype.getQueryResult = function (query) {
  109596. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  109597. };
  109598. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  109599. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109600. this._gl.beginQuery(glAlgorithm, query);
  109601. return this;
  109602. };
  109603. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  109604. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109605. this._gl.endQuery(glAlgorithm);
  109606. return this;
  109607. };
  109608. BABYLON.Engine.prototype._createTimeQuery = function () {
  109609. var timerQuery = this.getCaps().timerQuery;
  109610. if (timerQuery.createQueryEXT) {
  109611. return timerQuery.createQueryEXT();
  109612. }
  109613. return this.createQuery();
  109614. };
  109615. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  109616. var timerQuery = this.getCaps().timerQuery;
  109617. if (timerQuery.deleteQueryEXT) {
  109618. timerQuery.deleteQueryEXT(query);
  109619. return;
  109620. }
  109621. this.deleteQuery(query);
  109622. };
  109623. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  109624. var timerQuery = this.getCaps().timerQuery;
  109625. if (timerQuery.getQueryObjectEXT) {
  109626. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  109627. }
  109628. return this.getQueryResult(query);
  109629. };
  109630. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  109631. var timerQuery = this.getCaps().timerQuery;
  109632. if (timerQuery.getQueryObjectEXT) {
  109633. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  109634. }
  109635. return this.isQueryResultAvailable(query);
  109636. };
  109637. BABYLON.Engine.prototype.startTimeQuery = function () {
  109638. var caps = this.getCaps();
  109639. var timerQuery = caps.timerQuery;
  109640. if (!timerQuery) {
  109641. return null;
  109642. }
  109643. var token = new BABYLON._TimeToken();
  109644. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109645. if (caps.canUseTimestampForTimerQuery) {
  109646. token._startTimeQuery = this._createTimeQuery();
  109647. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  109648. }
  109649. else {
  109650. if (this._currentNonTimestampToken) {
  109651. return this._currentNonTimestampToken;
  109652. }
  109653. token._timeElapsedQuery = this._createTimeQuery();
  109654. if (timerQuery.beginQueryEXT) {
  109655. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109656. }
  109657. else {
  109658. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109659. }
  109660. this._currentNonTimestampToken = token;
  109661. }
  109662. return token;
  109663. };
  109664. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  109665. var caps = this.getCaps();
  109666. var timerQuery = caps.timerQuery;
  109667. if (!timerQuery || !token) {
  109668. return -1;
  109669. }
  109670. if (caps.canUseTimestampForTimerQuery) {
  109671. if (!token._startTimeQuery) {
  109672. return -1;
  109673. }
  109674. if (!token._endTimeQuery) {
  109675. token._endTimeQuery = this._createTimeQuery();
  109676. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  109677. }
  109678. }
  109679. else if (!token._timeElapsedQueryEnded) {
  109680. if (!token._timeElapsedQuery) {
  109681. return -1;
  109682. }
  109683. if (timerQuery.endQueryEXT) {
  109684. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  109685. }
  109686. else {
  109687. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  109688. }
  109689. token._timeElapsedQueryEnded = true;
  109690. }
  109691. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109692. var available = false;
  109693. if (token._endTimeQuery) {
  109694. available = this._getTimeQueryAvailability(token._endTimeQuery);
  109695. }
  109696. else if (token._timeElapsedQuery) {
  109697. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  109698. }
  109699. if (available && !disjoint) {
  109700. var result = 0;
  109701. if (caps.canUseTimestampForTimerQuery) {
  109702. if (!token._startTimeQuery || !token._endTimeQuery) {
  109703. return -1;
  109704. }
  109705. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  109706. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  109707. result = timeEnd - timeStart;
  109708. this._deleteTimeQuery(token._startTimeQuery);
  109709. this._deleteTimeQuery(token._endTimeQuery);
  109710. token._startTimeQuery = null;
  109711. token._endTimeQuery = null;
  109712. }
  109713. else {
  109714. if (!token._timeElapsedQuery) {
  109715. return -1;
  109716. }
  109717. result = this._getTimeQueryResult(token._timeElapsedQuery);
  109718. this._deleteTimeQuery(token._timeElapsedQuery);
  109719. token._timeElapsedQuery = null;
  109720. token._timeElapsedQueryEnded = false;
  109721. this._currentNonTimestampToken = null;
  109722. }
  109723. return result;
  109724. }
  109725. return -1;
  109726. };
  109727. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  109728. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  109729. };
  109730. // We also need to update AbstractMesh as there is a portion of the code there
  109731. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  109732. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  109733. this._isOccluded = false;
  109734. return;
  109735. }
  109736. var engine = this.getEngine();
  109737. if (engine.webGLVersion < 2) {
  109738. this._isOccluded = false;
  109739. return;
  109740. }
  109741. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  109742. this._isOccluded = false;
  109743. return;
  109744. }
  109745. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  109746. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  109747. if (isOcclusionQueryAvailable) {
  109748. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  109749. this._isOcclusionQueryInProgress = false;
  109750. this._occlusionInternalRetryCounter = 0;
  109751. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  109752. }
  109753. else {
  109754. this._occlusionInternalRetryCounter++;
  109755. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  109756. this._isOcclusionQueryInProgress = false;
  109757. this._occlusionInternalRetryCounter = 0;
  109758. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  109759. // if strict continue the last state of the object.
  109760. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  109761. }
  109762. else {
  109763. return;
  109764. }
  109765. }
  109766. }
  109767. var scene = this.getScene();
  109768. if (scene.getBoundingBoxRenderer) {
  109769. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  109770. if (!this._occlusionQuery) {
  109771. this._occlusionQuery = engine.createQuery();
  109772. }
  109773. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  109774. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  109775. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  109776. this._isOcclusionQueryInProgress = true;
  109777. }
  109778. };
  109779. })(BABYLON || (BABYLON = {}));
  109780. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  109781. var BABYLON;
  109782. (function (BABYLON) {
  109783. /**
  109784. * Class used to generate noise procedural textures
  109785. */
  109786. var NoiseProceduralTexture = /** @class */ (function (_super) {
  109787. __extends(NoiseProceduralTexture, _super);
  109788. /**
  109789. * Creates a new NoiseProceduralTexture
  109790. * @param name defines the name fo the texture
  109791. * @param size defines the size of the texture (default is 256)
  109792. * @param scene defines the hosting scene
  109793. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109794. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109795. */
  109796. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109797. if (size === void 0) { size = 256; }
  109798. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109799. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109800. _this._time = 0;
  109801. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109802. _this.brightness = 0.2;
  109803. /** Defines the number of octaves to process */
  109804. _this.octaves = 3;
  109805. /** Defines the level of persistence (0.8 by default) */
  109806. _this.persistence = 0.8;
  109807. /** Gets or sets animation speed factor (default is 1) */
  109808. _this.animationSpeedFactor = 1;
  109809. _this._updateShaderUniforms();
  109810. return _this;
  109811. }
  109812. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109813. var scene = this.getScene();
  109814. if (!scene) {
  109815. return;
  109816. }
  109817. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109818. this.setFloat("brightness", this.brightness);
  109819. this.setFloat("persistence", this.persistence);
  109820. this.setFloat("timeScale", this._time);
  109821. };
  109822. NoiseProceduralTexture.prototype._getDefines = function () {
  109823. return "#define OCTAVES " + (this.octaves | 0);
  109824. };
  109825. /** Generate the current state of the procedural texture */
  109826. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109827. this._updateShaderUniforms();
  109828. _super.prototype.render.call(this, useCameraPostProcess);
  109829. };
  109830. /**
  109831. * Serializes this noise procedural texture
  109832. * @returns a serialized noise procedural texture object
  109833. */
  109834. NoiseProceduralTexture.prototype.serialize = function () {
  109835. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109836. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109837. return serializationObject;
  109838. };
  109839. /**
  109840. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109841. * @param parsedTexture defines parsed texture data
  109842. * @param scene defines the current scene
  109843. * @param rootUrl defines the root URL containing noise procedural texture information
  109844. * @returns a parsed NoiseProceduralTexture
  109845. */
  109846. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109847. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109848. return texture;
  109849. };
  109850. return NoiseProceduralTexture;
  109851. }(BABYLON.ProceduralTexture));
  109852. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109853. })(BABYLON || (BABYLON = {}));
  109854. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109855. var __assign = (this && this.__assign) || function () {
  109856. __assign = Object.assign || function(t) {
  109857. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109858. s = arguments[i];
  109859. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109860. t[p] = s[p];
  109861. }
  109862. return t;
  109863. };
  109864. return __assign.apply(this, arguments);
  109865. };
  109866. var BABYLON;
  109867. (function (BABYLON) {
  109868. /**
  109869. * This can helps recording videos from BabylonJS.
  109870. * This is based on the available WebRTC functionalities of the browser.
  109871. *
  109872. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109873. */
  109874. var VideoRecorder = /** @class */ (function () {
  109875. /**
  109876. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109877. * a video file.
  109878. * @param engine Defines the BabylonJS Engine you wish to record
  109879. * @param options Defines options that can be used to customized the capture
  109880. */
  109881. function VideoRecorder(engine, options) {
  109882. if (options === void 0) { options = null; }
  109883. if (!VideoRecorder.IsSupported(engine)) {
  109884. throw "Your browser does not support recording so far.";
  109885. }
  109886. var canvas = engine.getRenderingCanvas();
  109887. if (!canvas) {
  109888. throw "The babylon engine must have a canvas to be recorded";
  109889. }
  109890. this._canvas = canvas;
  109891. this._canvas.isRecording = false;
  109892. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109893. var stream = this._canvas.captureStream(this._options.fps);
  109894. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109895. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109896. this._mediaRecorder.onerror = this._handleError.bind(this);
  109897. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109898. }
  109899. /**
  109900. * Returns wehther or not the VideoRecorder is available in your browser.
  109901. * @param engine Defines the Babylon Engine to check the support for
  109902. * @returns true if supported otherwise false
  109903. */
  109904. VideoRecorder.IsSupported = function (engine) {
  109905. var canvas = engine.getRenderingCanvas();
  109906. return (!!canvas && typeof canvas.captureStream === "function");
  109907. };
  109908. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109909. /**
  109910. * True wether a recording is already in progress.
  109911. */
  109912. get: function () {
  109913. return !!this._canvas && this._canvas.isRecording;
  109914. },
  109915. enumerable: true,
  109916. configurable: true
  109917. });
  109918. /**
  109919. * Stops the current recording before the default capture timeout passed in the startRecording
  109920. * functions.
  109921. */
  109922. VideoRecorder.prototype.stopRecording = function () {
  109923. if (!this._canvas || !this._mediaRecorder) {
  109924. return;
  109925. }
  109926. if (!this.isRecording) {
  109927. return;
  109928. }
  109929. this._canvas.isRecording = false;
  109930. this._mediaRecorder.stop();
  109931. };
  109932. /**
  109933. * Starts recording the canvas for a max duration specified in parameters.
  109934. * @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.
  109935. * @param maxDuration Defines the maximum recording time in seconds.
  109936. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109937. * @return a promise callback at the end of the recording with the video data in Blob.
  109938. */
  109939. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109940. var _this = this;
  109941. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109942. if (maxDuration === void 0) { maxDuration = 7; }
  109943. if (!this._canvas || !this._mediaRecorder) {
  109944. throw "Recorder has already been disposed";
  109945. }
  109946. if (this.isRecording) {
  109947. throw "Recording already in progress";
  109948. }
  109949. if (maxDuration > 0) {
  109950. setTimeout(function () {
  109951. _this.stopRecording();
  109952. }, maxDuration * 1000);
  109953. }
  109954. this._fileName = fileName;
  109955. this._recordedChunks = [];
  109956. this._resolve = null;
  109957. this._reject = null;
  109958. this._canvas.isRecording = true;
  109959. this._mediaRecorder.start(this._options.recordChunckSize);
  109960. return new Promise(function (resolve, reject) {
  109961. _this._resolve = resolve;
  109962. _this._reject = reject;
  109963. });
  109964. };
  109965. /**
  109966. * Releases internal resources used during the recording.
  109967. */
  109968. VideoRecorder.prototype.dispose = function () {
  109969. this._canvas = null;
  109970. this._mediaRecorder = null;
  109971. this._recordedChunks = [];
  109972. this._fileName = null;
  109973. this._resolve = null;
  109974. this._reject = null;
  109975. };
  109976. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109977. if (event.data.size > 0) {
  109978. this._recordedChunks.push(event.data);
  109979. }
  109980. };
  109981. VideoRecorder.prototype._handleError = function (event) {
  109982. this.stopRecording();
  109983. if (this._reject) {
  109984. this._reject(event.error);
  109985. }
  109986. else {
  109987. throw new event.error;
  109988. }
  109989. };
  109990. VideoRecorder.prototype._handleStop = function () {
  109991. this.stopRecording();
  109992. var superBuffer = new Blob(this._recordedChunks);
  109993. if (this._resolve) {
  109994. this._resolve(superBuffer);
  109995. }
  109996. window.URL.createObjectURL(superBuffer);
  109997. if (this._fileName) {
  109998. BABYLON.Tools.Download(superBuffer, this._fileName);
  109999. }
  110000. };
  110001. VideoRecorder._defaultOptions = {
  110002. mimeType: "video/webm",
  110003. fps: 25,
  110004. recordChunckSize: 3000
  110005. };
  110006. return VideoRecorder;
  110007. }());
  110008. BABYLON.VideoRecorder = VideoRecorder;
  110009. })(BABYLON || (BABYLON = {}));
  110010. //# sourceMappingURL=babylon.videoRecorder.js.map
  110011. var BABYLON;
  110012. (function (BABYLON) {
  110013. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  110014. if (replace === void 0) { replace = false; }
  110015. // Dispose existing light in replace mode.
  110016. if (replace) {
  110017. if (this.lights) {
  110018. for (var i = 0; i < this.lights.length; i++) {
  110019. this.lights[i].dispose();
  110020. }
  110021. }
  110022. }
  110023. // Light
  110024. if (this.lights.length === 0) {
  110025. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  110026. }
  110027. };
  110028. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  110029. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  110030. if (replace === void 0) { replace = false; }
  110031. if (attachCameraControls === void 0) { attachCameraControls = false; }
  110032. // Dispose existing camera in replace mode.
  110033. if (replace) {
  110034. if (this.activeCamera) {
  110035. this.activeCamera.dispose();
  110036. this.activeCamera = null;
  110037. }
  110038. }
  110039. // Camera
  110040. if (!this.activeCamera) {
  110041. var worldExtends = this.getWorldExtends();
  110042. var worldSize = worldExtends.max.subtract(worldExtends.min);
  110043. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  110044. var camera;
  110045. var radius = worldSize.length() * 1.5;
  110046. // empty scene scenario!
  110047. if (!isFinite(radius)) {
  110048. radius = 1;
  110049. worldCenter.copyFromFloats(0, 0, 0);
  110050. }
  110051. if (createArcRotateCamera) {
  110052. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  110053. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  110054. arcRotateCamera.wheelPrecision = 100 / radius;
  110055. camera = arcRotateCamera;
  110056. }
  110057. else {
  110058. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  110059. freeCamera.setTarget(worldCenter);
  110060. camera = freeCamera;
  110061. }
  110062. camera.minZ = radius * 0.01;
  110063. camera.maxZ = radius * 1000;
  110064. camera.speed = radius * 0.2;
  110065. this.activeCamera = camera;
  110066. var canvas = this.getEngine().getRenderingCanvas();
  110067. if (attachCameraControls && canvas) {
  110068. camera.attachControl(canvas);
  110069. }
  110070. }
  110071. };
  110072. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  110073. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  110074. if (replace === void 0) { replace = false; }
  110075. if (attachCameraControls === void 0) { attachCameraControls = false; }
  110076. this.createDefaultLight(replace);
  110077. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  110078. };
  110079. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  110080. if (pbr === void 0) { pbr = false; }
  110081. if (scale === void 0) { scale = 1000; }
  110082. if (blur === void 0) { blur = 0; }
  110083. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  110084. if (!environmentTexture) {
  110085. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  110086. return null;
  110087. }
  110088. if (setGlobalEnvTexture) {
  110089. if (environmentTexture) {
  110090. this.environmentTexture = environmentTexture;
  110091. }
  110092. }
  110093. // Skybox
  110094. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  110095. if (pbr) {
  110096. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  110097. hdrSkyboxMaterial.backFaceCulling = false;
  110098. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  110099. if (hdrSkyboxMaterial.reflectionTexture) {
  110100. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110101. }
  110102. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  110103. hdrSkyboxMaterial.disableLighting = true;
  110104. hdrSkyboxMaterial.twoSidedLighting = true;
  110105. hdrSkybox.infiniteDistance = true;
  110106. hdrSkybox.material = hdrSkyboxMaterial;
  110107. }
  110108. else {
  110109. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  110110. skyboxMaterial.backFaceCulling = false;
  110111. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  110112. if (skyboxMaterial.reflectionTexture) {
  110113. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110114. }
  110115. skyboxMaterial.disableLighting = true;
  110116. hdrSkybox.infiniteDistance = true;
  110117. hdrSkybox.material = skyboxMaterial;
  110118. }
  110119. return hdrSkybox;
  110120. };
  110121. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  110122. if (BABYLON.EnvironmentHelper) {
  110123. return new BABYLON.EnvironmentHelper(options, this);
  110124. }
  110125. return null;
  110126. };
  110127. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  110128. if (webVROptions === void 0) { webVROptions = {}; }
  110129. return new BABYLON.VRExperienceHelper(this, webVROptions);
  110130. };
  110131. })(BABYLON || (BABYLON = {}));
  110132. //# sourceMappingURL=babylon.sceneHelpers.js.map
  110133. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  110134. 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};"};
  110135. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  110136. globalObject["BABYLON"] = BABYLON;
  110137. //backwards compatibility
  110138. if(typeof earcut !== 'undefined') {
  110139. globalObject["Earcut"] = {
  110140. earcut: earcut
  110141. };
  110142. }
  110143. return BABYLON;
  110144. });